/*! exchTOC.js */
// Functions for the exchanges TOC page
// Requires: scripts.js

// Create product namespace if it doesn't exist
webmd.p.exch = webmd.p.exch || {};

// Function: getUserCounts
// Inputs:
//   ids [Array] List of exchange ids to fetch
//   callback(o) [Function] Function to call with the results
//       o [Object] Object consisting of exchangeId:numberofMembers
// Notes: If an error or timeout occurs, does nothing.
webmd.p.exch.getUserCounts = function(ids, callback) {

    var
    url = '/api/space/SpaceService.asmx/GetMemberCounts',
    timeout=15000,
    siteId = '3',
    o = {};

    if (!$.isArray(ids) || !$.isFunction(callback)) {
        return;
    }

    $.ajax({
        url:url,
        data:{siteId:siteId, spaceIds:ids},
        dataType:'xml',
		traditional:true,
        timeout:timeout,
        success:function(xml){
            $('SpaceMemberCount', xml).each(function(){
                var id = $('SpaceId', this).text();
                o[id] = $('MemberCount', this).text();
            });
            callback(o);
        }
    });
};

// Function: tocUserCounts
// Purpose:  Adds user counts to exchanges in the TOC page carousel
// Notes:    The carousel must be published with exchange ids.
webmd.p.exch.tocUserCounts = function() {

    // Get an exchange id from a div
    function getId(e) {
        var id = $(e).text();
        id = parseInt(id, 10);
        return isNaN(id) ? -1 : id;
    }

    // Get the exchange ids that we want to fetch
    var sel='div.ex_Carousel_rdr div.carMembers', divs = $(sel), ids=[];

    // If not found just return
    if (!divs[0]) { return; }

    // Get all the exchange ids and add to an array
    divs.each(function(){

        var id = getId(this);

        if (id > -1) {

            ids.push(id);

            // Save the id as part of the div so we don't have to parse it again
            $(this).data('id', id);

        }
    });
    
    // Fetch the member counts for all the ids, then add them to the page and show the divs
    webmd.p.exch.getUserCounts(ids, function(o){

        divs.each(function(){
            var div = $(this), id = div.data('id'), c = o[id];
            if (id && c) {
                div.html('<strong>' + c + '</strong> ' + (c > 1 ? 'members' : 'member')).show();
            }
        });

    });
};

//--------------------------------------------------
// Object: lookEx
// Purpose: Add tracking to the Looking for an Exchange section
//
webmd.p.exch.lookEx = function() {
	$('#ex_looking a').each(function(i) {
		$(this).click(function() {
			return sl(this, '', 'he-look-exch_' + (i+1));
		});
	});
}

//--------------------------------------------------
// Object: refreshAds
// Purpose: Refresh all ads on a page
//
webmd.p.exch.refreshAds = function(slideNumber) {
	
	// convert letters passed for slidenumber
	var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
	$.each(letters, function(i) {
		if (this == slideNumber) {
			slideNumber = i+1;
		}
	});
	
	// unique ID for ad server
	var transTileId = Math.round(99999999*Math.random());
	
	// Grab the top divs for both ads on the page
	$("#bannerAd_fmt, #leftAd_fmt, #rightAd_fmt").each( function() {
		
		// Find the ad within the div
		var ad = $(this).children("iframe[id*=Ad_Iframe]");

		// Remove everything from the div except for the ad
		$(this).children().not(ad).remove();

		// Remove children within the ad iframe
		ad.children().remove();

		// Update the src for each ad
		var strSrc = ad.attr("src");
		if (!strSrc) { return; }

		strSrc = strSrc.replace(new RegExp("transactionID=[0-9]+"), "transactionID=" + transTileId);
		strSrc = strSrc.replace(new RegExp("tile=[0-9]*"), "tile=" + transTileId);

		// slide ad targeting
		var next = slideNumber+1;
		strSrc = strSrc.replace(/frame=[0-9]*/, "frame=" + next);
		if (strSrc.indexOf('frame=') == -1) {
			strSrc += '&frame=' + next;
		}
		if(next == 1) { strSrc = strSrc.replace(/&frame=[0-9]*/, ""); }
		
		// Update the src without adding to the page history
		ad[0].contentWindow.location.replace(strSrc);
	});
};

// Search form on the TOC page
webmd.p.exch.searchForm = {

    init: function() {

        var self = this;

        self.div = $('#exsearch');
        if (!self.div[0]) { return; }

        self.form = $('form', self.div).submit(function(){ return self.validate(this); });

        self.input = $('input', self.div)
            .focus(function(){ self.labelFocus(this); })
            .blur( function(){ self.labelBlur(this); })
            .blur();
    },

    validate: function(f) {
        var i = this.input, v = i.val();
        if (v === undefined) { return; }
        if (v == i.attr('title') || !v.match(/\S/)) {
            alert('Please enter search keywords.');
            i[0].focus();
            return false;
        }
    },

    labelFocus: function(i) {
        if (i.value == i.title) {
	    i.value = "";
        }
    },

    labelBlur: function(i) {
        if (i.value == "") {
            i.value = i.title;
        }
    }

};

webmd.p.exch.tocTabs = function(opts){
    var defaults = {
        activeClass: 'active_fmt',
        contentId: '#tablocation_rdr',
        current: 0,
        navId: '#exch_tabs_toc_rdr',
        start: 0
    };
    var options = $.extend(defaults, opts || {});
    var $content = $(options.contentId).children();
    var $nav = $('a', options.navId);
    if($nav.length && $content.length){
        init();
    }
    function bindEvents(){
        $nav.bind('click', function(e){
            e.preventDefault();
            gotoTab($nav.index(this));
        })
    }
    function gotoTab(index){
        if(index != options.current){
            hide(options.current);
            show(index);
            wmdPageLink('tab_'+(index+1));
            options.current = index;
        }
    }
    function hide(index){
		$('#tablocation_rdr').slideUp(500, function() {
	        $($nav[index]).removeClass(options.activeClass);
			$($content[index]).css({display: 'none'});
		});
    }
    function init(){
        webmd.p.exch.tocBrowser();
        webmd.p.exch.tocWatchlist();
        bindEvents();
        gotoTab(options.start);
    }
    function show(index){
        var $thisNav = $($nav[index]);
        var $thisContent = $($content[index]);
        if($thisNav.data('init') == undefined){
            $(document).trigger('tocTabs:init'+index, {content: $thisContent, nav: $thisNav}).data('init', true);
        }
        $thisNav.addClass(options.activeClass);
		$('#tablocation_rdr').slideDown(500, function() {
			$($content[index]).css({display: 'block'});
			if($content[index].id=='slide3'){
				$('.alphanav').css({visibility: 'visible'});
			}else{
				$('.alphanav').css({visibility: 'hidden'});
			}
		});

    }

};

webmd.p.exch.tocBrowser = function(opts){
    var defaults = {
        ajax: {service: '/api/space/SpaceService.asmx/FindExchangesForCategories', timeout: 15000},
        alpha: {current: null, start: 0},
        alphaOmn: 'he-browse-tabs_',
        alphaOn: 'letteron',
        initialized: false,
        isWaiting: false,
        msg: {
            empty:'<div class="error">There were no exchanges found.</div>',
            error:'<div class="error">A problem occurred when browsing for exchanges.</div>',
            loading:'<div class="loading">Loading...</div>'
        },
        siteId: 3,
        tabEvent: 'tocTabs:init2'
    };
    var options = $.extend(defaults, opts || {});
    var $heading, $links, $results, $content, $data = null;
    initListener();
	
    function alphaChange(index){
        $($links[options.alpha.current]).removeClass(options.alphaOn);
        $($links[index]).addClass(options.alphaOn);
        options.alpha.current = index;
        options.isWaiting = true;
    }
    function bindAlphanav(){
        $links.bind('click', function(e){
            e.preventDefault();
            if(!options.isWaiting){
                var $this = $(this);
                var index = $links.index($this);
                if(index != options.alpha.current){
                    handleAlphaClick(index, $.trim($this.text()));
                }
            }
        });
    }
    function dataChange(letter){
        displayMsg('loading');
        $.ajax({
            data: {siteId: options.siteId, categoryName: letter},
            dataType: 'xml',
            error: function(){
                displayMsg();
                options.isWaiting = false;
            },
            success: function(data){
                $data = testXML(data);
                if($data != null){
                    writeData(letter);
                } else {
                    displayMsg();
                }
                options.isWaiting = false;
            },
            timeout: options.ajax.timeout,
            url: options.ajax.service
        });



    }
    function displayMsg(type){
        var msg;
        switch(type){
            case 'empty':
            msg = options.msg.empty;
            break;
            case 'loading':
            msg = options.msg.loading;
            break;
            default:
            msg = options.msg.error;
        }
        if(msg != undefined){
            $results.html(msg);
        }
    }
    function handleAlphaClick(index, letter){
        wmdPageLink(options.alphaOmn+letter);
        webmd.p.exch.refreshAds(letter);
        alphaChange(index);
        dataChange(letter);
    }
    function init(){
        $links = $('.alphanav a', $content);
        $heading = $('.alpharesults h3', $content);
        $results = $('.resultlist', $content);
        bindAlphanav();
        $($links[0]).trigger('click');
        options.initialized = true;
    }
    function initListener(){
        $(document).bind(options.tabEvent, function(e, data){
            if(!options.initialized){
                $content = (data.content != null && data.content != undefined) ? data.content : null;
                if($content != null){
                    init();
                }
            }
        });
    }
    function testXML(data){
        var $d = $('CategorytoSpacesMap', data);
        return ($d[0] != document) ? $d : null;
    }
    function writeData(letter){
		$heading.slideUp(500, function() {
			$heading.text(letter);
			$heading.slideDown(500, function() {webmd.p.exch.tocUpdateHeadings('#slide3');});
		});


        var cat, list, si, st, results = '', sponsored, subhead, tData, title, tSi, url, k=0;
        var length = $data.length;
        for(var i=0; i<length; i++){
            tData = $data[i];
            si = $('SpaceInfo', tData);
            cat = $('Category', tData).text();
            if(cat != undefined && si != undefined){
                subhead = '<h4>'+cat+'</h4>';
                var exch = '';
                var exchW = '';
                var sLength = si.length;
                for(var j=0; j<sLength; j++){
					k++;
                    tSi = si[j];
                    st = $('SpaceType', tSi).text();
                    title = $('Title', tSi).text();
                    url = $('Name', tSi).text();
                    if(st != undefined && title != undefined && url != undefined){
                        sponsored = (st == 'PublicSponsored') ? '<br/><span class="sponsored_label_fmt">(sponsored)</span>' : '';
                        list = '<li class="'+st+'"><a href="/'+url+'" onclick="return sl(this, \'\', \'he-lst-browse_'+k+'\');">'+title+'</a>'+sponsored+'</li>';
                        if(st == 'PublicHosted'){
                            exchW += list;
                        } else {
                            exch += list;
                        }
                    }
                }
            }
            if(exchW != '' || exch != ''){
                results += subhead+'<ul>'+exchW +exch +'</ul>';
            }
			

        }
        if(results == ''){
            displayMsg('empty');
        } else {
            $results.html(results).end()
                .find('ul li:nth-child(4n+1)').addClass('newrow');
        }


    }
	
};

webmd.p.exch.tocWatchlist = function(opts){
    var defaults = {
        initialized: false,
        msg: {
            login: 'Log in to see your Watchlist',
            noExchanges:'No Exchanges added to Watchlist',
            noDiscussions:'No discussions added to Watchlist'
        },
        tabEvent: 'tocTabs:init3',
        template: {
            row:'<tr><td class="link"><a href="{link}" onclick="wmdTrack(\'he-watchlist_{omModule}-{omLink}\');">{title}{num}</a></td><td class="time">{time}</td></tr>',
            rowEmpty:'<tr><td colspan="2" class="empty">{msg}</td></tr>',
            newReply: ' ({count} new)'
        }
    };
    var options = $.extend(defaults, opts || {});
    var $content, $results;
    initListener();

    function callback(data, textStatus){
        var result = '';
        var eCount = 0, dCount = 0, hasDisc = false, hasExch = false;
        var length = data.Entries.length;
        var exch = '<div id="watchlist-exchanges" class="watchlist_active_fmt exchanges"><table><thead><tr><th><div class="col1_head">My Exchanges</div></th><th><div class="col2_head">Last Activity</div></th></tr></thead><tbody>';
        var disc = '<div class="watchlist_active_fmt discussions"><table><thead><tr><th><div class="col1_head">My Discussions</div></th><th><div class="col2_head">Last Activity</div></th></tr></thead><tbody>';
        var end = '</tbody></table></div>';
        for (var i=0; i<length; i++){
            var entry = data.Entries[i];
            var date = (entry.ActivityDate == undefined) ? '' : convertDate(entry.ActivityDate);
            var num = '';
            switch (entry.ObjectType){
                case 'spon_space':
                if (entry.Title) {
                    entry.Title += options.sponsoredLabel;
                } // Fall through to next condition!
                case 'space':
                    if (entry.Title) {
                        eCount++;
                        hasExch = true;
                        exch += webmd.substitute(options.template.row, {link:entry.URL, num:num, omLink:eCount, omModule:1, title:entry.Title, time:date});
                    }
                break;
                case 'spon_forum':
                    if (entry.Title) {
                        entry.Title += options.sponsoredLabel;
                    } // Fall through to next condition!
                case 'forum':
                case 'discussion':
                    if (entry.Title) {
                        dCount++;
                        hasDisc = true;
                        num = entry.MiscData;
                        num = (num != null && num != undefined) ? ' ('+num+')' : '';
                        disc += webmd.substitute(options.template.row, {link:entry.URL, num:num, omLink:dCount, omModule:2, title:entry.Title, time:date});
                    }
                break;
                default:
                break;
            }
        }
        disc += hasDisc ? end : webmd.substitute(options.template.rowEmpty, {msg:options.msg.noDiscussions})+end;
        exch += hasExch ? end : webmd.substitute(options.template.rowEmpty, {msg:options.msg.noExchanges})+end;
        result = exch + disc;
        $results.html(result);
    }
    function callService(){
		var overrides = {
			data: {count: -1},
			success: function(data){
				callback(data);
			}
		};
		var call = $.extend({}, services.watchlist.get(), overrides);
		$.ajax(call);
    }
    function convertDate(d){
        var date;
        var matches = d.match(/Date\((\d+)-(\d+)\)/);
        if (matches){
            date = new Date(parseInt(matches[1], 10) - parseInt(matches[2], 10));
            date = DateDelta(date.toString());
        } else {
            date = '';
        }
        return date;
    }
    function init(){
        $results = $('.alpharesults', $content);
        $results.html('<p class="loading">Loading...</p>');

        if($results.length){
            if (isLoggedInWebMD()) {
                callService();
            } else {
                $results.html(makeLoginLink());
            }
        }
        options.initialized = true;
    }
    function initListener(){
        $(document).bind(options.tabEvent, function(e, data){
            $content = (data.content != null && data.content != undefined) ? data.content : null;
            if($content != null && !options.initialized){
                init();
            }
        });
    }
    function makeLoginLink(){
        return $('<p class="login"><a href="#">'+options.msg.login+'</a><p>').bind('click', function(e){
            e.preventDefault();
            wmdPageLink('he-lst-watchlist_login');
            webmd.p.exch.requireLogin(function(){ callService() });
        });
    }
};

webmd.p.exch.tocUpdateHeadings = function(container){
	switch(container){
		case '#slide1':
			ref_prefix = 'sc_';
			click_ref = 'he-ql-shrtcts';
			groupName='.sc_group';
			colnum = 4;
		break;
		case '#slide3':
			ref_prefix = 'topic_';
			click_ref = 'he-ql-browse-'+$('.alpharesults h3').html();
			groupName='.resultlist';
			colnum = 3;

		break;
		default:
			container = '#slide1';
			ref_prefix = 'sc_';
			click_ref = 'he-ql-shrtcts';
			groupName='.sc_group';
			colnum = 4;
	}
	var $headingList = $(container+' '+groupName+' h4');
	var $colsize = Math.ceil($headingList.length / colnum);
	if($colsize<2) $colsize=2;

	$(container+' .topicListResults').slideUp(500, function() {
		$(container+' .topicListResults').html('');
		var $curList, $biCall;
		for (var i=0;i<$headingList.length;i++){
			$colDiv = (i/$colsize);
			$curList = Math.floor($colDiv);
			if($colDiv==$curList){
				$('<ul class="list_'+$curList+'"></ul>').appendTo(container+' .topicListResults');
			}			
			
			$('<a name="'+ref_prefix+i+'" id="'+ref_prefix+i+'"></a>').insertBefore($headingList[i]);
			if(container == '#slide1'){
				$('<p class="back_top_link"><a href="'+container+'Top">Back to Top</a></p>').appendTo($($headingList[i]).parent().find('.sc_details'));
			}else{
				$('<p class="back_top_link"><a href="'+container+'Top">Back to Top</a></p>').insertAfter($($headingList[i]).next('ul'));
			}
			$(container+' .topiclist .list_'+$curList).append('<li></li>');
			$(document.createElement("a"))
				.attr({ href: '#'+ref_prefix+i, id : click_ref+'_'+(i+1) })
				.text($($headingList[i]).html().replace('amp;',''))
				.appendTo(container+' .topiclist .list_'+$curList+' li:last')
				.unbind('click').click(function(event){
					event.preventDefault();
					animateAnchor.call(this);
					return wmdPageLink($(this).attr('id'));
				})


		}
		animateAnchor=function(settings){
			var elementClick = "#"+$(this).attr("href").split("#")[1];
			var scroller = $(this).parents('.alpharesults');
			var destination = $(elementClick).offset().top-18;
			var divOffset = $(scroller).offset().top;
			$(scroller).animate({scrollTop: '+=' +(destination - divOffset)+ 'px'}, 900);
		}
		$('.back_top_link a').unbind('click').click(function(event){
			event.preventDefault();
			animateAnchor.call(this);
			return wmdPageLink('he-browse-btt');
		});
		
	});
	
	
	$(container+' .topicListResults').slideDown(500);
	
};

webmd.p.exch.fixTocBI = function(identifier, prefix){

	var $linkList = $(identifier);
	var newclick;
	for (var i=0;i<$linkList.length;i++){
		$($linkList[i]).attr({onClick : '', id : 'link'+(i+1)});
		$($linkList[i]).click(function(){
			return sl(this, '', prefix+"_"+$(this).attr('id').replace('link',''));
		});
	}
}

$(function(){
	
    /* tocTabs inits the tocBrowser, tocWatchlist */
    webmd.p.exch.tocTabs();
    webmd.p.exch.lookEx();
    webmd.p.exch.searchForm.init();
    // We need to do a timeout here to give the carousel time to initialize
    // before we fetch user counts (because carousel makes copies of the divs)
    setTimeout(webmd.p.exch.tocUserCounts, 1);
	
	//Moves Slide 1 and 2 Contents into the First Two Tabs, and shows the first Tab
	//onclick="return sl(this, '', 'grouplinks_1_1');"
	$('#ContentPane5 #communityGroup_rdr').addClass("exch_active_fmt");
	$('#ContentPane5 #communityGroup_rdr').removeAttr("id");
	$('#ContentPane6 #communityGroup_rdr').addClass("exch_experts_fmt");
	$('#ContentPane6 #communityGroup_rdr').removeAttr("id");
	$('#ContentPane7 #communityGroup_rdr').addClass("exch_boards_fmt");
	$('#ContentPane7 #communityGroup_rdr').removeAttr("id");
	
	   
	//Adds the omniture values for Carousel Directional Arrows
	$('.carPrev').attr("onClick", "return sl(this, '', 'he-nav-slider_prev')");
	$('.carNext').attr("onClick", "return sl(this, '', 'he-nav-slider_next')");
	
	
	$('#ContentPane5 .exch_active_fmt').appendTo('#slide1_content');
	$('#ContentPane6 .exch_experts_fmt').appendTo('#slide2_content');
	
	$('.basicsTeaser_rdr').addClass('jawsonly');

	var $sc_details = $('.sc_details ul');
	for (var i=0;i<$sc_details.length;i++){
			getLiList($sc_details[i]);
	}
	
	webmd.p.exch.fixTocBI(".sc_details a", "he-lst-shrtcts");	
	webmd.p.exch.fixTocBI(".communityGroup_fmt a", "he-lst-exprts");
	
	function getLiList(obj){
		var $liList = $(obj).children();
		var $colsize = Math.round($liList.length / 2);
		var $newUL = document.createElement('ul');
		obj.parentNode.insertBefore($newUL, obj);
		for (var j=0;j<=($colsize-1);j++){
			$newUL.appendChild($liList[j]);
		}
	}
	
	
	$('#slide1').show(function(){
		webmd.p.exch.tocUpdateHeadings();
	});
	
});



