//Start - global vars
reg_server = "https://member.webmd.com/default.aspx?";
reg_api = "https://regapi.webmd.com";
//End - global vars

// Create namespace for exchanges code
if (!window.webmd) { webmd = {}; }
if (!webmd.p) { webmd.p = {}; }
webmd.p.exch = {};

    if (inviteToken != '') {
	   setTimeout('ShowAdminInvitation()', 1000);
    }

    function ShowAdminInvitation() {
       try {
	   ShowModal(image_server_url + '/webmd/consumer_assets/site_images/exchange/modals/modal_admin_invitation.html','415');
	   return false;
       }
       catch (ex) {
	   displayException('ShowAdminInvitation', ex);
       }
    }


/* Base Exchange Services */
    var services = {};
    services.base = {
        beforeSend: function(xhr) {xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');},
        cache: false,
        dataType: 'json',
        error: function(request, status, errorThrown){},
        timeout: 10000,
        type: 'GET'
    };
    services.leftnav = function(){
        var overrides = {data: {name: '"'+space_name+'"'}, url: '/api/space/SpaceService.asmx/GetNavLinks'};
        return $.extend({}, services.base, overrides);
    };
    services.newsletter = function(){
        var overrides = {beforeSend: null, data: {nls: channelIdMap(priTopId).newsletter.sub}, error: null, success: null, url: reg_api+'/regapi.svc/jsonp/subscribe?callback=?'};
        return $.extend({}, services.base, overrides);
    };
    services.watchlist = {
        add: function(){
            var overrides = {beforeSend: null, type: 'POST', url: '/api/watchlist/watchlistapi.svc/add'};
            return $.extend({}, services.base, overrides);
        },
        get: function(){
            /* {count} values -1 through 4 are valid, -1 shows all */
            var overrides = {data: {count: null}, url: '/api/watchlist/watchlistapi.svc/wl'};
            return $.extend({}, services.base, overrides);
        },
        exists: function(){
            var overrides = {beforeSend: null, url: '/api/watchlist/watchlistapi.svc/iswlobj'};
            return $.extend({}, services.base, overrides);
        },
        update: function(){
            var overrides = {beforeSend: null, type: 'POST', url: '/api/watchlist/watchlistapi.svc/update'};
            return $.extend({}, services.base, overrides);
        }
    };

/** BEGIN Exchange Left-nav and Watchlist
 * Requires space_id and priTopId(channel id)
 */
(function($) {
    /* Global vars for Left-nav and Watchlist */
    var $cms, $loading;
    var Data = {};
    // var hostPrefix = 'http://'+prefix+'.'+domain;
    var hostPrefix = 'http://exchanges.webmd.com';
    /**
     * Exchanges Left-nav
     * Name webmd.p.exch.leftNav
     * Public methods: .refresh()
     */
    $.fn.exchLeftNav = function(opts){
        var $data = null;
        var $this = $(this);
        var defaults = {
            data: null,
            leftNavId: '#'+$this.attr('id'),
            sectionClass: 'section',
            sectionTypes: ['community', 'informed', 'watch', 'cms'],
            subsectionClass: 'subsection'
        };
        var options = $.extend(defaults, opts || {});
        $loading = $this.find('img') || null;
        /* Get CMS content before any other manipulation is done */
        $cms = $this.children('.'+options.sectionClass).remove().addClass('cms').css({display: 'block'}) || null;
        if($this.length){
            getServiceData();
        }
        this.refresh = function(){
            refresh();
        };
        function getServiceData(){
            var overrides = {
                error: function(request, status, errorThrown){
                    initialize();
                },
                success: function(data){
                    $data = data;
                    initialize();
                }
            };
            var call = $.extend({}, services.leftnav(), overrides);
            $.ajax(call);
        }
        function initialize(){
            if($data){
                processData();
            }
            initSections();
            showSections();
			initDigestPromo();
        }
        function initSections(){
            var length = options.sectionTypes.length;
            for(var i=0; i<length; i++){
                $this.append(makeSectionObject(options.sectionTypes[i]));
            }
            Behavior.add($this);
			if(webmd.url.getParam('retsub')){
				var digLink = $("a[title*='My Email Digests']","#ex-lr-nav")
				digLink.trigger('click');
			}
        }
        function makeSectionObject(sectionType){
            var data = (sectionType == 'community') ? $data : Data.makeSection(sectionType);
            return Section.buildSection(sectionType, data);
        }
        function processData(){
            $data = Data.clean($data.d, ['appid', 'name', 'qualifiername', 'url']);
                        /* manually tagging these, the .appid in data object is not a reliable data point */
            var length = $data.length;
            for(var i=0; i<length; i++){
                var tag = null;
                var tData = $data[i];
                var name = tData.name.toLowerCase();
                switch(name) {
                    case 'discussions': tag = 2; break;
                    case 'tips': tag = 3; break;
                    case 'resources': tag = 11; break;
                    case 'about this community': tag = 13; break;
                    case 'expert directory': tag = 17; break;
                    case 'my community profile': tag = tData.appid; break;
                    case 'manage this community': tag = tData.appid; break;
                    case 'sponsor directory': tag = 25; break;
                    case 'member directory': tag = 15; break;
                    case 'my exchange profile': tag = 14; break;
                }
                if(tag){
                    tData.bi = BI('community', tag);
                }
            }
        }
        function refresh(){
            var $obj, length = options.sectionTypes.length, sectionType;
            for(var i=0; i<length; i++){
                sectionType = options.sectionTypes[i];
                if (sectionType == 'informed' || sectionType == 'watch'){
                    $obj = makeSectionObject(sectionType);
                    $this.find('.'+options.sectionClass+'.'+sectionType).replaceWith($obj);
                }
            }
        }
        function showSections(){
            if($loading.length){
                $loading = $loading.remove();
            }
        }
		function initDigestPromo(){
			if(isLoggedInWebMD()){
				//when user is logged in check for registered digests
				var callback = function(data){
					if(data.length == 0){
						createDigestPromo();
					}
				};
				Section.buildSubAjax('emails', callback);
			}else{
				createDigestPromo();
			}
			$('.promo_close_btn a').live('click', function(e){
				e.preventDefault();
				webmd.p.exch.overlay.close();
			});
		}

		// new 09.27.11 update for non logged in user - rdh
		if(typeof postId != "undefined" && !webmd.cookie.exists("WBMD_AUTH")) {
			var userId = webmd.url.getParam("user");
			watchListCountNLI(userId);
		}
		function watchListCountNLI(userId) {
			try {
				if(postId && userId) {
					$.ajax({
						dataType: 'application/json',
						type: 'POST',
						contentType: 'application/json; charset=UTF-8',
						data: webmd.json.stringify({"postId": postId, "userId": userId}),
						url: "/api/forums/ForumApi.svc/json/MarkAllRead",
						timeout:10000,
						success: function(data) {
							webmd.debug("Success!");
							webmd.debug(data);
						},
						error: function(data) {
							webmd.debug('Error');
						}
					});
				}
			} catch (ex) {
				displayException('watchListCount', ex);
			}
		}

		// new 07.20.11 rdh
		function watchListCount (data) {
			try {
				if(postId || postId != '') {
					$(data).each(function() {
						var userid = webmd.p.exch.lbmonitor.getUserId();
						if (this.objecttype == "forum" && this.objectid == postId) {
							$.ajax({
								dataType: 'application/json',
								type: 'POST',
								contentType: 'application/json; charset=UTF-8',
								data: webmd.json.stringify({"postId": postId, "userId": userid}),
								url: "/api/forums/ForumApi.svc/json/MarkAllRead",
								timeout:10000,
								success: function(data) {
									webmd.debug("Success!");
									webmd.debug(data);
								},
								error: function(data) {
									webmd.debug('Error');
								}
							});
						}
					});
				}
			} catch (ex) {
				displayException('watchListCount', ex);
			}
		}

		function createDigestPromo(){
			var cookiePass=checkCookie();
			if(s_sponsor_program == '' && cookiePass==true ){
				$targetX=$('#ex-lr-nav').offset().left+110+'px';
				$promoFade='';
				$promoElm=$(document.createElement('div'))
					.attr('id','promo_rdr')
					.css({
						top: function(index, value) {return $('#ex-lr-nav').offset().top+10+'px';}
					})
					.mouseover(function() { clearTimeout($promoFade); })
					.mouseout(function() { $promoFade=setTimeout( "$('#promoCloseButn').trigger('click');", 7000 ); })
					.append('<h4>Daily Email Digests</h4><p>Get the latest content from your favorite Communities delivered to you every morning!</p><p class="learn_more_link"><a href="#">Learn More</a></p>')
					.prepend('<p id="promo_close"><a id="promoCloseButn" href="#">Close</a></p>').bind('click', function(e){
						e.preventDefault();
						closePromo();
					});
				$('#ContentPane24').append($promoElm);
				$('p.learn_more_link a').bind('click', function(e){
					e.preventDefault();
					webmd.p.exch.watchlist.controller.add({isModal: true, objType: 'promotion'});
				});
				$($promoElm).animate({
						left: $targetX
					}, 500, function() {
						$promoFade=setTimeout( "$('#promoCloseButn').trigger('click');", 7000 );
					});
			}
		}

		function checkCookie(){
			//checks to see if session cookie exists, then checks to see how many times it's been shown in a year
			var digestSession = webmd.cookie.get('digest_session');
			if(digestSession == ''){
				webmd.cookie.set('digest_session', 1);
				var digestCookie=webmd.cookie.get('digest_promo');
				if (digestCookie==''){
					webmd.cookie.set('digest_promo', 1, {expires:365});
					return true;
				}else{
					if(digestCookie < 3){
						digestCookie++
						webmd.cookie.set('digest_promo', digestCookie, {expires:365});
						return true;
					}else{
						return false;
					}
				}
			}else{
				return false;
			}
		}
		function closePromo(){
			$($promoElm).animate({
				opacity: 'toggle',
				left: '-600px'
			  }, 500);
		}

        /* Behaviors for accordion-style sections of webmd.p.exch.leftNav */
        var Behavior = {
            options: {
                current: null,
                previous: 300,
                speed: 300
            },
            add: function($obj){
                var self = this;
                bind();
                function animate($obj){
                    if($obj.hasClass('open')){
                        $obj.prev('h3').removeClass('active-toggle');
                        $obj.animate({height: 0, opacity: 0}, self.options.speed, function(){
                            $obj.removeClass('open').addClass('closed');
                        });
                    } else {
                        $(options.leftNavId).find('.active-toggle').not($obj).removeClass('active-toggle');
                        $(options.leftNavId).find('.open').animate({height: 0, opacity: 0}, self.options.speed, function(){
                            $(this).removeClass('open').addClass('closed');
                        });
                        $obj.prev('h3').addClass('active-toggle');
                        $obj.animate({height: getHeight($obj), opacity: 1}, self.options.speed, function(){
                            $obj.removeClass('closed').addClass('open');
                        });
                    }
                }
                function bind(){
                    $obj.bind('exchLeftNav:animate', function(e, obj){
                        animate($(obj));
                    });
                    $obj.find('h3 a').live('click', function(e){
                        e.preventDefault();
                        var $link = $(this);
                        var $next = $link.parents('h3').next('.subsection');
                        if($next.hasClass('open')){
                            $obj.trigger('exchLeftNav:animate', $next);
                        } else {
                            getSub($link);
                        }
                    });
                }
                function getHeight($obj){
                    var c, cMarTop, cMarBot, cPadTop, cPadBot;
                    var cHeight = 0;
                    var children = $obj.children(':visible');
                    var length = children.length;
                    for(var i=0; i<length; i++){
                        c = $(children[i]);
                        cMarTop = c.css('marginTop');
                        cPadTop = c.css('paddingTop');
                        cPadBot = c.css('paddingBottom');
                        cHeight = cHeight + c.height() + ((cMarTop == 'auto') ? 0 : parseInt(cMarTop)) + ((cPadTop == 'auto') ? 0 : parseInt(cPadTop)) + ((cPadBot == 'auto') ? 0 : parseInt(cPadBot));
                        if(i == length-1){
                            cMarBot = c.css('marginBottom');
                            cHeight = cHeight + ((cMarBot == 'auto') ? 0 : parseInt(cMarBot));
                        }
                    }
                    return cHeight;
                }
                function getSub(obj){
                    var sectionType, subtype;
                    var $head = $(obj);
                    var $content = $head.parents().next('.'+options.subsectionClass);
                    subtype = $head.data('opts').subtype;
                    if(subtype == 'communities' || subtype == 'discussions' || subtype == 'emails'){
                        Section.buildSub($content, subtype);
                    } else {
                        sectionType = $.data($head[0], 'opts').type;
                        Section.buildSub($content, sectionType, Data.makeSub(sectionType));
                    }
                }
            }
        };
        /* Creates base data objects for each section */
        Data.makeSection = function(sectionType){
            var data = null;
            switch(sectionType) {
                case 'cms':
                    data = $cms;
                    break;
                case 'informed':
                    data = [{accordion: true, name: 'Staying Informed', subtype: sectionType, type: sectionType}];
                    break;
                case 'watch':
                    if(isLoggedInWebMD()){
                        data = [{accordion: true, name: 'My Communities', subtype: 'communities', type: sectionType},
                            {accordion: true, name: 'My Discussions', subtype: 'discussions', type: sectionType},
                            {accordion: true, name: 'My Email Digests', subtype: 'emails', type: sectionType}];
                    } else {
                        data = [{accordion: false, bi: BI(sectionType, 'wl'), methods: 'webmd.p.exch.requireLogin(); return false;', name: 'My Watchlist', type: sectionType}];
                    }
                    break;
                default:
                    break;
            }
            return data;
        };
        /* Creates Related Exchanges link, based on info from HE PRD1.2 appendix */
        Data.makeRelatedLink = function(){
            var title = 'Related ', url = hostPrefix+'/webmd-exchanges/';
            var map = spaceIdMap();
            if(map.relatedName){
                title += map.relatedName;
                title += ' Communities';
                url += map.relatedUrl;
                return Template.link({bi: BI('cms', '18'), el: 'li', name: title, url: url});
            } else {
                return null;
            }
        };
        /* Makes base subsection data for anything which is not sourced from a service call */
        Data.makeSub = function(type){
            var data = [];
            switch(type) {
                case 'informed':
                    /*var channel = channelIdMap(priTopId);*/
                    /* One-off change for Eye Health Newsletter serving, similar to fix in newsletter_exchange.js - should be a better long-term solution */
                    var channel = (s_asset_id == '091e9c5e808edeaa') ? channelIdMap(4051) : channelIdMap(priTopId);
                    if(channel.name){
                        var nlt = 'Newsletters';
                        channel.name = (channel.name.indexOf(nlt) == -1) ? channel.name : channel.name.replace(nlt, 'Daily');
                        data.push({name: 'Sign up for the ' + channel.name + ' Newsletter', objecttype: 'newsletter', url: '/'});
                    }
                    var digestData = {name: 'Sign up for the ' + space_title + ' Daily Email Digest', objecttype: 'email_digest', url: '/'};
                    if(space_invite_policy != 'InvitationRequired'){
                        data.push(digestData);
                        data.push({name: 'Learn More', objecttype: 'promotion', url: '/'});
                    }
                    break;
                default:
                    data = null;
                    break;
            }
            return data;
        };
        /* Builds sections/subsections for webmd.p.exch.leftNav based on Data returns from above, not used for CMS content */
        var Section = {
            /* If no entries in a subsection */
            blank: function(type){
                var msg;
                switch(type) {
                    case 'communities':
                        msg = 'You are not subscribed to any communities.'; break;
                    case 'discussions':
                        msg = 'You have no unread discussions.'; break;
                    case 'emails':
						if(space_invite_policy != 'InvitationRequired'){
                        	msg = '<a href="/" id="emailDigestSignup" onclick="wmdPageLink(\'he-nav-watchlist_7-1\'); return false;">Sign up for the '+space_title+' Daily Email Digest</a>';
						} else {
							msg = 'There are no email digests available.'}; break;
                    case 'informed':
                        msg = 'There are no newsletters or email digests available.'; break;
                    default:
                        break;
                }
                return msg;
            },
            /* Builds section DOM */
            buildSection: function(sectionType, data){
                var self = this;
                if(sectionType == 'cms'){
                    var related = Data.makeRelatedLink();
                    if(related){
                        data = data.prepend(related);
                    }
                    data = data.remove();
                    return data.data('opts', {accordion: false, type: 'cms'});
                } else {
                    var $section, i, length, tData;
                    var accordion = false, bi = null, wrapEl = 'ul';
                    if(sectionType == 'community'){
                        var $homelink = Template.link({bi: BI(sectionType, 'Home'), el: 'li', name: 'Home', url: hostPrefix+'/'+space_name});
                    }
                    if(data == null){
                        if($homelink){
                            $section = Template.section({accordion: accordion, className: options.sectionClass, el: wrapEl, type: sectionType});
                            $section = self.checkForActive($section.append($homelink));
                            return $section.data('opts', {accordion: accordion, type: sectionType});
                        }
                    } else {
                        length = data.length;
                        for(i=0; i<length; i++){
                            if(data[i]['accordion']){
                                accordion = true;
                                wrapEl = 'div';
                                break;
                            }
                        }
                        $section = Template.section({accordion: accordion, className: options.sectionClass, el: wrapEl, type: sectionType});
                        if($homelink){
                            $section.append($homelink);
                        }
                        for(i=0; i<length; i++){
                            tData = data[i];
                            tData.el = (tData.accordion) ? 'h3' : 'li';
                            $section.append(Template.link(tData));
                            /* Appends sub container if heading is accordion-style */
                            if(tData.accordion){
                                var $sub = Template.subsection({className: options.subsectionClass, el: 'div', type: tData.subtype}).css({display: 'block', height: 0, opacity: 0});
                                $section.append($sub);
                            }
                        }
                        $section = self.checkForActive($section);
                        return $section.data('opts', {accordion: accordion, type: sectionType});
                    }
                }
            },
            /* Builds subsection DOM */
            buildSub: function($el, sectionType, data){
                var self = this;
                if(data == undefined){
                    var callback = function(data){
                        self.buildSub($el, sectionType, data);
                    };
                    self.buildSubAjax(sectionType, callback);
                } else {
                    var $links = {}, $obj = $([]);
                    var comCount = 0, discCount = 0, emailCount = 0, infCount = 0;
                    var length = data.length;
                    for(var i=0; i<length; i++){
                        var tData = data[i];
                        tData.name = (tData.title) ? tData.title : tData.name;
                        tData.spon = self.getSponsored(tData);
                        if(sectionType == 'communities' && tData.objecttype.indexOf('space') != -1 && comCount < self.options.numLinks){
                            ++comCount;
                            tData.bi = BI(sectionType, comCount);
                            tData.truncate = false;
                            $links.all = {bi: BI(sectionType, 'sa'), state: 'default'};
                            $links.edit = {bi: BI(sectionType, 'e'), state: 'edit'};
                            $obj = $obj.add(Template.sublink(tData));
                        } else if(sectionType == 'discussions' && tData.objecttype.indexOf('forum') != -1 && discCount < self.options.numLinks){
                            ++discCount;
                            tData.bi = BI(sectionType, discCount);
                            tData.count = tData.miscdata || '';
                            tData.truncate = true;
                            $links.all = {bi: BI(sectionType, 'sa'), state: 'default'};
                            $links.edit = {bi: BI(sectionType, 'e'), state: 'edit'};
                            $obj = $obj.add(Template.sublink(tData));
                        } else if (sectionType == 'emails' && tData.objecttype == 'email_digest' && emailCount < self.options.numLinks){
                            ++emailCount;
                            tData.bi = BI(sectionType, emailCount);
                            tData.truncate = false;
                            $links.all = {bi: BI(sectionType, 'sa'), state: 'default'};
                            $links.edit = {bi: BI(sectionType, 'e'), state: 'edit'};
                            $obj = $obj.add(Template.sublink(tData));
                        } else if (sectionType == 'informed'){
                            ++infCount;
                            tData.bi = BI(sectionType, infCount);
                            tData.methods = ' return false;';
                            tData.truncate = false;
                            var $template = $(Template.sublink(tData));
                            $template = $template.data('objecttype', tData.objecttype).bind('click', function(e){
                                e.preventDefault();
                                var otype = $.data(this, 'objecttype');
                                webmd.p.exch.watchlist.controller.add({isModal: true, objType: otype});
                            });
							if($template.data('objecttype')=='promotion'){
								$template.attr('class','learn_more_link');
							}
                            $obj = $obj.add($template);
                        }
                        tData = null;
                    }
                    if($obj.length && (comCount > 0 || discCount > 0 || emailCount > 0 || infCount > 0)){
                        $obj = $obj.add(Template.editlinks($links, sectionType));
                    } else {
                        $obj = $obj.add('<p>'+self.blank(sectionType)+'</p>');
						if(sectionType == 'emails' && space_invite_policy != 'InvitationRequired'){
							var $links = $obj.find('a');
                             $($links[0]).bind('click', function(e){
                                e.preventDefault();
                                webmd.p.exch.watchlist.controller.add({isModal: true, objType: 'email_digest'});
                            });
						}
                    }
                    $el.html($obj);
                    $(options.leftNavId).trigger('exchLeftNav:animate', $el);
					if(webmd.url.getParam('retsub')){
						$($obj).find('a:last').trigger('click');
					}
                }
            },
            /* Handles service calls for subsection data, called from Section.buildSub() */
            buildSubAjax: function(sectionType, callback){
                var self = this;


                var overrides = {
                    data: {count: self.options.count},
                    success: function(data){
                        data = data.Entries;
                        if(data){
                            data = Data.clean(data, ['alerttype', 'id', 'miscdata', 'name', 'objecttype', 'qualifiername', 'title', 'url','objectid']);
			    watchListCount(data); // new 07.20.11 rdh
                            callback(data);
                        } else {
                            return null;
                        }
                    }
                };
                var call = $.extend({}, services.watchlist.get(), overrides);
                $.ajax(call);
            },
            /* Checks for active visual state */
            checkForActive: function($obj){
                var $links = $obj.find('a');
                var linkLength = $links.length;
                for(var i=0; i<linkLength; i++){
                    var $link = $($links[i]);
                    if($link.attr('title') == 'My Watchlist'){
                        $link.css({fontWeight: 'bold'});
                    }
                    if($link.attr('href').split('.com')[1] == location.href.split('.com')[1]){
                        $($link[0].parentNode).addClass('active');
                    } else {
                        $($link[0].parentNode).removeClass('active');
                    }
                }
                return $obj;
            },
            getSponsored: function(data){
                var sponsored = false;
                if(data.objecttype){
                    sponsored = !(data.objecttype.indexOf('spon_') == -1);
                }
                if(data.qualifiername != undefined && !sponsored){
                    sponsored = !(data.qualifiername.indexOf('spon_') == -1);
                }
                return sponsored;
            },
            options: {
                /*** TEMPORARY FIX until count is honored by service ***/
                /* Count will then be changed to 4, numLinks check may be deprecated */
                count: -1,
                /*** ***/
                numLinks: 4
            }
        };
        /* Templates used to build left-nav components */
        var Template = {
            editlinks: function(obj, sectionType){
                var bi;
                var s = '<div class="edit">';
                var methods = function(link){
                    bi = (link.bi) ? link.bi : '';
                    return bi+'webmd.p.exch.watchlist.controller.refresh(\''+link.state+'\',\''+sectionType+'\',this); return false;';
                };
                if(obj.all){
                    s += '<a href="/" onclick="'+methods(obj.all)+'">See All</a>';
                }
                if(obj.all && obj.edit){s += '|';}
                if(obj.edit){
                    s += '<a href="/" onclick="'+methods(obj.edit)+'">Edit</a>';
                }
                return s;
            },
            link: function(obj){
                var bi = (obj.bi) ? obj.bi : '';
                var methods = (obj.methods) ? obj.methods : '';
                var link = $('<a href="'+((obj.url) ? obj.url : '/')+'" onclick="'+bi+methods+'" title="'+obj.name+'">'+obj.name+'</a>').data('opts', obj);
                return $('<'+obj.el+'></'+obj.el+'>').append(link);
            },
            section: function(obj){
                var display = (obj.type == 'informed' && channelIdMap(priTopId).name == null && space_invite_policy == 'InvitationRequired') ? 'none' : 'block';
                return $('<'+obj.el+' class="'+obj.className+' '+obj.type+'" style="display: '+display+'"></'+obj.el+'>').data('opts', obj);
            },
            sublink: function(obj){
                var self = this;
                var bi = (obj.bi) ? obj.bi : '';
                var count = (obj.count) ? '('+obj.count+')' : '';
                var methods = (obj.methods) ? obj.methods : '';
                var spon = (obj.spon) ? '<br/><span class="sponsored">Sponsored</span>' : '';
                var name = (obj.truncate) ? self.truncate(obj.name) : obj.name;
                return $('<a href="'+obj.url+'" onclick="'+bi+methods+'" title="'+name+'">'+name+' '+count+spon+'</a>').data('opts', obj);
            },
            subsection: function(obj){
                return $('<'+obj.el+' class="'+obj.className+' '+obj.type+'"></'+obj.el+'>').data('opts', obj);
            },
            truncate: function(string, length){
                if(!length){ length = 14; }
                if (string != null) {
                return (length <= string.length) ? string.slice(0, length)+'...' : string;
		}
            }
        };
        return this;
    };

    /**
     * Exchanges Watchlist Controller
     * Name webmd.p.exch.watchlist.controller
     * Public methods: .add() .close(), .open(), .refresh(), .save()
     */
    $.fn.watchlistController = function(opts){
        var defaults = {
            changes: {},
            hasOverlay: null,
            modeName: {edit: 'edit', standard: 'default'},
            msg: {
                none: 'There have been no changes to your Watchlist.',
                saved: 'Your updates have been saved!'
            },
            saved: false
        };
        var options = $.extend(defaults, opts || {});
        init();

        /* common opts: alert (alertType), id (space_id or item id), miscData, objType
        * optional opts: isModal (evals whether to use modal impl. or vanilla service call), error, success */
        this.add = function(opts){ evaluateAddType(opts) };
        this.change = function(id, alertType, isDelete){
            addChange(id, alertType, isDelete);
        };
        this.close = function(){ close() };
        /* requires opts: id (objId), type (objType)
        * optional opts: error, success */
        this.exists = function(opts){ entryExists(opts) };
        this.open = function(mode, type){
            refresh((mode ? mode : 'default'), (type ? type : 'communities'));
        };
        this.refresh = function(mode, type){ refresh(mode, type) };
        this.save = function(mode, type){
			saveChanges(mode, type);
			//return to subscriptions page
			if(webmd.url.getParam('retsub')){
				var env = window.location.host.split('.')[1]
				env = (env != 'webmd')? 'member.'+env : 'member';
				window.location.href="https://"+env+".webmd.com/subscriptions.aspx";
			}
		};

        function addChange(id, alertType, isDelete){
            if(!options.changes[id]){
                options.changes[id] = {};
            }
            options.changes[id].alertType = alertType;
            options.changes[id].isDelete = isDelete;
        }
        function addEntry(opts){
            if(opts.objType == 'email_digest' || opts.objType == 'forum' || opts.objType == 'spon_forum') {
                opts.qname = (space_type == 'PublicSponsored') ? 'spon_space_id' : 'space_id';
                opts.qval = space_id;
            }
            var overrides = {
                data: { alert: opts.alert, id: opts.id, miscdata: opts.miscData, objtype: opts.objType, qname: opts.qname, qval: opts.qval },
                error: opts.error,
                success: opts.success
            };
            var call = $.extend({}, services.watchlist.add(), overrides);
            $.ajax(call);
        }
        function addEntryNewsletter(opts){
            var overrides = {
                error: opts.error,
                success: opts.success
            };
            var call = $.extend({}, services.newsletter(), overrides);
            $.ajax(call);
        }
        function close(){
            clearChanges();
            options.saved = false;
            if(options.hasOverlay){
                webmd.p.exch.watchlist.overlay.hide();
            }
			//return to subscriptions page
			if(webmd.url.getParam('retsub')){
				var env = window.location.host.split('.')[1]
				env = (env != 'webmd')? 'member.'+env : 'member';
				window.location.href="https://"+env+".webmd.com/subscriptions.aspx";
			}
        }
        function clearChanges(){
            options.changes = {};
        }
        function checkForUrlParam(){
            var param = getParam('watchlist');
            if(param){
                var ref = function(){
                    refresh(options.modeName.edit, 'emails');
                };
                var reqlogin = function(){
                    webmd.p.exch.requireLogin(ref);
                };
                /* timeout since isLoggedIn does not load immediately */
                setTimeout(function(){
                    if(isLoggedInWebMD()){
                        ref();
                    } else {
                        reqlogin();
                    }
                }, 1000);
            }
        }
        function entryExists(opts){
            var overrides = {
                data: {id: opts.id, type: opts.type},
                success: function(status){
                    opts.success(status);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    opts.error(XMLHttpRequest, textStatus, errorThrown);
                }
            };
            var call = $.extend({}, services.watchlist.exists(), overrides);
            $.ajax(call);
        }
        /* Evaluate type of entry to be added into Watchlist */
        function evaluateAddType(opts){
            var defaults = {
                alert: 0,
                error: null, /* on error callback */
                id: space_id, /* can be space_id or the object's id */
                isModal: false, /* true pops webmd.p.exch.overlay, with content defined below */
                miscData: null,
                objType: undefined,
                success: null /* on success callback */
            };
            var options = $.extend({}, defaults, opts);
            if(options.isModal){
                if(options.objType == 'email_digest'){
                    var show = function(){
                        webmd.p.exch.leftNav.emaildigest.show();
                    };
                    if(isLoggedInWebMD()){
                        show();
                    } else {
                        webmd.p.exch.requireLogin(show);
                    }
                } else if (options.objType == 'newsletter'){
                    /* No HTMl file exists, going with performance vs. ajax */
                    var modalId = 'modal-newsletter';
                    webmd.p.exch.overlay.setWidth(415);
                    webmd.p.exch.overlay.html('<div id="'+modalId+'" class="modal newsletter"><h3 class="newsletterTitle">Stay Informed with Newsletters</h3><p class="newsletterText">Loading...</p><form action="'+hostPrefix+'" method="post"><input name="nls" type="hidden" value=""><input class="email" name="email" type="text" value="" title="Enter Email Address"><div class="buttons"><button class="exchOverlayClose secondary" name="close" type="button"><span>Close</span></button><button class="newsletterSubmit primary" name="submit" type="submit"><span>Sign Up</span></button></div></form></div>');
                    webmd.p.exch.leftNav.newsletter.init($('#'+modalId), {modal: true});
                } else if (options.objType == 'promotion'){
                    var modalId = 'modal-promotion';
                    webmd.p.exch.overlay.setWidth(940);
					webmd.p.exch.overlay.load('/api/proxy/proxy.aspx?url=http://img.'+domain+'/dtmcms/live/webmd/consumer_assets/site_images/exchange/modals/modal_email_digest_promo.html');
                }
            } else {
                if(options.objType == 'email_digest'){
                    options.alert = 2;
                    options.success = function(){
                        webmd.p.exch.leftNav.refresh();
                    };
                    addEntry(options);
                } else if(options.objType == 'newsletter'){
                    addEntryNewsletter(options);
                } else {
                    addEntry(options);
                }
            }
        }
        function getContent(mode, type, callback){
            var overrides = {
                data: {count: -1},
                success: function(data){
                    data = data.Entries;
                    if(data){
                        data = Data.clean(data, ['activitydate', 'alerttype', 'id', 'miscdata', 'name', 'objecttype', 'qualifiername', 'title', 'url']);
                        callback(data);
                    } else {
                        return null;
                    }
                }
            };
            var call = $.extend({}, services.watchlist.get(), overrides);
            $.ajax(call);
        }
        function getParam(key){
            var s, regex;
            key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
            regex = new RegExp('[\\?&]'+key+'=([^&#]*)');
            s = regex.exec(window.location.href);
            return (s) ? s[1] : null;
        }
        function init(){
            options.hasOverlay = (typeof webmd.p.exch.watchlist.overlay);
            checkForUrlParam();
        }
        function refresh(mode, type){
            options.saved = (options.saved && mode != options.modeName.standard);
            var callback = function(data){
                if(options.hasOverlay){
                    webmd.p.exch.watchlist.overlay.saved(options.saved);
                    webmd.p.exch.watchlist.overlay.write(mode, type, data);
                    webmd.p.exch.watchlist.overlay.show(type);
                    if(options.saved){
                        webmd.p.exch.watchlist.overlay.message(options.msg.saved);
                    }
                }
            };
            getContent(mode, type, callback);
        }
        function saveChanges(mode, type){
            var data = '';
            for(var i in options.changes){
                var tChange = options.changes[i];
                data += i+'|'+tChange['alertType']+'|'+tChange['isDelete']+';';
            }
            if(data != ''){
                options.saved = true;
                var overrides = {
                    data: 'u='+data,
                    success: function(data){
                        clearChanges();
                        refresh(mode, type);
                        webmd.p.exch.grouptools.refresh();
                        webmd.p.exch.leftNav.refresh();
                    }
                };
                var call = $.extend({}, services.watchlist.update(), overrides);
                $.ajax(call);
            } else {
                if(options.hasOverlay){
                    webmd.p.exch.watchlist.overlay.message(options.msg.none);
                }
            }
        }
        return this;
    };

    /**
     * Exchanges Watchlist Overlay
     * Please use the webmd.p.exch.watchlist.controller to handle adding and removing watchlist entries
     * Name webmd.p.exch.watchlist.overlay
     * Public methods: .hide(), .message(), saved(), show(), write()
     */
    $.fn.watchlistOverlay = function(opts){
        var $this = $(this);
        var defaults = {
            anim: {delay: 6000, maxOpacity: 1, minOpacity: 0, speed: 300},
            bound: false,
            el: {
                button: {cancel: 'Cancel', close: 'Close', edit: 'Edit', save: 'Save', saved: 'Saved'},
                email: {add: 'Turn on email updates', remove: 'Turn off email updates'},
                heading: {all: 'all', preferences: 'preferences'},
                subheading: {communities: 'communities', discussions: 'discussions', emails: 'emails'},
                subscription: {add: 'Restore this', remove: 'Remove this'}
            },
            isOpen: false,
            mode: null,
            modeName: {edit: 'edit', standard: 'default'},
            saved: false,
            type: null
        };
        var options = $.extend(defaults, opts || {});
        setContentEvents();

        this.hide = function(){ hideOverlay() };
        this.message = function(msg){ showMessage(msg) };
        this.saved = function(bool){
            options.saved = bool;
            if(options.saved){
                setContentEvents();
            }
        };
        this.show = function(type){ showOverlay(type) };
        this.write = function(mode, type, data){ writeContent(mode, type, data) };

        function contentEventHandler($el){
            var data = $el.data('opts');
            if(data){
                if(options.saved){
                    options.saved = false;
                    $this.find('.bottom').html(makeButtons(options.mode, options.type));
                }
                if(data.id && data.status != null){
                    var alertType = null;
                    var isDelete = null;
                    if($el.hasClass('remove')){

                        if(data.status){
                            alertType = 1;
                            isDelete = 1;
                            $el.data('opts').status = false;
                            $el.removeClass('on').addClass('off').attr('title', options.el.subscription.add+' '+data.description);
                            var $prev = $el.parents('.remove').prev().find('a.email');
                            if($prev.length){
                                $prev.removeClass('on').addClass('off');
                                $prev.data('opts').status = false;
                            }
                        } else {
                            $el.data('opts').status = true;
                            $el.removeClass('off').addClass('on').attr('title', options.el.subscription.remove+' '+data.description);
                        }
                    } else if ($el.hasClass('email')){
                        isDelete = 0;
                        if(data.status){
                            alertType = 1;
                            $el.data('opts').status = false;
                            $el.removeClass('on').addClass('off').attr('title', options.el.email.add);
                        } else {
                            alertType = 2;
                            $el.data('opts').status = true;
                            $el.removeClass('off').addClass('on').attr('title', options.el.email.remove);
                            var $next = $el.parents('.email').next().find('a.remove');
                            if($next.length){
                                $next.removeClass('off').addClass('on');
                                $next.data('opts').status = true;
                            }
                        }
                    }
                    if(alertType != null && isDelete != null){
                        webmd.p.exch.watchlist.controller.change(data.id, alertType, isDelete);
                    }
                }
            }
        }
        function getSponsored(data){
            var sponsored = false;
            if(data.objecttype){
                sponsored = !(data.objecttype.indexOf('spon_') == -1);
            }
            if(data.qualifiername != undefined && !sponsored){
                sponsored = !(data.qualifiername.indexOf('spon_') == -1);
            }
            return sponsored;
        }
        function hideOverlay(){
            $this.css({display: 'none'});
            options.isOpen = false;
            options.saved = false;
        }
        function makeButtons(mode, type){
            var bArray, tag;
            switch(mode){
                case (options.modeName.edit):
                    if(options.saved){
                        bArray = [{className: options.el.button.close.toLowerCase(), methods: 'webmd.p.exch.watchlist.controller.close();', name: options.el.button.close}, {className: options.el.button.saved.toLowerCase(), name: options.el.button.saved}];
                    } else {
                        bArray = [{className: options.el.button.cancel.toLowerCase(), methods: 'webmd.p.exch.watchlist.controller.close();', name: 'Cancel'}, {className: options.el.button.save.toLowerCase(), methods: 'wmdPageLink(\'he-watchlist2_sav\'); webmd.p.exch.watchlist.controller.save(\'edit\', \''+type+'\');', name: options.el.button.save}];
                    }
                    break;
                case (options.modeName.standard):
                    tag = (type == 'communities') ? 'he-watchlist3_1-edit' : 'he-watchlist3_2-edit';
                    bArray = [{className: options.el.button.close.toLowerCase(), methods: 'webmd.p.exch.watchlist.controller.close();', name: options.el.button.close}, {className: options.el.button.edit.toLowerCase(), methods: 'wmdPageLink(\''+tag+'\'); webmd.p.exch.watchlist.controller.refresh(\'edit\', \''+type+'\');', name: options.el.button.edit}];
                    break;
                default:
                    bArray = null;
                    break;
            }
            return Template.buttons(bArray);
        }
        function makeContent(mode, type, data){
            var $obj = $([]);
            for(var i in options.el.subheading){
                var section = makeSection(mode, i, data);
                if(section){
                    $obj = $obj.add(section);
                }
            }
            return $obj;
        }
        function makeHeading(mode){
            return Template.heading(mode);
        }
        function makeSection(mode, type, data){
            var $list;
            var length = data.length;
            var prefix = (mode == options.modeName.standard) ? 'he-watchlist3_' : 'he-watchlist2_';
            var $obj = $([]).add(Template.subheading(mode, type));
            var $ul = $('<ul class="'+type+'"></ul>');
            for(var i=0; i<length; i++){
                var tData = data[i];
                tData.spon = getSponsored(tData);
                switch(type) {
                    case 'communities':
                        if(!(tData.objecttype.indexOf('space') == -1)){
                            tData.methods = 'wmdTrack(\''+prefix+'1-ttl\');';
                            $list = Template.list(mode, type, tData);
                        }
                        break;
                    case 'discussions':
                        if(!(tData.objecttype.indexOf('forum') == -1)){
                            tData.methods = 'wmdTrack(\''+prefix+'2-ttl\');';
                            $list = Template.list(mode, type, tData);
                        }
                        break;
                    case 'emails':
                        if(!(tData.objecttype.indexOf('email_digest') == -1)){
                            tData.methods = 'wmdTrack(\''+prefix+'3-ttl\');';
                            $list = Template.list(mode, type, tData);
                        }
                        break;
                    default:
                        list = '';
                }
                if($list != ''){
                    $ul.append($list);
                }
            }
            if(!$ul.children().length){
                $ul.append(Template.nosub(type));
            }
            return $obj.add($ul);
        }
        function scrollToType(type){
            if(type){
                var $heading = $this.find('h4.'+type);
                var $mask = $this.find('.mask');
                if($heading.length && $mask.length){
                    $mask.scrollTop($heading.position().top);
                }
            }
        }
        function setContentEvents(){
            var $el = $this.find('a');
            var clickHandler = function(e, $el){
                if($el.hasClass('email') || $el.hasClass('remove')){
                    e.preventDefault();
                    contentEventHandler($el);
                }
            };
            if(options.bound && options.saved){
                $el.die('click', function(e){clickHandler(e, $(this))});
            } else if(!options.bound && !options.saved){
                $el.live('click', function(e){clickHandler(e, $(this))});
                options.bound = true;
            }
        }
        function showMessage(msg){
            var $msg = $this.find('.bottom .messaging');
            $msg.stop().css({opacity: options.anim.minOpacity}).text(msg).animate({opacity: options.anim.maxOpacity}, options.anim.speed, function(){
                setTimeout(function(){
                    $msg.animate({opacity: options.anim.minOpacity}, options.anim.speed, function(){
                        $msg.text('');
                    })
                }, options.anim.delay);
            });
        }
        function showOverlay(type){
            if(!options.isOpen){
                $this.css({display: 'block'});
                options.isOpen = true;
            }
            scrollToType(type);
        }
        function writeContent(mode, type, data){
            options.mode = mode;
            options.type = type;
            $this.html(Template.main());
            $this.find('.bottom').html(Template.messaging()).append(makeButtons(mode, type)).end()
                .find('.middle .mask .content').html(makeContent(mode, type, data)).end()
                .find('.top').html(makeHeading(mode)).end()
                .find('.nosub').closest('ul').prev('h4').find('span:not(.title)').css({display: 'none'});
        }
        /* Templates used to build Watchlist components */
        var Template = {
            buttons: function(array){
                if(array){
                    var length = array.length;
                    var s = '';
                    for(var i=0; i<length; i++){
                        var obj = array[i];
                        var className = (obj.className) ? ' class="'+obj.className+'"' : '';
                        var methods = (obj.methods) ? ' onclick="'+obj.methods+'return false;" ' : '';
                        s += '<button'+className+' '+methods+'>'+obj.name+'</button>';
                    }
                    return s;
                } else {
                    return null;
                }
            },
            heading: function(mode){
                return '<h3>'+(mode == options.modeName.standard ? 'See All' : 'Preferences')+'</h3>';
            },
            list: function(mode, type, obj){
                var activity = '', count = '';
                var bi, biEmail, biRemove, eAlt, sAlt;
                var $email, $emailLink, $remove, $removeLink;
                var $list = $('<li></li>');
                var spon = (obj.spon) ? '<br/><span class="sponsored">Sponsored</span>' : '';
                var makeDefaults = function(){
                    if(type != 'emails'){
                        activity = (mode == options.modeName.standard && obj.activitydate) ? '<span class="date">'+DateDelta(convertFromEpoch(obj.activitydate))+'</span>' : activity;
                        count = (obj.miscdata) ? ' ('+obj.miscdata+')' : count;
                    }
                    bi = (obj.methods) ? ' onclick="'+obj.methods+'"' : '';
                    $list.append($('<span class="title"></span>').append($('<a href="'+obj.url+'"'+bi+'>'+obj.title+count+'</a>')).append(spon))
                        .append(activity);
                };
                switch(type){
                    case 'communities':
                        makeDefaults();
                        if(mode == options.modeName.edit){
                            biRemove = 'wmdPageLink(\'watchlist2_1-rem\')';
                            sAlt = ((obj.alerttype == 2) ? options.el.subscription.add : options.el.subscription.remove)+' Community';
                            $email = $('<span class="email"></span>');
                            $removeLink = $('<a class="remove on" href="/" onclick="'+biRemove+'" title="'+sAlt+'"></a>')
                                    .data('opts', {alertType: 1, description: 'Community', id: obj.id, status: true, title: sAlt});
                            $remove = $('<span class="remove"></span>').append($removeLink);
                            $list.append($email).append($remove);
                        }
                        break;
                    case 'discussions':
                        makeDefaults();
                        if(mode == options.modeName.edit){
                            biEmail = 'wmdPageLink(\'watchlist2_email\');';
                            biRemove = 'wmdPageLink(\'watchlist2_2-rem\');';
                            eAlt = ((obj.alerttype == 2) ? options.el.email.add : options.el.email.remove);
                            sAlt = ((obj.alerttype == 2) ? options.el.subscription.remove : options.el.subscription.add)+' Discussion';
                            $emailLink = $('<a class="'+((obj.alerttype == 2) ? 'email on' : 'email off')+'" href="/" onclick="'+biEmail+'" title="'+eAlt+'"></a>')
                                    .data('opts', {alertType: 2, id: obj.id, status: (obj.alerttype == 2), title: eAlt, type: type});
                            $email = $('<span class="email"></span>').append($emailLink);
                            $removeLink = $('<a class="remove on" href="/" onclick="'+biRemove+'" title="'+sAlt+'"></a>')
                                    .data('opts', {alertType: 1, description: 'Discussion', id: obj.id, status: true, title: sAlt});
                            $remove = $('<span class="remove"></span>').append($removeLink);
                            $list.append($email).append($remove);
                        }
                        break;
                    case 'emails':
                        makeDefaults();
                        if(mode == options.modeName.edit){
                            biEmail = 'wmdPageLink(\'watchlist2_3-rem\');';
                            sAlt = options.el.subscription.remove+' Email Digest';
                            $email = $('<span class="email"></span>');
                            $removeLink = $('<a class="remove on" href="/" onclick="'+biEmail+'" title="'+sAlt+'"></a>')
                                    .data('opts', {alertType: 2, description: 'Email Digest', id: obj.id, status: true, title: sAlt});
                            $remove = $('<span class="remove"></span>').append($removeLink);
                            $list.append($email).append($remove);
                        }
                        break;
                    default:
                        $list = null;
                }
                return $list;
            },
            main: function(){
                return '<div class="top"></div><div class="middle"><div class="mask"><div class="content"></div></div></div><div class="bottom"></div>';
            },
            messaging: function(){
                return $('<p class="messaging"></p>').css({opacity: 0});
            },
            nosub: function(type){
                return '<li class="nosub">You are not subscribed to any '+type+'.</li>';
            },
            subheading: function(mode, type){
                var s = '', date = '', email = '', remove = '', title = '';
                var cs = options.el.subheading[type];
                var className = (cs) ? $.trim(cs.replace(/\./g,' ')) : '';
                switch(type) {
                    case 'communities':
                        title += '<span class="title">My Communities</span>';
                        if(mode == options.modeName.standard){
                            date += '<span class="activity">Last Activity</span>';
                        } else {
                            remove += '<span class="remove">Remove</span>';
                        }
                        break;
                    case 'discussions':
                        title += '<span class="title">My Discussions</span>';
                        if(mode != options.modeName.standard){
                            email += '<span class="email">Email</span>';
                            remove += '<span class="remove">Remove</span>';
                        }
                        break;
                    case 'emails':
                        title += '<span class="title">My Email Digests</span>';
                        if(mode != options.modeName.standard){
                            remove += '<span class="remove">Remove</span>';
                        }
                        break;
                }
                return '<h4 class="'+className+'">'+title+date+remove+email+'</h4>';
            }
        };
        return this;
    };

    /* BI for consistent portions of webmd.p.exch.leftNav */
    /* Should be modified to inlcude webmd.p.exch.watchlist */
    var BI = function(sectionType, suffix){
        var tag, type;
        switch(sectionType) {
            case 'cms':
                tag = 'he-nav-main_'+suffix; type = 'wmdTrack'; break;
            case 'communities':
                tag = 'he-nav-watchlist_1-'+suffix; type = (suffix == 'sa' || suffix == 'e') ? 'wmdPageLink' : 'wmdTrack'; break;
            case 'community':
                tag = 'he-nav-main_'+suffix; type = 'wmdTrack'; break;
            case 'discussions':
                tag = 'he-nav-watchlist_2-'+suffix; type = (suffix == 'sa' || suffix == 'e') ? 'wmdPageLink' : 'wmdTrack'; break;
            case 'emails':
                tag = 'he-nav-watchlist_3-'+suffix; type = (suffix == 'sa' || suffix == 'e') ? 'wmdPageLink' : 'wmdTrack'; break;
            case 'informed':
                tag = 'he-nav-watchlist_4-'+suffix; type = 'wmdPageLink'; break;
            case 'watch':
                tag = 'he-nav-watchlist_'+suffix; type = 'wmdTrack'; break;
            default:
                tag = null; type = null; break;
        }
        return (tag && type) ? type+'(\''+tag+'\');' : '';
    };

    /* Data cleaning for webmd.p.exch.leftNav and webmd.p.exch.watchlist, since capitalizations are inconsistent between services */
    Data.clean = function(data, array){
        var attr, aAttr, obj, tValue;
        obj = $.map(data, function(o, i){
            var nData = {};
            for(i in o){
                attr = i.toLowerCase();
                var length = array.length;
                for(var j=0; j<length; j++){
                    aAttr = array[j];
                    if(attr == aAttr){
                        tValue = o[i];
                        if(tValue && tValue != ''){
                            nData[attr] = o[i];
                        }
                    }
                }
            }
            return nData;
        });
        return obj;
    };


})(jQuery);

/* Init Exchange left-nav and Watchlist under webmd.p.exch */
$(document).ready(function(){
    var $leftnav = $('#ex-lr-nav');
    var $watchlist = $('#watchlist-overlay');
    if($leftnav.length){
        $leftnav.append($watchlist.remove());
        webmd.p.exch.leftNav = $leftnav.exchLeftNav();
        if(typeof webmd.m.newsletter == 'object'){
            webmd.p.exch.leftNav.newsletter = new webmd.m.newsletter.ModuleExchange();
        }
        webmd.p.exch.leftNav.emaildigest = new webmd.m.emaildigest;
        webmd.p.exch.leftNav.emaildigest.init();
    }
    if($watchlist.length){
        webmd.p.exch.watchlist = {};
        webmd.p.exch.watchlist.overlay = $watchlist.watchlistOverlay();
        webmd.p.exch.watchlist.controller = $watchlist.watchlistController();
    }
});
/*** END Exchange left-nav and Watchlist ***/

/* BEGIN Watchlist add discussion from Content Feed */
    function LoginAddDiscussionToWatchList(obj, id, type) {
        return webmd.p.exch.requireLogin(function(){ AddDiscussionToWatchList(obj,id,type); });
    }
    function AddDiscussionToWatchList(obj, id,type){
        var $link = $(obj);
        var emailoption = (isWHSUser()) ? 'none' : 'email';
        if(space_type == "PublicSponsored"){
            type = "spon_forum";
        }
        var text = {
            adding: 'Adding to Watch List...',
            error: 'Error adding to Watchlist',
            success: 'You are Watching This Discussion'
        };
        var error = function(data){ $link.text(text.error) };
        var success = function(data){
            if(data){
                $link.text(text.success);
            } else {
                $link.text(text.error);
            }
        };
        $link.text(text.adding);
        webmd.p.exch.watchlist.controller.add({id: id, objType: type, alert: emailoption, miscData: '0', error: error, success: success});
        return false;
    }
/* END Watchlist add discussion from Content Feed */

webmd.m.emaildigest = function(){};
webmd.m.emaildigest.prototype = {
    error: function(){
        var self = this;
        webmd.p.exch.overlay.setWidth(415);
        webmd.p.exch.overlay.html('<p>'+self.options.msg.error+'</p>');
    },
    hide: function(){
        $('#'+self.options.id).find('input').unbind('click');
        webmd.p.exch.overlay.close();
    },
    init: function(opts){
        var self = this;
        var defaults = {
            error: function(){
                self.error();
            },
            id: 'exchOverlayContent',
            msg: {
                error: 'We\'re sorry: an error occurred, please try again later.'
            },
            success: function(){
                self.success();
            },
            url1: '/api/proxy/proxy.aspx?url='+image_server_url+'/webmd/consumer_assets/site_images/exchange/modals/modal_daily_email_digest_signup.html',
            url2: '/api/proxy/proxy.aspx?url='+image_server_url+'/webmd/consumer_assets/site_images/exchange/modals/modal_daily_email_digest_confirm.html'
        };
        self.options = $.extend({}, defaults, opts);
    },
    show: function(){
        var self = this;
        webmd.p.exch.overlay.setWidth(415);
        webmd.p.exch.overlay.load(self.options.url1, null, self.options.success);
    },
    success: function(){
        var self = this;
        $('#'+self.options.id).find('.confirm').bind('click', function(e){
            var callback = function(){
                webmd.p.exch.watchlist.controller.add({objType: 'email_digest', success: webmd.p.exch.leftNav.refresh()});
            };

            webmd.p.exch.overlay.setWidth(415);
            webmd.p.exch.overlay.load(self.options.url2, null, callback);
        })
    }


};

/** Channel ID mappings
 * @param id  usually js variable {priTopId}
 * @returns newsletter.description, newsletter.name, newsletter.sub
 * used by Exchange left nav and newsletter_exchange.js */
var channelIdMap = function(id){
    id = parseInt(id);
    var nlSub, name, nlDesc, nlTitle = null;
    switch(id) {
        case 1001: nlSub = 66; name = 'ADD/ADHD'; nlDesc = 'Sign up for the ADD/ADHD newsletter and keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1002: case 1003: nlSub = 65; name = 'Substance Abuse'; nlDesc = 'Don\'t take the road to recovery alone. Get the Substance Abuse newsletter with WebMD.'; break;
        case 1004: case 1009: case 1072: case 1130: nlSub = 11; name = 'Allergies & Asthma'; nlDesc = 'Sign up for the Allergies &amp; Asthma newsletter and keep up with all the latest Allergies news, treatments, and research with WebMD.'; break;
        case 1005: nlSub = 60; name = 'Alzheimer\'s'; nlDesc = 'Sign up for the Alzheimers newsletter to keep up with all the latest Alzheimer\'s news, treatments, and research with WebMD.'; break;
        case 1006: case 1014: case 1039: case 1058: case 1069: case 1093: case 1095: case 1113: case 1117: case 1120: case 1144: case 1146: case 1163: nlSub = 35; name = 'Women\'s Health'; nlDesc = 'Sign up for the Women\'s Health newsletter and keep up with all the latest diet, fitness and health news you need from WebMD.'; break;
        case 1008: case 1087: case 1088: case 1161: nlSub = 12; name = 'Arthritis'; nlDesc = 'Sign up for the Arthritis newsletter to keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1010: case 1027: case 1028: case 1090: case 1104: nlSub = 17; name = 'Chronic Pain/Back Pain'; nlDesc = 'Sign up for the Back Pain newsletter to keep up with all the latest news, treatments, and research on back pain and chronic pain with WebMD.'; break;
        case 1011: case 1051: case 1075: case 1105: case 1132: case 1133: case 1136: nlSub = 37; name = 'Skin & Beauty'; nlDesc = 'Start receiving the Skin &amp; Beauty newsletter and get the latest diet, exercise and health tips to keep your skin glowing and beautiful!'; break;
        case 1012: case 1018: case 1021: case 1156: case 1038: case 1078: case 1122: nlSub = 19; name = 'Emotional Wellness'; nlDesc = 'Sign up for the Emotional Wellness newsletter and keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1013: nlSub = 53; name = 'Bipolar'; nlDesc = 'Sign up for WebMD\'s Bipolar newsletter and keep up with all the latest news, treatments, and industry research with WebMD.'; break;
        case 1015: case 1022: case 1023: case 1030: case 1061: case 1068: case 1071: case 1084: case 1089: case 1159: case 1097: nlSub = 14; name = 'Cancer'; nlDesc = 'Sign up for the Cancer newsletter and keep up with all the latest news, treatments, and research from WebMD.'; break;
        case 1016: case 1054: case 1055: case 1056: case 1057: case 1108: case 1141: case 1147: case 1164: nlSub = 24; name = 'Heart Health'; nlDesc = 'Sign up for the Heart Health newsletter and keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1017: case 1150: nlSub = 40; name = 'Healthy Bones'; nlDesc = 'Sign up for the Healthy Bones newsletter and keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1020: nlSub = 13; name = 'Breast Cancer'; nlDesc = 'Sign up for the Breast Cancer newsletter and keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1024: case 1025: case 1070: case 1091: case 1126: case 1152: case 1160: case 1196: nlSub = 28; name = 'Parenting and Children\'s Health'; nlDesc = 'Get the Parenting &amp; Children\'s Health newsletter and get useful parenting tips and health news you need to keep your little ones happy &amp; healthy.'; break;
        case 1026: nlSub = 16; name = 'Cholesterol Management'; nlDesc = 'Sign up for the Cholesterol Management newsletter and keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1032: case 1100: nlSub = 44; name = 'Depression'; nlDesc = 'Sign up for the Depression newsletter and keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1033: case 1042: nlSub = 18; name = 'Diabetes'; nlDesc = 'Sign up for the Diabetes newsletter and keep up with all the latest news, treatments, and research with WebMD.'; break;
        case 1034: case 1110: case 1115: case 1128: nlSub = 34; name = 'Weight Control'; nlDesc = 'Sign up for the Weight Control newsletter and keep up with all the latest dieting news, treatments and research with WebMD.'; break;
        case 1035: case 1119: case 1066: case 1067: case 1112: case 1123: case 1138: nlSub = 22; name = 'GI Disorders'; nlDesc = 'Sign up for the GI Disorders newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1036: case 1044: case 1045: case 1052: case 1053: case 1130: case 1151: case 1155: nlSub = 43; name = 'Living Better'; nlDesc = 'Sign up for the Living Better newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1040: nlSub = 20; name = 'Epilepsy'; nlDesc = 'Sign up for the Epilepsy newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1041: nlSub = 48; name = 'Erectile Dysfunction'; nlDesc = 'Sign up for the Men\'s Health newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1043: nlSub = 45; name = 'Fibromyalgia'; nlDesc = 'Sign up for the Fibromyalgia newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1046: case 1079: nlSub = 21; name = 'Fitness'; nlDesc = 'Sign up for the Fitness newsletter and keep up with all the latest dieting news, treatments and research with WebMD.'; break;
        case 1047: case 1062: nlSub = 42; name = 'Healthy Recipes'; nlDesc = 'Sign up for the Healthy Recipes newsletter and get quick and easy, healthy recipes from WebMD.'; break;
        case 1048: case 1049: case 1101: case 1102: case 1103: case 1131: nlSub = 30; name = 'Sex & Relationships'; nlDesc = 'Sign up for the Sex &amp; Relationships newsletter and get relationship tips, diet and exercise tips to rev-up your sex life.'; break;
        case 1050: case 1129: nlSub = 83; name = 'Daily Bite'; nlDesc = 'Sign up for the Daily Bite newsletter and get the latest on healthy living, recipes and health news from WebMD.'; break;
        case 1059: nlSub = 67; name = 'Hepatitis'; nlDesc = 'Sign up for the WebMD Hepatitis newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1060: case 1064: nlSub = 43; name = 'Living Better'; nlDesc = 'Sign up for the Living Better newsletter and receive healthy living and dieting tips and updates on treatments and research from WebMD.'; break;
        case 1063: nlSub = 25; name = 'Hypertension'; nlDesc = 'Sign up for the Hypertension newsletter and keep up with all the health living news treatments and latest research with WebMD.'; break;
        case 1065: case 1166: case 1167: nlSub = 33; name = 'Trying to Conceive'; nlDesc = 'Sign up for the Trying to Conceive newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1073: nlSub = 68; name = 'Lupus'; nlDesc = 'Sign up for the Lupus newsletter and get the latest news, treatments, and research information from WebMD.'; break;
        case 1074: case 1080: case 1086: case 1094: case 1099: case 1109: case 1111: case 1121: case 4051: nlSub = 36; name = 'WebMD Newsletters'; nlDesc = 'Sign up for WebMD newsletters for the latest health and wellness information.'; nlTitle = 'WebMD Newsletters'; break;
        case 1076: case 1140: case 1143: case 1157: nlSub = 26; name = 'Men\'s Health'; nlDesc = 'Sign up for the Men\'s Health newsletter and all the diet, exercise and lifestyle news with WebMD.'; break;
        case 1077: nlSub = 62; name = 'Menopause'; nlDesc = 'Sign up for the Menopause newsletter and keep up with all the diet, exercise and lifestyle news along with the latest research with WebMD.'; break;
        case 1081: case 1116: case 1168: nlSub = 41; name = 'Weight Loss Wisdom'; nlDesc = 'Sign up for the Weight Loss Wisdom newsletter and keep up with all the latest dieting news, exercise and health tips from WebMD.'; break;
        case 1082: nlSub = 27; name = 'Multiple Sclerosis'; nlDesc = 'Sign up for the Multiple Sclerosis newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1085: nlSub = 63; name = 'Oral Health'; nlDesc = 'Sign up for the Oral Health newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1092: nlSub = 69; name = 'Parkinson\'s Disease'; nlDesc = 'Get the WebMD Parkinson\'s Disease newsletter and keep up with all the latest news, treatments and research with WebMD.'; break;
        case 1096: case 1152: nlSub = 28; name = 'Pregnancy Week-by-Week'; nlDesc = 'Sign up for our Pregnancy: Week-by-Week newsletter and let WebMD join you on your amazing journey to motherhood!'; break;
        case 1098: nlSub = 29; name = 'Rheumatoid Arthritis'; nlDesc = 'Sign up for the Rheumatoid Arthritis newsletter and get the very latest diet and exercise tips, news, treatments and research with WebMD.'; break;
        case 1106: nlSub = 31; name = 'Sleep Disorders'; nlDesc = 'Stop tossing and turning. Get the latest diet and exercise tips, treatments and research about better sleep from WebMD.'; break;
        case 1107: nlSub = 32; name = 'Smoking Cessation'; nlDesc = 'Stop trying to quit and start on the road to a healthier you. Get the Smoking Cessation newsletter from WebMD.'; break;
        case 1114: nlSub = 38; name = 'Video of the Week'; nlDesc = 'Sign up for our Pictures of Health newsletter and get the latest videos and slideshows from WebMD!'; break;
        case 1125: nlSub = 64; name = 'Sports Medicine'; nlDesc = 'Sign up for the Sports Medicine newsletter and get the latest fitness, diet and health new you need from WebMD.'; break;
        case 1162: nlSub = 28; name = 'Baby\'s First Year'; nlDesc = 'Let WebMD walk through the first year of your baby\'s life with you, get the latest parenting news, and pediatrician tips with WebMD.'; break;
        case 1165: nlSub = 47; name = 'WebMD Healthy Pets'; nlDesc = 'Sign up for the WebMD Healthy Pets newsletter and get the latest on food, exercise and health news for Fluffy and Fido.'; break;
        default: nlSub = null, name = null, nlDesc = 'WebMD Newsletters. With more than 40 to choose from, there\'s sure to be one that\'s perfect for you! <a href="https://member.webmd.com/newsletters/newsletters.aspx" target="_blank">Sign Up</a>';
    }
    return {name: name, newsletter: {description: nlDesc, sub: nlSub, title: nlTitle}};
};

/** Space ID mappings
 * @returns object with newsletter subscription id
 * used by Exchange left nav */
var spaceIdMap = function(){
    var relatedName, relatedUrl;
    switch(parseInt(space_id)) {
        case 39: case 54: case 57: case 64: case 72: case 103: case 105: case 106: case 514: case 653:
            relatedName = 'Eating & Diet', relatedUrl = 'eating-diet-exchanges'; break;
        case 41: case 42: case 45: case 46: case 51: case 59: case 68: case 71: case 80: case 115: case 118: case 149: case 517: case 542: case 834:
            relatedName = 'Women\'s Health', relatedUrl = 'womens-health-exchanges'; break;
        case 42: case 86: case 115: case 121: case 126: case 140: case 141: case 142: case 143: case 144: case 145: case 146: case 542: case 739:
            relatedName = 'Trying to Conceive', relatedUrl = 'trying-to-conceive-exchanges'; break;
        case 45: case 47: case 69: case 517:
            relatedName = 'Sex & Relationships', relatedUrl = 'sex-relationships-exchanges'; break;
        case 46: case 550: case 145: case 121: case 733: case 602: case 124: case 126: case 125: case 1119: case 119: case 127: case 123: case 122: case 793: case 1080: case 1096: case 942:
            relatedName = 'Pregnancy', relatedUrl = 'pregnancy-exchanges'; break;
        case 49: case 88: case 92: case 96: case 107: case 108: case 110: case 112: case 113: case 499: case 574: case 895: case 1085:
            relatedName = 'Mental Health', relatedUrl = 'mental-health-exchanges'; break;
        case 50: case 40: case 77: case 81: case 48: case 58: case 1117: case 711: case 147: case 919:
            relatedName = 'Pain Management', relatedUrl = 'pain-management-exchanges'; break;
        case 60: case 57: case 735: case 484: case 833: case 557:
            relatedName = 'Digestive Disorders', relatedUrl = 'digestive-disorders-exchanges'; break;
        case 69: case 73: case 56: case 739: case 1068: case 689: case 1063:
            relatedName = 'Men\'s Health', relatedUrl = 'mens-health-exchanges'; break;
        case 88: case 43: case 44: case 593: case 783: case 101: case 129: case 1037: case 731: case 540: case 539: case 1330: case 926: case 133: case 134: case 135: case 132: case 136: case 137: case 131:
            relatedName = 'Parenting', relatedUrl = 'parenting-exchanges'; break;
        case 93: case 75: case 76: case 51: case 56: case 741: case 718: case 969: case 835: case 528:
            relatedName = 'Cancer', relatedUrl = 'cancer-exchanges'; break;
        default:
            relatedName = null, relatedUrl = null;
    }
    return {relatedName: relatedName, relatedUrl: relatedUrl};
};

//DateDiff--Start
function DateDelta(datetime) {

	if(datetime.match('^(1/1/0001|0001-01-01)')) {
		return 'N/A';
	}

    // Temp fix for timezone
    /*
    datetime = datetime.replace(/GMT-0500 \(EDT\)/, 'GMT-0400 (EDT)');

    if (/(AM|PM)$/.test(datetime)) { // Temp fix for adding timezone
        datetime += ' EDT';
    }
    */

    var date1 = new Date();
    var date2 = new Date(Date.parse(datetime));

    var compdate1 = date1.getTime();
    var compdate2 = date2.getTime();

    var diffdate = compdate1 - compdate2; //diff in milliseconds
    diffdate = diffdate / 1000 / 60; //convert to minutes

    if (Math.floor(diffdate) <= 0) {
        return 'just now';
    }
    if (diffdate < 60) { //less than 1 hour
        var m = Math.round(diffdate);
        var incr = (m > 1) ? ' minutes' : ' minute';
        var desc = ' ago';
        return m.toString()+incr+desc;
    }
    if (diffdate < 60 * 24) { //less than one day
        return Math.round(diffdate / 60).toString() + ' ' + Pluralize(Math.round(diffdate / 60), 'hour') + ' ago';
    }
    if (diffdate < 60 * 24 * 7) { //less than one week
        return Math.round(diffdate / 60 / 24).toString() + ' ' + Pluralize(Math.round(diffdate / 60 / 24), 'day') + ' ago';
    }
    if (diffdate < 60 * 24 * 7 * 4) { //less than one month
        return Math.round(diffdate / 60 / 24 / 7).toString() + ' ' + Pluralize(Math.round(diffdate / 60 / 24 / 7), 'week') + ' ago';
    }
    if (diffdate < 60 * 24 * 7 * 4 * 12) { //less than one year
        return Math.round(diffdate / 60 / 24 / 7 / 4).toString() + ' ' + Pluralize(Math.round(diffdate / 60 / 24 / 7 / 4), 'month') + ' ago';
    }

    return Math.round(diffdate / 60 / 24 / 7 / 4 / 12).toString() + ' ' + Pluralize(Math.round(diffdate / 60 / 24 / 7 / 4 / 12), 'year') + ' ago';

}

function isLoggedInWebMD(){
    return webmd.cookie.exists('WBMD_AUTH') || webmd.cookie.exists('WHS_AUTH');
}

function isLoggedInExch(){
    return isLoggedInWebMD() && webmd.cookie.exists('GRP_USER');
}

function isWHSUser(){
    return webmd.cookie.exists('WLMDWEBXAUTH');
}

function canInvite(){
    return webmd.p.exch.lbmonitor.getCanInvite();
}

function convertFromEpoch(Epoch) {
	var strValue = Epoch.match('[0-9]{1,}');
	var intValue = parseInt(strValue);
	var realDate = new Date(intValue);
	var strDate = realDate.toString();
	return strDate;
}

webmd.p.exch.lbmonitor = {

    // Extern variables: space_name
    // Extern functions: webmd.cookie, webmd.url

    cookieName: 'EXG_USER',
    lbmonitor:'/api/forums/lbmonitor.aspx?spacename=' + space_name,
    timeoutSeconds: 5,

    init: function(){
        this.getFromCookie();
    },

    refresh: function(options) {

        var
        self=this,
        o = options || {};

	$.ajax({
	    cache:false,
	    timeout:self.timeoutSeconds * 1000,
	    url:self.lbmonitor,
	    success:function(){
                self.getFromCookie();
                if ($.isFunction(o.success)) { o.success(); }
            },
	    error:function(){
                if ($.isFunction(o.error)) {
                    o.error();
                }
            }
        });

    },

    cookieExists:function(){
        return webmd.cookie.exists(this.cookieName);
    },

    getFromCookie: function() {

        var cookieValue, url;

        cookieValue = webmd.cookie.get(this.cookieName),

        // Make a fake URL so we can read parameters from it
        url = 'http://' + location.hostname + '/';
        if (cookieValue) {
            url += '?' + cookieValue;
        }

        this.values = {
            caninvite: webmd.url.getParam('caninvite', url),
            ismem: webmd.url.getParam('ismem', url),
            userid: webmd.url.getParam('userid', url),
            roles: webmd.url.getParam('roles', url)
        };
    },

    getCanInvite: function(){
        return (this.values.caninvite === 'True');
    },

    getIsMember: function(){

        if (this.values.ismem === '1') {
            return true;
        } else if (this.values.ismem === '0') {
            return false;
        } else {
            return null;
        }

    },

    getUserId: function(){
        return this.values.userid || '';
    },

    getRoles: function(){
        return this.values.roles || '';
    }

};

webmd.p.exch.lbmonitor.init();

if (location.hostname.indexOf('forums.') === 0 && isLoggedInWebMD()) {
    webmd.p.exch.lbmonitor.refresh();
}

$.extend(webmd.p.exch, {

    urlInvalidMsg: "The URL entered is not valid. It must start with http or https and be in the format: http://example.com/path",

    urlAddHttp: function(url) {
        // If there is no protocol at front of url, add http.
        // Returns updated url.
        if (!url.match(/^[^:\/]+:/i)) {
            url = 'http://' + url.replace(/^\/+/, '');
        }
        return url;
    },

    urlIsValid: function(url) {
        // Simple test if matches http or https and ://some.domain
        // Doesn't absolutely guarantee a valid url
        // Returns true or false
        return /^https?:\/\/[^\/]+\.[^\/]+.*/i.test(url);
    },

    urlIsValidAlert: function(url, alertMsg) {
        // Returns true or false and displays an alert if necessary
        var isValid = this.urlIsValid(url);
        if (!isValid) {
            alert(alertMsg || webmd.p.exch.urlInvalidMsg);
        }
        return isValid;
    },

    urlValidateInput: function(input) {

        // Adds http to a url if necessary and possible,
        // then validates and throws an alert if necessary.
        // Returns true for valid, false for invalid

        var i = $(input), url = i.val();

        if (url === undefined) { return false; }

        // Fix the url first
        url = this.urlAddHttp(url);
        i.val(url);

        // Verify it is valid
        return this.urlIsValidAlert(url);
    }
});



var debug = true;

function MyTrace(msg) {

    if (debug) {

        try {

            //alert(getCurrentDateTimeString() + ": " + msg);

            Sys.Debug.trace(getCurrentDateTimeString() + ": " + msg);

        }

        catch (ex) {

        }

    }

}

function MyTraceObject(obj) {

    if (debug) {

        try {

            for (var key in obj) {
                Sys.Debug.trace(key + ": " + obj[key]);
            }

        }

        catch (ex) {

        }

    }

}



function getCurrentDateTimeString() {
    var now = new Date();
    return now.toDateString() + ', ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '::' + now.getMilliseconds(); //now.toLocaleTimeString();
}

function displayException(methodName, e) {
    var msg = "Exception occurred in: " + methodName + "\n\r" +
		"e.number is: " + (e.number & 0xFFFF) + "\n\r" +
		"e.description is: " + e.description + "\n\r" +
		"e.name is: " + e.name + "\n\r" +
		"e.message is: " + e.message;
    MyTrace(msg);
}

String.prototype.trim = function() {
    // Strip leading and trailing white-space
    return this.replace(/^\s*|\s*$/g, "");
}

String.prototype.normalize_space = function() {
    // Replace repeated spaces, newlines and tabs with a single space
    return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
}

var tmrIds = new Array();
function countChar(tbxId, spnId, maxCount) {
    var count = $get(tbxId).value.length;
    $get(spnId).innerHTML = maxCount - count;
    //MyTrace('count=' + count);
}

function startCountTimer(tbxId, spnId, maxCount, interval) {
    tmrIds[tbxId] = setInterval('countChar("' + tbxId + '", "' + spnId + '", ' + maxCount + ')', interval);
    //MyTrace('start');
}

function clearCountTimer(tbxId) {
    clearInterval(tmrIds[tbxId]);
    //MyTrace('cleared');
}

function Pluralize(no, word) {
    if (no > 1) {
        return word + 's';
    }
    else {
        return word;
    }
}

webmd.p.exch.replaceWordChars = (function(){

    var
    codeMap = {
        8216:"'",
        8217:"'",
        8220:'"',
        8221:'"',
        8211:'&mdash;',
        8212:'&mdash;'
    },
    charMap = {},
    reStr = '',
    re;

    // Create a regexp to match all the characters in codeMap
    $.each(codeMap, function(key,val){

        var c = String.fromCharCode(key);

        // For best efficiency later, create a map for the actual character
        charMap[c] = val;

        reStr += c;
    });

    re = new RegExp('[' + reStr + ']', 'g');

    // Return the actual function to use for replaceWordChars
    return function(s) {

        return s.replace(re, function(s){
            return charMap[s];
        });

    };

})();

//JQueryRTE--Start
/*! $Id: jquery.rte.js 189 2009-06-15 17:30:31Z pfitzgerald $
* WebMD rich text editor
* Is loosley based on jQuery RTE plugin 0.5.1
* Copyright (c) 2009 Batiste Bieler
* Distributed under the GPL Licenses.
* Distributed under the The MIT License.
*/

(function($) {

    function RteController(textarea, options) {

        // Save the textarea in th object. Use $()[0] just in case a jQuery object was passed in.
        this.textarea = $(textarea)[0];

        // Initialize the edtior
        this.init(options);
    }

    // Prototype methods for the RTE object
    RteController.prototype = {

        // Function: init
        // Purpose:  Initialize the editor
        // Inputs:   options (object)
        //
        init: function(options) {

            var content, css, doc, i, idoc,
            self = this,
            $ta = $(self.textarea);

            // Set default options and override the defaults
            self.options = $.extend({
                css: 'body{font-family:Arial,Verdana,Helvetica,sans-serif;font-size:10pt;margin:0;padding:.5em;} p{margin:0;border:0}',
                syncOnSubmit: true,
                height: '200',
                format: 'bbcode'
            }, options);

            // Get the default text from the textarea
            content = self._preProcess($ta.val());

            // Create the iframe
            // For compatibility reasons, create using native DOM methods
            self.iframe = i = document.createElement("iframe");
            i.frameBorder = 0;
            i.frameMargin = 0;
            i.framePadding = 0;
            i.height = self.options.height || '100%';

            // If the textarea has a class, set the same class on the iframe so it can be styled
            if ($ta.attr('class')) {
                i.className = $ta.attr('class');
            }

            // CSS within the iframe
            css = self.options.css ? ('<style>' + self.options.css +'</style>') : '';

            // HTML within the iframe
            doc = '<html><head>' + css + '</head><body class="rte-iframe-body">' + content + '</body></html>';

            // Add the iframe to the page after the textarea.
            // Must do this before we can access the contentWindow for the iframe.
            $ta.after(i);

            // Save the iframe document so we can attach events to it if desired
            self.iframeDoc = idoc = i.contentWindow.document;

            // Activate design mode for rich text editing

            idoc.designMode = "on";

            // Write the content to the document
            idoc.open();
            idoc.write(doc);
            idoc.close();

            // Make all the links have a title attribute, to display tooltip for better usability
            self._addTitlesToLinks();

            // Sync the textarea when the form is submitted?
            if (self.options.syncOnSubmit) {

                $(self.textarea.form).submit(function() {
                    self.sync();
                });
            }

	    // Display the RTE
            self.show();

            // Force Mozilla to use HTML elements instead of CSS
            self._exec('styleWithCSS', false);

            // Trigger a custom event on the textarea for each keyup of the rte
            $(self.iframeDoc).keyup(function(){

                $ta.trigger('rtekeyup', [self]);

                // To bind to this custom event use code like:
                // $('#mytextarea').bind('rtekeyup', function(event,rte){})
            });
        },

        // Function: show
        // Purpose:  Shows the editor iframe and hides the textarea
        //
        show: function() {
            $(this.iframe).show();
            $(this.textarea).hide();
        },

        // Function: hide
        // Purpose:  Hides the editor iframe and shows the textarea
        //
        hide: function() {
            $(this.iframe).hide();
            $(this.textarea).show();
        },

        // Function: get
        // Purpose:  Returns the html from the editor. Also fixes the HTML to make it better.
        // Returns:  (string) the html
        //
        getContent: function() {
            // Get the html from the editor, then post-process it to fix the html
            return this._postProcess(this._get());
        },

        // Function: set
        // Purpose:  Set content into the editor
        // Inputs:   s (string) the html to insert in the editor
        setContent: function(s) {
            $(this.iframe).contents().find("body").html(s);
            this._addTitlesToLinks();
        },

        getSelectedText: function() {

            var w = this.iframe.contentWindow;

            if (w.getSelection) {
                return w.getSelection().toString();
            }

            return this.iframeDoc.selection.createRange().text;
        },

        insertHtml: function(s) {
            // In IE, 'inserthtml' is not supported, but _exec() has a special case to handle it
            this._exec('inserthtml', s);
            this._addTitlesToLinks();
        },

        // Function: sync
        // Purpose:  Copy the content from the editor back into the textarea
        // Returns:  (string) the html
        //
        sync: function() {
            $(this.textarea).val(this.getContent());
        },

        // Function: formatXXX
        // Purpose:  Run a formatting command on the selected text
        // Inputs:   formatLink(s)
        //           formatImg(s)
        //
        formatClear: function() { this._exec('removeFormat'); },
        formatBold: function() { this._exec('bold'); },
        formatItalic: function() { this._exec('italic'); },
        formatUnderline: function() { this._exec('underline'); },
        formatStrikethrough: function() { this._exec('strikeThrough'); },
        formatUl: function() { this._exec('insertunorderedlist'); },
        formatOl: function() { this._exec('insertorderedlist'); },
        formatLink: function(url) {
            this._exec('createLink', url);
            this._addTitlesToLinks();
        },
        formatUnlink: function(url) { this._exec('unlink', url); },
        formatImg: function(url) {
            this._exec('inserthtml', '<img src="' + webmd.htmlEncode(url) + '"\>');
            this._fixImageSizes();
        },

        length: function(typeHtml) {
            var $b = $('body', this.iframeDoc);
            if (typeHtml) {
                return jQuery.trim($b.html()).length;
            } else {
                return jQuery.trim($b.text()).length;
            }
        },

        // Function: _exec
        // Purpose:  Run a designMode command on the selected text
        // Notes:
        // http://msdn.microsoft.com/en-us/library/ms533049(VS.85).aspx
        // http://www.mozilla.org/editor/midas-spec.html
        //
        _exec: function(command, option) {

            var w = this.iframe.contentWindow, range;

            w.focus();

            try {
                w.document.execCommand(command, false, option);
            } catch (e) {

                // IE doesn't support inserthtml, so insert it a different way
                if (command === 'inserthtml') {
                    range = this.iframeDoc.selection.createRange();
                    if (!(range.boundingTop == 2 && range.boundingLeft == 2)) {
                        range.pasteHTML(option);
                        range.collapse(false);
                        range.select();
                    }
                }
            }

            w.focus();
        },

        // Function: _get
        // Purpose:  Return the raw text from the editor
        // Returns:  (string)
        //
        _get: function() {
            return $('body', this.iframeDoc).html();
        },

        // Function: _addTitlesToLinks
        // Purpose:  Add a title attribute to the link, so the user gets a tooltip to see what the link is
        // Notes:    We will remove the title attribute in post-processing before it is submitted.
        //
        _addTitlesToLinks: function() {

            $('a:not([title])', this.iframeDoc).each(function() {

                var href = $(this).attr('href');
                $(this).attr('title', 'Link: ' + href);

            });

        },

        _fixImageSizes: function() {
            var self=this, iframeWidth = $(self.iframe).width() * .9;
            if (iframeWidth) {
                $('img', self.iframeDoc).each(function() {
                    var img = $(this), imageWidth = img.width();
                    if (img.is(':not(.fixed)')) {
                        // In case image hasn't loaded yet, give it a load event.
                        img.addClass('fixed').load(function(){ self._fixImageSizes(); });
                    }
                    if (imageWidth > iframeWidth) {
                        img.width(iframeWidth);
                    }
                });
            }
        },

        // Function: _replaceEL
        // Purpose:  Replaces one element with another
        // Inputs:   j (jQuery) a jquery object for the element(s) to change
        //           newEl (string) type of new element to create
        // Examples:
        // > _replaceEl($('span'), 'div');
        //
        _replaceEl: function(j, newEl) {
            $(j).each(function() {
                var $el, $repl;
                $el = $(this);
                $repl = $('<' + newEl + '>').html($el.html());
                $el.replaceWith($repl);
            });
        },

        // Function: _preProcess
        _preProcess: function(s) {
            if (this.options.format === 'bbcode') {
                s = s.replace(/\[img\]([^\[]*)\[\/img\]/ig, '<img src="$1" />');
                s = s.replace(/\[url="([^"]*)"\]([^\[]*)\[\/url\]/ig, '<a href="$1">$2</a>');
                s = s.replace(/\[(\/?)(b|blockquote|i|u|s|ul|ol|li|p|br)(\s*\/)*\]/ig, '<$1$2$3>');
            }
            return s;
        },

        // Function: _postProcess
        // Purpose:  Post-process the HTML to make it cleaner
        // Inputs:   s (string) html content to process
        // Returns:  (string)
        //
        _postProcess: function(s) {

            var $s, m;

            // First use jQuery to change some of the elements.
            // It would be hard to do this using regular expressions,
            // because of nested elements.

            $s = $('<div></div>').html(s);

            // Change EM, STRIKE, STRONG elements
            this._replaceEl($s.find('strong'), 'b'); // IE
            this._replaceEl($s.find('em'), 'i'); // IE
            this._replaceEl($s.find('strike'), 's'); // Firefox

            // Change SPAN to B, I, U, or S (Safari)
            if ($s.find('span[class="Apple-style-span"]').length) {
                // Note we can't use attribute matching in jQuery for the the style attribute [style=value],
                // so we must use an alternate method to fine the elements
                this._replaceEl($s.find('span').filter(function() { return $(this).attr('style').indexOf('bold') != -1; }), 'b');
                this._replaceEl($s.find('span').filter(function() { return $(this).attr('style').indexOf('italic') != -1; }), 'i');
                this._replaceEl($s.find('span').filter(function() { return $(this).attr('style').indexOf('underline') != -1; }), 'u');
                this._replaceEl($s.find('span').filter(function() { return $(this).attr('style').indexOf('line-through') != -1; }), 's');
            }

            // Get the HTML back into a string so we can do additional fixes
            // using regular expressions
            s = $s.html();

            // Remove DIV elements (Safari)
            s = s.replace(/<div>\s*(<br[^>]*>)\s*<\/div>/ig, '$1');
            s = s.replace(/^<div>/ig, '');
            s = s.replace(/<div>/ig, '<br />');
            s = s.replace(/<\/div>/ig, '');

            // Change P elements into a BR elements (IE)
            s = s.replace(/\s*<p[^>]*>/ig, '');
            s = s.replace(/<\/p[^>]*>/ig, '<br />');

            // Fix BR and IMG elements without closing slash (IE)
            s = s.replace(/<br\s*>/ig, '<br />');
            s = s.replace(/<(img[^>]+[^\/])>/ig, '<$1 />');

            // Remove trailing space

            s = s.replace(/\s*&nbsp;\s*/ig, ' ');
            s = s.replace(/(\s+|&nbsp;|<br\s*\/?>)+$/ig, '');

            // Fix any open LI elements
            s = s.replace(/<li\b[^>]*>/ig, '</li><li>').replace(/<\/li\b[^>]*>\s*<\/li\b[^>]*>/ig, '</li>').replace(/<(ul|ol)\b[^>]*>\s*<\/li\b[^>]*>/ig, '<$1>')

            // Remove comments
            s = s.replace(/<!--(.|\s)*?-->/g, '');

            // Remove directives like <?xml>
            s = s.replace(/<\?(.|\s)*?>/g, '');

            // Remove elements and attributes that are not whitelisted
            s = s.replace(/<(\/?)(\w+)([^>]*)>/ig, function(s, slash, el, attr) {

                el = el.toLowerCase();
                if ($.inArray(el, ['a', 'b', 'blockquote', 'i', 'u', 's', 'ul', 'ol', 'li', 'img', 'p', 'br']) === -1) {
                    return '';
                }

                if (el === 'a') {
                    // Remove anything but the href attribute
                    attr = attr.replace(/.*(href="[^">]*").*/i, ' $1');
                } else if (el === 'img') {
                    // Remove anything but the src attribute
                    attr = attr.replace(/.*(src="[^">]*").*/i, ' $1 /');
                } else {
                    // Remove any attributes on other elements
                    if (attr.match(/\/$/)) {
                        attr = ' /';
                    } else {
                        attr = '';
                    }
                }
                return '<' + slash + el + attr + '>';
            });

            // Collapse extra space and newlines
            s = s.replace(/\s+/g, ' ');

            // Convert to BBCode?
            if (this.options.format === 'bbcode') {

                //s = s.replace(/\[/g, '&91;');
                //s = s.replace(/\]/g, '&93;');

                s = s.replace(/<img([^>]*)src="([^>]*)"([^>]*)>/ig, '[img]$2[/img]');
                s = s.replace(/<a([^>]*)href="([^>]*)"([^>]*)>/ig, '[url="$2"]');
                s = s.replace(/<\/a>/ig, '[/url]');

                // Since we have stripped out invalid elements and attributes,
                // and the rest of the bbcode elements are the same as the HTML elements,
                // we can just convert the angle brackets to square brackets
                //s = s.replace(/<([^>]+)>/ig, '[$1]');

                // Convert HTML elements to bbcode
                s = s.replace(/<(\/?)(\w+)([^>]*)>/g, '[$1$2$3]');
            }

            s = webmd.p.exch.replaceWordChars(s);

            return s;
        }
    };

    //----------------------------------------------------------------------
    // jQuery plugin to create an editor, with a toolbar and counter.
    //
    $.fn.rte = function(options) {

        // Function: isUrl
        // Returns:  Boolean
        //
        function isUrl(s) {
            var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
            return regexp.test(s);
        }

        // Function: htmlEncode
        // Purpose:  Make text safe to insert on the page
        // Inputs:   s (string)
        //
        function htmlEncode(s) {
            return s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
        }

        // Set default options.
        // Note you can also specify options for RteController (see above).
        //
        options = $.extend({
            counter: 4000,
            counterOnSubmit: true
        }, options);

        // Iterate and construct the RTEs
        return this.each(function() {

            var
            $counter,
            $ta = $(this),
            $tb,
            rte;

            // Check if the RTE was already created
            if ($ta.data('rte')) {
                rte = $ta.data('rte');
                rte.show();
                return;
            }

            // Create the RTE
            rte = new RteController($ta, options);

            // Attach the rte to the textarea so you can get to it later if necessary
            $ta.data('rte', rte);

            // Create a toolbar. Note a CSS sprite supplies the icons and replaces the text.
            $tb = $('<div class="rte-toolbar">' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-bold" title="Bold">Bold</a>' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-italic" title="Italic">Italic</a>' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-underline" title="Underline">Underline</a>' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-strikethrough" title="Strikethrough">Strikethrough</a>' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-ul" title="Unordered List">Bullet List</a>' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-ol" title="Ordered List">Numbered List</a>' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-link" title="Link">Add Link</a>' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-unlink" title="Remove Link">Remove Link</a>' +
                    '<a href="#" onclick="return false;" class="rte-toolbar-img" title="Add Image">Insert Image</a>' +
                    '</div>');
            $tb.find('.rte-toolbar-bold').click(function() {
                rte.formatBold();
                return false;
            });
            $tb.find('.rte-toolbar-italic').click(function() {
                rte.formatItalic();
                return false;
            });
            $tb.find('.rte-toolbar-underline').click(function() {
                rte.formatUnderline();
                return false;
            });
            $tb.find('.rte-toolbar-strikethrough').click(function() {
                rte.formatStrikethrough();
                return false;
            });
            $tb.find('.rte-toolbar-ol').click(function() {
                rte.formatOl();
                return false;
            });
            $tb.find('.rte-toolbar-ul').click(function() {
                rte.formatUl();
                return false;
            });
            $tb.find('.rte-toolbar-img').click(function() {

                var img = 'http://';

                while (true) {

                    img = window.prompt('Enter an image URL:', img);
                    img = webmd.p.exch.urlAddHttp(img);

                    if (!img) {

                        return false;

                    } else if (!webmd.p.exch.urlIsValidAlert(img)) {

                    } else {

                        rte.formatImg(img);
                        return false;

                    }
                }
            });
            $tb.find('.rte-toolbar-link').click(function() {

                var
                link = 'http://',
                linkE = '';

                while (true) {

                    link = prompt('Enter a link URL:', link);
                    link = webmd.p.exch.urlAddHttp(link);

                    if (!link) {

                        return false;

                    } else if (!webmd.p.exch.urlIsValidAlert(link)) {

                    } else {

                        if (rte.getSelectedText()) {
                            rte.formatLink(link);
                        } else {
                            linkE = htmlEncode(link);
                            rte.insertHtml('<a href="' + linkE + '">' + linkE + '</a>');
                        }

                        return false;
                    }
                }
            });
            $tb.find('.rte-toolbar-unlink').click(function() {
                rte.formatUnlink();
                return false;
            });

            // Add the toolbar to the page, before the textarea
            $ta.before($tb);

            // Create a counter
            if (options.counter) {

                $counter = $('<div class="rte-counter"></div>');

                $(rte.iframe).after($counter);

                $ta.bind('rtekeyup', function(event, rte) {

                        var
                        count = rte.length(),
                        left = 0,
                        leftTxt = '',
                        html = '';

                        html = '<span class="rte-counter-max">' +
                            options.counter +
                            ' characters max' +
                            '</span>';

                        left = options.counter - count;

                        if (left == 1) {
                            leftTxt = '1 character left';

                            $('#exchange-post-enabled_' + options.unique_id).show();
                            $('#exchange-post-disabled_' + options.unique_id).hide();
                        } else if (left >= 0) {
                            leftTxt = left + ' characters left';
                            $('#exchange-post-enabled_' + options.unique_id).show();
                            $('#exchange-post-disabled_' + options.unique_id).hide();
                        } else {
                            leftTxt = '<span class="rte-counter-over">' +
                            Math.abs(left) + ' too many characters!' +
                               '</span>';
                            $('#exchange-post-enabled_' + options.unique_id).hide();
                            $('#exchange-post-disabled_' + options.unique_id).show();
                        }

                        html += ' / <span class="rte-counter-left">' + leftTxt + '</span>';

                        $counter.html(html);
                    })
                    .trigger('rtekeyup', [rte]);
            }
        }); // each

    }; // jQuery.rte

})(jQuery);
//JQueryRTE--End

if (webmd.useragent.getDevice() == "ipad" || webmd.useragent.getDevice() == "iphone") { // if iphone or ipad ...

//JQueryRTE--Start
/*! $Id: jquery.rte.js 189 2009-06-15 17:30:31Z pfitzgerald $
* WebMD rich text editor
* Is loosley based on jQuery RTE plugin 0.5.1
* Copyright (c) 2009 Batiste Bieler
* Distributed under the GPL Licenses.
* Distributed under the The MIT License.
*/

(function($) {

    function RteController(textarea, options) {

        // Save the textarea in th object. Use $()[0] just in case a jQuery object was passed in.
        this.textarea = $(textarea)[0];

        // Initialize the edtior
        this.init(options);
    }

    // Prototype methods for the RTE object
    RteController.prototype = {

        // Function: init
        // Purpose:  Initialize the editor
        // Inputs:   options (object)
        //
        init: function(options) {

            var content, css, doc, i, idoc,
            self = this,
            $ta = $(self.textarea);

			// Initialize and trim the textarea
			$ta.val($.trim($ta.val()));

            // Set default options and override the defaults
            self.options = $.extend({
                css: 'body{font-family:Arial,Verdana,Helvetica,sans-serif;font-size:10pt;margin:0;padding:.5em;} p{margin:0;border:0}',
                syncOnSubmit: true,
                height: '200',
                format: 'bbcode'
            }, options);


			// we might need to set textarea height with this
            //i.height = self.options.height || '100%';

			// trigger rtekeyup
			$ta.keyup(function(){ $(this).trigger('rtekeyup', [self]); });
        },

        // Function: show
        // Purpose:  Shows the editor iframe and hides the textarea
        //
        show: function() {
            $(this.textarea).show();
        },

        // Function: hide
        // Purpose:  Hides the editor iframe and shows the textarea
        //
        hide: function() {
        },

        // Function: get
        // Purpose:  Returns the html from the editor. Also fixes the HTML to make it better.
        // Returns:  (string) the html
        //
        getContent: function() {
            // Get the html from the editor, then post-process it to fix the html
            return $(this.textarea).val();
        },

        // Function: set
        // Purpose:  Set content into the editor
        // Inputs:   s (string) the html to insert in the editor
        setContent: function(s) {
            $(this.textarea).val(s);
        },

        getSelectedText: function() {
            return this.getContent();
        },

        insertHtml: function(s) {
            // In IE, 'inserthtml' is not supported, but _exec() has a special case to handle it
            this.setContent(s);
        },

        // Function: sync
        // Purpose:  Copy the content from the editor back into the textarea
        // Returns:  (string) the html
        //
        sync: function() {
        },

        length: function(typeHtml) {
            return $(this.textarea).val().length;
        }
    };

    //----------------------------------------------------------------------
    // jQuery plugin to create an editor, with a toolbar and counter.
    //
    $.fn.rte = function(options) {

        // Set default options.
        // Note you can also specify options for RteController (see above).
        //
        options = $.extend({
            counter: 4000,
            counterOnSubmit: true
        }, options);

        // Iterate and construct the RTEs
        return this.each(function() {

            var
            $counter,
            $ta = $(this),
            $tb,
            rte;

            // Check if the RTE was already created
            if ($ta.data('rte')) {
                rte = $ta.data('rte');
                rte.show();
                return;
            }

            // Create the RTE
            rte = new RteController($ta, options);

            // Attach the rte to the textarea so you can get to it later if necessary
            $ta.data('rte', rte);

            // Create a counter
            if (options.counter) {

                $counter = $('<div class="rte-counter"></div>');

                $ta.after($counter);

                $ta.bind('rtekeyup', function(event, rte) {

                    var
                    count = rte.length(),
                    left = 0,
                    leftTxt = '',
                    html = '';

                    html = '<span class="rte-counter-max">' +
                        options.counter +
                        ' characters max' +
                        '</span>';

                    left = options.counter - count;

                    if (left == 1) {
                        leftTxt = '1 character left';

                        $('#exchange-post-enabled_' + options.unique_id).show();
                        $('#exchange-post-disabled_' + options.unique_id).hide();
                    } else if (left >= 0) {
                        leftTxt = left + ' characters left';
                        $('#exchange-post-enabled_' + options.unique_id).show();
                        $('#exchange-post-disabled_' + options.unique_id).hide();
                    } else {
                        leftTxt = '<span class="rte-counter-over">' +
                            Math.abs(left) + ' too many characters!' +
                            '</span>';
                        $('#exchange-post-enabled_' + options.unique_id).hide();
                        $('#exchange-post-disabled_' + options.unique_id).show();
                    }

                    html += ' / <span class="rte-counter-left">' + leftTxt + '</span>';

                    $counter.html(html);
                })
                    .trigger('rtekeyup', [rte]);
            }
        }); // each

    }; // jQuery.rte

})(jQuery);
	//JQueryRTE--End


}


//JQueryCookie--Start
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
//JQueryCookie--End
//webmd.p.exch20--Start
// Code for the WebMD Exchanges product
// Requires: jquery

//----------------------------------------------------------------------
// Functions to deal with replies
//
webmd.p.exch.reply = {

    // Function: displayForm()
    // Inputs:   el (Element) A reply link
    //
    displayForm: function(el) {

        var $a = $(el), $clone, $form, $alertDiv;
        // Determine where we should insert the form.
        // Traverse back up to the parent, then look for the form to insert
        $form = $a.closest('.exchange-reply-container').find('form.exchange-reply-form').eq(0);
        if (!$form.length) {
            throw ('webmd.p.exch.reply.displayForm cannot find insertion point for reply form.');
        }


        // Make sure we don't try to add the form twice
        if ($form.data('added')) {
            $a.hide();
	    $('#x' + el.id).attr('style', 'display: inline;');
            $form.show();
            return;
        }
        $form.data('added', true);

        // Get the template to use for the reply form
        $clone = $('#template-reply').children().clone();
        if (!$clone.length) {
            throw ('webmd.p.exch.reply.displayForm cannot find form template.');
        }

        $clone.find('.template-reply-innercontainer').attr('id', 'template-reply-innercontainer_' + el.id);
        $clone.find('#exchange-post-enabled').attr('id', 'exchange-post-enabled_' + el.id);
        $clone.find('#exchange-post-disabled').attr('id', 'exchange-post-disabled_' + el.id);

        var txt = 'comment';

        if (el.rel == 'forum') {
            txt = 'discussion';
            $clone.find('.reply-checkbox-type').show();
        }
        else if (el.rel == 'tip') {
            txt = 'tip';
        }
        else if (el.rel == 'resource') {
            txt = 'resource';
        }

        $clone.find('.reply-type').html(txt);


        $('.template-reply-cancel', $clone).click(function() {
            $form.hide();
            $('#x' + el.id).attr('style', 'display: none;');
            $a.show();
            return false;
        });



        // Add the reply form to the page
        $form.append($clone);
        $form.show();
        $a.hide();
        $('#x' + el.id).attr('style', 'display: inline;');

        // Turn the textarea into a rich text editor
        $('textarea', $clone).rte({ counter: 4000, unique_id: el.id });
    }
};
//webmd.p.exch20--End
//tips--Start
		   var imageurl = image_server_url;

                    // Function to switch the tip(s) being displayed

                    function changeTip(tip) {
                        var count = document.getElementById('nodeCount').innerHTML;
                        var prev = tip - 1;
                        var next = tip + 1;
			if (prev == 0) {
                            document.getElementById('img1').src = imageurl +'/images/tip_off_left.gif';
                            document.getElementById('img2').src = imageurl +'/images/tip_on_right.gif';
                            document.getElementById('btn1').href = '';
                            document.getElementById('btn2').href = 'javascript:changeTip(' + (tip + 1) + ')';
                        } else if (tip == count) {
                            document.getElementById('img1').src = imageurl +'/images/tip_on_left.gif';
                            document.getElementById('img2').src = imageurl +'/images/tip_off_right.gif';
                            document.getElementById('btn1').href = 'javascript:changeTip(' + (tip - 1)  + ')';
                            document.getElementById('btn2').href = '';
                        } else {
                            document.getElementById('img1').src = imageurl +'/images/tip_on_left.gif';
                            document.getElementById('img2').src = imageurl +'/images/tip_on_right.gif';
                            document.getElementById('btn1').href = 'javascript:changeTip(' + (tip - 1) + ')';
                            document.getElementById('btn2').href = 'javascript:changeTip(' + (tip + 1) + ')';
                        }
                        for (var i = 1; i <= count; i++) {
                            // checking for selected tip
                            if (i == tip) {
                                document.getElementById('tiphtml' + i).style.display = 'block';
                            } else {
                                document.getElementById('tiphtml' + i).style.display = 'none';
                            }
                        }
                    }
//tips--End

//JQModal--Start
/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Version: 03/01/2009 +r14
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 75,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);
//JQModal--End
//webmd.p.exchange.overlay--Start
/* webmd.p.exch.overlay.js */
// Requires: jquery, jqModal

webmd.p.exch.overlay = {

    id: 'exchOverlay',
    idClose: 'exchOverlayCloseButton',
    idContent: 'exchOverlayContent',
    className: 'exchOverlay',
    classNameBg: 'exchOverlayBg',
    timeout: 20000,

    // Anything within overlay with this class will trigger a close on click
    classNameClose: 'exchOverlayClose',

    // Use CSS to style the loading message
    msgLoading: '<div class="exchOverlayLoading">Loading...</div>',
    msgError: '<div class="exchOverlayError">An error occurred when loading this page.</div>',
    msgTimeout: '<div class="exchOverlayTimeout">A timeout occurred when loading this page.</div>',

    init: function() {

        if (this.div) { return; }

        // Initialize the overlay
        this.div =
            $('<div id="' + this.id + '" class="' + this.className + '">' +
              '<div class="' + this.classNameClose + '" id="'+ this.idClose +'">Close</div>' +
              '<div id="' + this.idContent + '"></div>' +
              '</div>')
            .hide()
            .appendTo('body')
            .jqm({ closeClass: this.classNameClose, overlayClass: this.classNameBg });
            // To disable modal closing if clicking outside the modal, replace with statement below
            // .jqm({closeClass:this.classNameClose, overlayClass:this.classNameBg, modal:true});

        this.content = $('#' + this.idContent);
    },

    html: function(html) {
        $(this.content).html(html);
        this.open();
    },

    load: function(url, params, callback) {
        var self = this, oldtimeout = jQuery.ajaxSettings.timeout;

        if ($.isFunction(params)) {
	    callback = params;
            params = null;
        }

        this.html(this.msgLoading);
        $.ajaxSetup({timeout:self.timeout});
        this.content.load(url, params, function(responseText, textStatus, XMLHttpRequest){
            if (textStatus == 'success') {
                // On success, the content has already been written into the div
                // Find anything with the close class, and make it close the overlay when clicked
                self.content.find('.' + self.classNameClose).click(function(){ self.close(); return false; });
            } else if (textStatus == 'timeout') {
                self.content.html(self.msgTimeout);
            } else {
                self.content.html(self.msgError);
            }

            if (callback) {
                callback(responseText, textStatus, XMLHttpRequest);
            }
        });
        $.ajaxSetup({timeout:oldtimeout});
    },

    open: function() {
        this.div.css('top', $(window).scrollTop() + 50); //to control position from top in pixels
        this.div.jqmShow();
    },

    close: function() {
        this.div.jqmHide();
    },

    setWidth: function(w) {
        this.div.css('width', w);
        this.div.css('marginLeft', -(Math.floor(w/2)+12));
    }
};

// Initialize the overlay on page ready
$(function(){
    webmd.p.exch.overlay.init();
});

//webmd.p.exchange.overlay--End
//webmd.p.exchange.interstitial--Start

// Set up a live event on the document, to be triggered whenever the user clicks any link in the main content area.
// When user clicks a link, if it is not in the whitelist, then display the overlay with some custom text.
$('#contentBackground_fmt a').live('click', function(e){

    // Ignore right click
    if (e.button !== 0) { return; }

    // "this" is the <a> element that was clicked
    var
    i,
    ctr,
    link = this,
    href = link.href,
    pathname=link.pathname,
    protocol=link.protocol.replace(':', '').toLowerCase(),
    host = link.hostname.toLowerCase(),
    whitelist = {
        protocols:[
            'javascript',
            'mailto'
        ],
        hosts:[
            '10.50.30.131',
            '64.62.177.27',
            'a1977.g.akamai.net',
            'emdeon.com',
			'feedproxy.google.com',
            'medicinenet.com',
            'medscape.com',
            'rxlist.com',
            'wbmd.com',
            'webmd.com',
            'webmd.compuserve.com',
            'webmd.netscape.com',
            'webmdcareers.net',
            'webmdtest.net'
        ],
        // If the whitelisted link matches this jQuery selector, then open in a new window
        openWinSelector:'a[rel=nofollow]'
    };

    function gotoWhitelist() {
        // Check if the link matches the openWinSelector, and if so open in a new window.
        if ($(link).is(whitelist.openWinSelector)) {
            if (window.open(href)) { return false; }
        }
        return true;
    }

    if (!href) { return true; }

    // Add the current location to the whitelist
    whitelist.hosts.push(window.location.hostname);

    // If this protocol is in the whitelist, let the href go through
    if ($.inArray(protocol, whitelist.protocols) >= 0) {
        return gotoWhitelist();
    }

    // Special case for /click links.
    // Note: IE strips the leading slash
    if (pathname == '/click' || pathname == 'click') {
        href = webmd.url.getParam('url', href) || href;

        // Handle metrics call from ctr cookie "pagename_module_link"
        // Remove the "pagename_" part.
        ctr = webmd.cookie.get('ctr').replace(/.*?_/, '');
        if (ctr) { wmdPageLink(ctr); }

    } else {

        // If link hostname is in the whitelist, let the href go through
        for (i=0; i < whitelist.hosts.length; i++) {
            if (host.indexOf(whitelist.hosts[i]) >= 0) {
                return gotoWhitelist();
            }
        }
    }

    // If we get here, the href is not in the whitelist, so display an interstitial.

    // Don't run until the page is ready
    $(function(){

        webmd.p.exch.overlay.load('/api/proxy/proxy.aspx?url=' + image_server_url + '/webmd/consumer_assets/site_images/exchange/modals/modal_leave_this_exchange.html', function(responseText, textStatus) {

            // Add a click event to open a new window to the href
            if (textStatus == 'success') {
                webmd.p.exch.overlay.content.find('form')
                    .submit(function(){
                        var w = window.open(href);
                        webmd.p.exch.overlay.close();
                        if (!w) { window.location = href; } // if couldn't open a window, just follow the href
                        return false;
                    });
            }
        });
    });

    // Prevent the browser from following the href
    return false;
});

//webmd.p.exchange.interstitial--End
// groupstory--Start
function EditStory()
{
	$get("editstory").style.display = "block";
	//hook up text area to rte
	$("textarea.story").rte({ format: 'bbcode' });
	var newStoryLink = $('#newStoryLink');
	var offPreview = $get("offPreview");
	var story =	$('textarea.story').data('rte');
	if(newStoryLink.length > 0 && offPreview.innerHTML.length == 0)
	{
		story.setContent("");
	}
	$get("mystory").style.display = "none";
}

function CancelEditStory()
{
	$get('editstory').style.display = "none";
	$get('mystory').style.display = "block";
}

function DeleteStory()
{
	var answer = confirm("Are you sure you want to delete your story?");
	if(answer)
	{
		$get('updateAction').value = 'delete';
		document.aspnetForm.submit();
	}
}

function SaveStory()
{
	//check to see if there is a story
	var story = $('textarea.story').data('rte').getContent();
	if(story.length == 0 || story == 'Tell us your story!')
	{
		alert("Please enter your story.");
		return false;
	}
	$get('updateAction').value = 'save';
}
// groupstory--End
// reporting abuse --start
var x_report_appname;
var x_report_objectid;
var x_report_ownerid;

function AdminReport(appname, objectid, ownerid, hide)
{
	//Check for auth cookie
	if(isLoggedInWebMD())
	{
		x_report_appname = appname;
		x_report_objectid = objectid;
		x_report_ownerid = ownerid;
		var job = new Object();
		var url;
		if(appname == 'profilepic'){
			url = '/api/space/SpaceService.asmx/AdminModerateMedia';
		}
		else {
			url = '/api/moderation/ApiModerationService.svc/json/AdminModerate';
		}
		job.siteId = space_site_id;
		job.appName= x_report_appname;
		job.objectId = x_report_objectid;
		job.ownerId = x_report_ownerid;
		job.toHide = hide;
		job.spaceId = space_id;
		$.ajax({
			dataType: 'json',
			type: 'POST',
			contentType: 'application/json',
			data: webmd.json.stringify(job),
			url: url,
			timeout:10000,
			success: function(data) {
			},
			failure: function(data) {
				alert('Error');
			}
		});

	}
	else
	{
		//*** NEED TO UPDATE PER ENVIRONMENT... THIS IS THE REGISTRATION URL FOR LOGIN**$$//
		window.location = reg_server + 'returl=' + location.href;
	}
	return false;
}
function ShowReportPopup(appname, objectid, ownerid, proxytarget, modalwidth)
{
	//Check for auth cookie
	if(isLoggedInWebMD())
	{
		x_report_appname = appname;
		x_report_objectid = objectid;
		x_report_ownerid = ownerid;
		ShowModal(proxytarget,modalwidth);
	}
	else
	{
		//*** NEED TO UPDATE PER ENVIRONMENT... THIS IS THE REGISTRATION URL FOR LOGIN**$$//
		window.location = reg_server + 'returl=' + location.href;
	}
	return false;
}

function ShowModal(proxytarget, modalwidth)
{
	webmd.p.exch.overlay.setWidth(modalwidth);
	webmd.p.exch.overlay.load('/api/proxy/proxy.aspx?url=' + proxytarget);
	return false;
}

function Report(text, code)
{
    var job = new Object();
    var url;
    if(x_report_appname == 'profilepic'){
      url = '/api/space/SpaceService.asmx/ModerateMedia';
    }
    else {
      url = '/api/moderation/ApiModerationService.svc/json/ModerateObject';
    }
    job.siteId = space_site_id;
    job.appName= x_report_appname;
    job.objectId = x_report_objectid;
    var ruserid = webmd.p.exch.lbmonitor.getUserId();
    job.userId = ruserid;
    job.ownerId = x_report_ownerid;
    job.flagType = parseInt(code);
    job.flagText = text;
    $.ajax({
        dataType: 'json',
        type: 'POST',
        contentType: 'application/json',
        data: webmd.json.stringify(job),
        url: url,
        timeout:10000,
        success: function(data) {
            ShowModal(image_server_url + '/webmd/consumer_assets/site_images/exchange/modals/modal_report_sent.html','415');
        },
            failure: function(data) {
                alert('Error');
        }
    });

}

function UrlEncode(text)
{
        var encodedtext = encodeURIComponent(text);
        encodedtext = encodedtext.replace("+", "%2B");
        encodedtext = encodedtext.replace("/", "%2F");
        encodedtext = encodedtext.replace(".", "%2E");
		return encodedtext;
}
// reporting abuse --end
//Inline Registration-- Start
/*!
 * postMessage - v0.5 - 9/11/2009
 * http://benalman.com/
 *
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Licensed under the MIT license
 * http://benalman.com/about/license/
 */
(function($){
  '$:nomunge'; // Used by YUI compressor.

  // A few vars used in non-awesome browsers.
  var interval_id,
    last_hash,
    cache_bust = 1,

    // A var used in awesome browsers.
    rm_callback,

    // A few convenient shortcuts.
    window = this,
    FALSE = !1,

    // Reused internal strings.
    postMessage = 'postMessage',
    addEventListener = 'addEventListener',

    p_receiveMessage,

    // I couldn't get window.postMessage to actually work in Opera 9.64!
    has_postMessage = window[postMessage] && !$.browser.opera;

  $[postMessage] = function( message, target_url, target ) {
    if ( !target_url ) { return; }

    // Serialize the message if not a string. Note that this is the only real
    // jQuery dependency for this script. If removed, this script could be
    // written as very basic JavaScript.
    message = typeof message === 'string' ? message : $.param( message );

    // Default to parent if unspecified.
    target = target || parent;

    if ( has_postMessage ) {
      // The browser supports window.postMessage, so call it with a targetOrigin
      // set appropriately, based on the target_url parameter.
      target[postMessage]( message, target_url.replace( /([^:]+:\/\/[^\/]+).*/, '$1' ) );

    } else if ( target_url ) {
      // The browser does not support window.postMessage, so set the location
      // of the target to target_url#message. A bit ugly, but it works! A cache
      // bust parameter is added to ensure that repeat messages trigger the
      // callback.
      target.location = target_url.replace( /#.*$/, '' ) + '#' + (+new Date) + (cache_bust++) + '&' + message;
    }
  };

  $.receiveMessage = p_receiveMessage = function( callback, source_origin, delay ) {
    if ( has_postMessage ) {
      // Since the browser supports window.postMessage, the callback will be
      // bound to the actual event associated with window.postMessage.

      if ( callback ) {
        // Unbind an existing callback if it exists.
        rm_callback && p_receiveMessage();

        // Bind the callback. A reference to the callback is stored for ease of
        // unbinding.
        rm_callback = function(e) {
          if ( ( typeof source_origin === 'string' && e.origin !== source_origin )
            || ( $.isFunction( source_origin ) && source_origin( e.origin ) === FALSE ) ) {
            return FALSE;
          }
          callback( e );
        };
      }

      if ( window[addEventListener] ) {
        window[ callback ? addEventListener : 'removeEventListener' ]( 'message', rm_callback, FALSE );
      } else {
        window[ callback ? 'attachEvent' : 'detachEvent' ]( 'onmessage', rm_callback );
      }

    } else {
      // Since the browser sucks, a polling loop will be started, and the
      // callback will be called whenever the location.hash changes.

      interval_id && clearInterval( interval_id );
      interval_id = null;

      if ( callback ) {
        delay = typeof source_origin === 'number'
          ? source_origin
          : typeof delay === 'number'
            ? delay
            : 100;

        interval_id = setInterval(function(){
          var hash = document.location.hash,
            re = /^#?\d+&/;
          if ( hash !== last_hash && re.test( hash ) ) {
            last_hash = hash;
            callback({ data: hash.replace( re, '' ) });
          }
        }, delay );
      }
    }
  };

})(jQuery);

/*! webmd.p.exch.reg.js */
// Requires: scripts.js, webmd.p.exch.overlay, jquery.ba-postmessage.js

// Function wrapper to require the user to be logged in
webmd.p.exch.requireLogin = function(callback) {
    var
    iframeUrl= reg_api + '/iframe/default/index.html',
    iframeWidth=600,
    iframeHeight=205,
    iframeClass='regIFrame',
    exchUrl='http://' + prefix + '.' + domain + '/lbmonitor.aspx?spacename=' + space_name, // url to set exchanges cookie
    exchCookie='GRP_USER', // name of the exchanges cookie
    forumsDomain='forums.' + domain,
    pagename,
    metricsPagename,
    errorMsg = 'Sorry, we are experiencing a problem. Please try to log in again shortly.',
	inline = true,
    msg = {
        noRegCookie: errorMsg  + ' (E101)', // no webmd auth cookie set
        noExchCookie: errorMsg + ' (E102)', // lbmonitor contacted, but not cookie set
        noLbmonitor: errorMsg  + ' (E103)'  // could not contact lbmonitor
    };


    if (!callback) {
		callback = function(){};
		inline = false;
	}

    // Check if the user is already logged in
    if (isLoggedInExch() || (!space_name && isLoggedInWebMD())) {

        // Pass "false" to the callback to indicate that the action
        // was not interrupted.
		//webmd.p.exch.overlay.close();
        return callback(false);

    } else {

        // Clear the document hash. Can't remove it entirely
        // or set it to '#' or it will scroll the page.
        if (window.location.hash) {
            window.location.hash = '_';
        }

        // Add this page exact url to the iframe URL,
        // so it can communicate back to us without changing the page.
        // Note: Temporarily to support new and old funcationality,
        // pass pagename in a parameter (new) and in the hash (old)
        pagename = encodeURIComponent( document.location.href.replace(/#.*/, '') );
        metricsPagename = encodeURIComponent(window.s_md.pagename || window.s_pagename || document.location.href.replace(/[\?#].*/, ''));
        iframeUrl += '?pagename=' + pagename + '&s_pagename=' + metricsPagename;


		function loadOverlay(){
			//loads js when not loaded

			var signin_params={
				appid: 	5,
				returl: '',
				inline: inline
			};

			if (!webmd.p.registration) {
				webmd.p.registration = {};
			}
			if(!webmd.p.registration.loginOverlay) {
				webmd.load({
					js:'/api/proxy/proxy.aspx?url=' + image_server_url + "/webmd/PageBuilder_Assets/JS_static/registration/loginOverlay.js?sdfjk",
					load: function() {
						webmd.p.registration.loginOverlay.show(signin_params);
					}
				});
			}else{
				return true;
			}
		}
		//alert(callback);
		loadOverlay();

		/*
        // Open an overlay, and display an iframe for the registration form
        webmd.p.exch.overlay.setWidth(iframeWidth);
        webmd.p.exch.overlay.html(webmd.substitute(
            '<div class="exchOverlayLoading">Loading...</div><iframe src="{src}" class="{className}" width="{width}" height="{height}" frameborder="0" scrolling="no" style="display:none" onload="$(this).show().prev().hide()"/>',
            { src:iframeUrl, width:iframeWidth, height:iframeHeight, className:iframeClass }
        ));
		*/

        // Set up a listener so the iframe can tell us when it is done
        $.receiveMessage(function(e){

            var h, hSave;

            // Clear the document hash. Can't remove it entirely
            // or set it to '#' or it will scroll the page.
            if (window.location.hash) {
                window.location.hash = '_';
            }

            if (e.data.indexOf('login_done') != -1) {
                $.receiveMessage(); // stop listening
                webmd.overlay.close();

                if (!isLoggedInWebMD()) {
                    // ERROR: the WMD_AUTH cookie was not set
		    alert(msg.noRegCookie);
		    return false;
                }

                if (!space_name) {
                    webmd.p.exch.requireLoginAfter();
		    callback(true);
                    return;
                }

		// Set the exchanges cookie then do the callback if successful
                webmd.p.exch.lbmonitor.refresh({

		    success:function(){
			if (isLoggedInExch()) {
                            webmd.p.exch.requireLoginAfter();
			    // Pass "true" to the success function to indicate that
			    // the action was interupted to make the user log in.
			    // This lets you detect if a form submittal was
			    // interrupted, so you can resubmit the form.
				webmd.overlay.close();
			    callback(true);

			} else {
                            // ERROR: lbmonitor returned successfully but did not set the GRP_USER cookie
			    alert(msg.noExchCookie);
                            //window.location.reload();
			}
		    },

		    error:function(){
                        // ERROR: lbmonitor was not contacted successfully
			alert(msg.noLbmonitor);
                        //window.location.reload();
		    }
                });

            } else if (e.data.indexOf('login_cancel') != -1) {

                // Canceled the log in
                $.receiveMessage(); // stop listening
                webmd.p.exch.overlay.close();

            } else if (e.data.indexOf('login_height') != -1) {

                h = Number( e.data.replace( /.*login_height=(\d+)(?:&|$)/, '$1' ) );

                if ( !isNaN( h ) && h > 0 && h !== hSave ) {
                    // Height has changed, update the iframe.
                    $('iframe.' + iframeClass).height( hSave = h );
                }
            }

        });

        return false;
    }
};

webmd.p.exch.requireLoginAfter = function(){
    // Code to run after incontext login
    webmd.p.exch.leftNav.refresh();
};

/*! END webmd.exch.reg.js */

//Inline Registration-- End

//LoginShowReportPopup -- Begin
function LoginShowReportPopup(type,id,creator,url,width) {
    return webmd.p.exch.requireLogin(function(){ ShowReportPopup(type,id, creator,url,width); });
}
//LoginShowReportPopup -- End
//WebX Tip/Resource Vote -- Start
function webxVote(vote)
{
	if (vote == "yes")
	{
		document.getElementById('helpful_x').innerHTML = parseInt(document.getElementById('helpful_x').innerHTML) + 1;
	}
	document.getElementById('helpful_y').innerHTML = parseInt(document.getElementById('helpful_y').innerHTML) + 1;
}
//WebX Tip/Resource Vote -- End

//Start Explicit Member join -- Start
function BecomeExplicit()
{
    var answer = false;

    // Prompt the user only if user is not already an implicit member.
    // If the lbmonitor cookie was not found, then do not prompt the user
    if(webmd.p.exch.lbmonitor.getIsMember() === false) // would return null if cookie was not found
    {
	answer = confirm('You have just contributed to the ' + space_title + ' Community. This community has a member directory. Would you like to be displayed in this directory?');

        if (answer) {
            wmdPageLink('he-join_join');
        }
    }

    return answer;
}



//
// webmd.m.exch.charCounter
//
// add character counters to specified textareas, optionally enable/disable
// a button when textareas exceed max character count (toggle image source and class name)
//
// @param array textareas each item should be a json object:
//  json.maxchars number max chars for textarea
//  json.selector text jQuery selector for the textarea
//  json.text_count text
//  json.text_divider text
//  json.text_error text
//  json.text_max text
//   json.text_x vars fill various spans in the counter
//   can use these tokens in any of vars:
//   {maxchars} maximum character
//   {over} number of characters over the limit
//   {remaining} remaining characters
//
//
// @param object/optional btn
//  btn.off_class string class name for disabled button
//  btn.on_class string class name for enabled button
//  btn.off_img string URL for disabled image
//  btn.on_img string URL for enabled image
//  btn.selector string jQuery selector for button
//
webmd.p.exch.charCounter = function(textareas, btn) {

	// create empty object if btn param not specified, save btn jQuery
	btn = btn || {};
	var $btn = $(btn.selector);

	$.each(textareas, function(i, textarea) {

		// initial last status, changed by keyup function
		var lastStatus = true;

		// save the jQuery for each textarea
		textareas[i].$textarea = $(textarea.selector);

		// add counter output div for each textarea, save reference
		textareas[i].$counter = $('<div class="exchanges_charcount"></div>').insertAfter( textareas[i].$textarea );

		// merge default messages with overrides
		textareas[i].msgs = $.extend({}, {
			text_divider: ' / ',
			text_error : '{over} too many characters!',
			text_max : '{maxchars}  characters max',
			text_remaining: '{remaining} characters left'
		}, this);

		// add keyup function to each textarea
		textareas[i].$textarea
			.keyup(function() {

				var isValid = true;

				$.each(textareas, function() {

					var output, remaining, self = this;

					// messages
					remaining = self.maxchars-self.$textarea[0].value.length;

					// build output
					output = '<span class="exchanges_charcount';
					output += (remaining < 0) ? '_error' : '_ok';
					output += '">';
					output += '<span class="exchanges_charcount_max">'+self.msgs.text_max+'</span>';
					output += '<span class="exchanges_charcount_divider">'+self.msgs.text_divider+'</span>';
					output += '<span class="exchanges_charcount_remaining"';
					output += (remaining < 0) ? 'style="color:red;font-weight:bold;"' : '';
					output += '">';
					output += (remaining < 0) ? self.msgs.text_error : self.msgs.text_remaining;
					output += '</span>';
					output += '</span>';

					// sub content for tokens
					output = webmd.substitute(output, {
						count: self.$textarea[0].value.length,
						maxchars: self.maxchars,
						over: remaining*-1,
						remaining: remaining
					});

					// update counter
					self.$counter.html(output);

					// if current length exceeds maxlength
					if (self.$textarea[0].value.length > self.maxchars) {
						isValid = false;
					}

				});

				// only toggle buttons on status change
				if (isValid !== lastStatus) {

					// take action on buttons and input
					switch($btn[0].nodeName.toLowerCase()) {
						case 'button':
						case 'input':
							if (btn.off_class || btn.on_class) {
								if (isValid) {
									$btn
										.addClass(btn.on_class)
										.removeClass(btn.off_class)
										.removeAttr('disabled');
								} else {
									$btn
										.attr('disabled', 'disabled')
										.addClass(btn.off_class)
										.removeClass(btn.on_class);
								}
							}
							if (btn.off_img && btn.on_img) {
								if (isValid) {
									$btn[0].src = btn.on_img;
								} else {
									$btn[0].src = btn.off_img;
								}
							}
							break;
					}

					// update status
					lastStatus = isValid;

				}

			});

	});

	// trigger a keyup on the first selector to init the counters and button toggle
	textareas[0].$textarea.trigger('keyup');

};

function newPost(sExchange) {
    var _dte=new Date()
    var dEx=new Date(_dte.getFullYear(), _dte.getMonth(), _dte.getDate(), _dte.getHours(), _dte.getMinutes()+2, _dte.getSeconds());
    document.cookie = "newpost=" + sExchange  + "; path=/; domain=.webmd.com;expires=" + dEx.toGMTString();
    return true;
}


// Expert badges popup
$('.expert_badge_fmt, .guest_expert_badge_fmt, .sponsor_badge_fmt, .guest_sponsor_badge_fmt').live('click', function(){

	var domain = window.domain || 'webmd.com',
	url = 'http://exchanges.' + domain + '/webmd-exchanges/experts-guests-sponsors';

	if ($(this).is('.expert_badge_fmt')) {
		url += '#topic_guest';
	} else if ($(this).is('.guest_expert_badge_fmt')) {
		url += '#topic_guest-expert';
	} else if ($(this).is('.sponsor_badge_fmt')) {
		url += '#topic_sponsor';
	} else if ($(this).is('.guest_sponsor_badge_fmt')) {
		url += '#topic_sponsored-guest';
	}

	webmd.openWindow(url, {
		standard:true, name:'_blank', width:530, height:490, toolbar:0, status:0, left:25, top:25
	});

	return false;
});

webmd.p.exch.share = {

	className:'exchShareThis',
	imgBase: image_server_url + '/webmd/consumer_assets/site_images/exchange/images/',
	icons: {
		facebook: 'share-facebook.png',
		twitter: 'share-twitter.png'
	},

	preload: function() {
		var self = this;
		$.each(self.icons, function() {
			$('<img>').attr('src', self.imgBase + this);
		});
	},

	init: function() {

		var
		self = this,
		spans = $('span.' + self.className);

		if (!spans.length) {
			return;
		}

		// Find all hidden exchShareThis spans, and add share links to them
		spans.each(function(){

			var
			span = $(this),
			a = span.find('a:first'),
			o = {
				url: a[0].href || '',
				title: 'WebMD: ' + a.text(),
				desc: span.find('i').text() || ''
			};

			if (o.url) {

				// Fix the link by adding a hash tag
				o.url = o.url.replace(/\/\d+\/(\d+)$/, '$&#$1');

				// Attach the share data to the span so we can get to it in the click event
				span.data('share', o);

				span.html(' | ' +
						  '<a href="#" class="facebook" title="Share on Facebook"><img src="' + self.imgBase + self.icons.facebook + '" alt="Facebook" /></a> ' +
						  '<a href="#" class="twitter" title="Share on Twitter"><img src="' + self.imgBase + self.icons.twitter + '" alt="Twitter" /></a> ' +
						  '<a href="#" class="share" title="Share on other social bookmarking services">Share</a>' +
						  '</span>').show();
			}
		});

		// Create a single event to handle clicks on all share links
		spans.live('click', function(event){

			var
			data = $(this).data('share'),
			link = $(event.target);

			// Ignore right click
			if (event.button !== 0) {
				return;
			}

			// Ignore if click was not on a link
			if (!link.is('a,a img')) {
				return;
			}

			if (link.is('a.twitter img')) {
				data.title = self.truncate(data.title + ' | ' + data.desc, 100);
				self.share(data, 'twitter');
			} else if (link.is('a.facebook img')) {
				self.share(data, 'facebook');
			} else {
				self.share(data);
			}

			return false;
		});
	},

	share: function(o, service) {

		var
		url = 'http://api.addthis.com/oexchange/0.8' + (service ? '/forward/' + service : '') + '/offer',
		addThisUser = 'webmdnews';

		$.each({
			url:o.url,
			title:o.title,
			description:o.desc,
			template:'{{title}} {{url}}',
			username:addThisUser
		}, function(k,v){
			url = webmd.url.addParam(k, v, url);
		});

		this.biCall(o.url, service);
		this.interstitial(url);
	},

	truncate: function(s, len) {
		if (s.length > len - 4) {
			s = s.substring(0, len - 4);
			s = s.replace(/\s*\w+$/, ''); // remove last word
			s += '... ';
		}
		return s;
	},

	biCall: function(url, service) {
		var
		bi,
		serviceMap = {
			twitter:'twt',
			facebook:'fcb',
			digg:'dig',
			delicious:'del'
		};

		// Determine what type of link it is
		if (url.indexOf('/forum/') != -1) {
			bi = 'he-dis-shr';
		} else if (url.indexOf('/resource/') != -1) {
			bi = 'he-res-shr';
		} else if (url.indexOf('/tip/') != -1) {
			bi = 'he-tip-shr';
		} else {
			bi = 'he-ech-shr';
		}

		bi += '_' + (serviceMap[service] || '_shr');

		wmdPageLink(bi);
	},

	interstitial: function(url) {

		webmd.p.exch.overlay.load('/api/proxy/proxy.aspx?url=' + image_server_url + '/webmd/consumer_assets/site_images/exchange/modals/modal_share_this.html', function(responseText, textStatus) {

			// Add a click submit event for the form
			if (textStatus == 'success') {
				webmd.p.exch.overlay.content.find('form').submit(function(){
					var w = window.open(url);
					webmd.p.exch.overlay.close();
					if (!w) { window.location = url; } // if couldn't open a window, just follow the href
					return false;
				});
			}
		});
	}
};

/* Stop showing ShareIcons

// Preload share images immediately
webmd.p.exch.share.preload();

// Set up the share links when page is ready
$(function(){
	webmd.p.exch.share.init();
});

*/

// Temporary hack to fix profile page
$(function(){
	var
	imgFmt = $('.exchange_memberprofile_rdr .img_fmt:first'),
	changePic, reportPic, hidePic, showPic, ul;

	if (imgFmt[0]) {

		changePic = $('#changepicture');
		reportPic = $('#rptPic');
		hidePic = $('#adminHidePic');
		showPic = $('#adminShowPic');
		ul = $('<ul class="pic_options_fmt"></ul>');

		if (reportPic[0]) {
			ul.append($('<li>').append(reportPic));
			reportPic.text('Report This');
		}

		if (hidePic[0]) {
			ul.append($('<li>').append(hidePic));
			hidePic.text('Hide');
		}

		if (showPic[0]) {
			ul.append($('<li>').append(showPic));
		}

		changePic.appendTo(ul);

		if (ul.find('li').length > 1) {
			ul.find('li:first').addClass('first');
			ul.find('li:last').addClass('last');
		}

		imgFmt.append(ul);
	}

});

/* Content Feed submit content check for FB */
function contentFeedCheckForFB(el){
    var $parent = $(el).closest('.exchange-reply-container');
    var $frame = $parent.find('iframe');
    var content = $frame.contents().find('body').html();
    var lookForImage = function($el){
        var bool = false;
        var img = $el.find('img');
        var iLength = img.length;
        for(var j=0; j<iLength; j++){
            var $i = $(img[j]);
            if(!bool){
                src = $i.attr('src');
                if(src.length){
                    bool = ((src.indexOf('fbcdn') != -1) || (src.indexOf('facebook') != -1));
                }
            }
        }
        return bool;
    };
    var process = function($el, bool){
        if(bool){
            $el.remove();
        } else {
            var $children = $el.children();
            if($children.length && $children != ''){
                $el.replaceWith($children);
            } else {
                $el.remove();
            }
        }
    };
    if(content != ''){
        var  bool, src;
        var $holder = $('<div></div>').append(content);
        var $rem = $holder.find('a, form, input');
        var length = $rem.length;
        for(var i=0; i<length; i++){
            var $t = $($rem[i]);
            var tag = $t[0].tagName.toLowerCase();
            if(tag == 'a'){
                var href = $t.attr('href');
                if((href.indexOf('facebook') != -1) || (href.indexOf('album.php?profile') != -1) || (href.indexOf('photo.php?pid') != -1)){
                    bool = lookForImage($t);
                    process($t, bool);
                }
            } else if(tag == 'form'){
                bool = lookForImage($t);
                process($t, bool);
            } else if(tag == 'input'){
                src = $t.attr('src');
                if(src){
                    if((src.indexOf('facebook') != -1) || (src.indexOf('fbcdn') !=-1) || (src.indexOf('facebook') != -1)){
                        bool = lookForImage($t);
                        process($t, bool);
                    }
                }
            }
        }
        if($holder.length && $holder.html() != ''){
            $frame.contents().find('body').html($holder.html());
        }
        if(bool){
            alert('For the safety of your personally identifiable information, we have blocked the pasting of this image in the editor. Click the \<Add Photo\> button (represented by the camera icon) to include your photo.');
            return false;
        }
    }
    return true;
}

// Temporary hack used by links in content feed xsl
webmd.p.exch.gotoThread = function(a){
	// a is an <a> element on the page
	if (window.location.pathname.match(/\/search$/)) {
		// Search page - change /n1/n2 to /n1/n2#n2
		window.location = a.href.replace(/\/\d+\/(\d+)$/, '$&#$1');
	} else {
		// Other pages - change /n1/n2 to /n1
		window.location = a.href.replace(/(\/\d+)\/\d+$/, '$1');
	}
	return false;
}

/* Sets ExchangesAnnoucnement module visuals */
$(document).ready(function(){
    setAnnouncementStatus();
	carouselOveride();
});
var setAnnouncementStatus = function(){
    var $this = $('#announcement_messages');
    if($this.length){
        init();
    }
    function init(){
        var announcement = checkAnnouncementStatus();
        var module = checkModuleStatus(announcement);
        $this.css({display: (module) ? 'block' : 'none'});
        $('.announcement', $this).css({display: (announcement) ? 'block' : 'none'});
    }
    function checkAnnouncementStatus(){
        var path = window.location.pathname;
        var indexPage = new RegExp('^/(([0-9]|[-]|[a-z])+)/(([0-9]|[-]|[a-z])+)/index(/[^\?]*)?[\?]?(.*)$');
        var threadPage = new RegExp('^/([0-9]+)/(/[^\?]*)?[\?]?(.*)$');
        return !(path.match(indexPage) || path.match(threadPage));
    }
    function checkModuleStatus(bool){
        var children = $('.wrap', $this).children('div:not(".end")').length;
        return (bool && children > 0) ? true : false;
    }
};

var carouselOveride = function(){
	$('#divImageSelect #imgSelected').wrap('<div class="img_preview_rdr" />');
	$('h4.exchhdr').next('img').wrap('<div class="img_preview_rdr" />');
}

/* show short description for feed search results - temporarily disabled since it causes issues with very short posts (less than trim length)
webmd.p.exch.feedResults = {
	init: function() {
		var responseList = $('#ContentPane5 .exchange-reply-container');
		var $fullMarkup, $targetElm, $finalMarkup, $lastwordPos;
		for (var i=0;i<responseList.length;i++){
			$fullMarkup=$(responseList[i]).find('#fulltext'+(i+1)+' span:first-child').html().replace(/<(?:.|\s)*?>/g,' '); //Get First div in container, then strip all tags from it
			$lastwordPos=this.getLastWord($fullMarkup);
			$finalMarkup = $fullMarkup.substr(0,$lastwordPos)+"...";
			$targetElm=$('#resurl'+(i+1)).after($finalMarkup);
		}
	},
	getLastWord: function(str) {
		for (var j=120;j>0;j--){
			if( str.charAt(j)==" " ){
				return j;
			}
		}
	}
};

$(function(){
	if ( s_furl.toLowerCase().search("search")!= -1 ){
		webmd.p.exch.feedResults.init();
	}
});
*/

// work in progress message 06.01.11 rdh
/*
$(function(){
	if(document.location.href.match('forum') != null){
        	cancelPost = function() {
		location.href = "http://exchanges.perf.webmd.com/" + space_name;
	}
	$('div.right_buttons_post, div.right_buttons_posta').html('<style type="text/css">.right_buttons_post, div.right_buttons_posta{border:1px solid #ccc;margin: 10px 8px 0 0;padding:10px 4px 2px 10px;}.right_buttons_post .wip, div.right_buttons_posta .wip{text-align:left;font-weight:bold;padding:0 0 10px 0}.right_buttons_post span, div.right_buttons_posta span{color: red;}</style><div class="wip"><span>Work in Progress:</span><br/>New posts may take several minutes to display on the site.</div><a href="javascript:cancelPost()"><img width="67" height="23" border="0" class="template-reply-cancel" alt="Cancel" src="http://img.perf.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/exchange/images/btn_x_cancel.gif"></a> <input width="67" type="image" height="23" class="template-reply-post" alt="Create" src="http://img.perf.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/exchange/images/btn_x_post.gif" name="create"><span style="display: none;" id="Span2"><img border="0" alt="Too Many Characters in Post" src="http://img.perf.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/exchange/images/btn_x_post_blur.gif"></span><div class="breaker"></div>');
	}
});
*/


