﻿
/***********************************************
*
*File: jquery.base64Encode.js STarts
*
***********************************************/

try {
(function($){
		
		var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		
		var uTF8Encode = function(string) {
			string = string.replace(/\x0d\x0a/g, "\x0a");
			var output = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					output += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					output += String.fromCharCode((c >> 6) | 192);
					output += String.fromCharCode((c & 63) | 128);
				} else {
					output += String.fromCharCode((c >> 12) | 224);
					output += String.fromCharCode(((c >> 6) & 63) | 128);
					output += String.fromCharCode((c & 63) | 128);
				}
			}
			return output;
		};
		
		var uTF8Decode = function(input) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
			while ( i < input.length ) {
				c = input.charCodeAt(i);
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				} else if ((c > 191) && (c < 224)) {
					c2 = input.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				} else {
					c2 = input.charCodeAt(i+1);
					c3 = input.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		}
		
		$.extend({
			base64Encode: function(input) {
				var output = "";
				var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
				var i = 0;
				input = uTF8Encode(input);
				while (i < input.length) {
					chr1 = input.charCodeAt(i++);
					chr2 = input.charCodeAt(i++);
					chr3 = input.charCodeAt(i++);
					enc1 = chr1 >> 2;
					enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
					enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
					enc4 = chr3 & 63;
					if (isNaN(chr2)) {
						enc3 = enc4 = 64;
					} else if (isNaN(chr3)) {
						enc4 = 64;
					}
					output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4);
				}
				return output;
			},
			base64Decode: function(input) {
				var output = "";
				var chr1, chr2, chr3;
				var enc1, enc2, enc3, enc4;
				var i = 0;
				input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
				while (i < input.length) {
					enc1 = keyString.indexOf(input.charAt(i++));
					enc2 = keyString.indexOf(input.charAt(i++));
					enc3 = keyString.indexOf(input.charAt(i++));
					enc4 = keyString.indexOf(input.charAt(i++));
					chr1 = (enc1 << 2) | (enc2 >> 4);
					chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
					chr3 = ((enc3 & 3) << 6) | enc4;
					output = output + String.fromCharCode(chr1);
					if (enc3 != 64) {
						output = output + String.fromCharCode(chr2);
					}
					if (enc4 != 64) {
						output = output + String.fromCharCode(chr3);
					}
				}
				output = uTF8Decode(output);
				return output;
			}
		});
	})(jQuery);
	
	}catch (_err) {}
/***********************************************
*
*File: jquery.base64Encode.js Ends
*
***********************************************/

  



/***********************************************
*
*File: beliefnet.js Starts
*
***********************************************/  
try {

var userID;
var itemStatistics = {};
var userName;

function GetLogoutUrl(){
	var location = window.location.toString();
	location = QueryStringURLEncodeForThis(location);
	var itemURL = "http://www.beliefnet.com/sso.ashx?logoutredirect="+location;
	itemURL = $.base64Encode(itemURL);
	return  "http://community.beliefnet.com/tools/logout.one?origin_url="+itemURL;

}

$(document).ready(function() {
    scanInputs();



    $(".customize").click(function() {
        $(".customizeCont").animate({ height: "toggle" }, "normal");
        return false;
    });

    $(".prayerDatePicker:first").each(function() {
        $("body").append("<table id='bNetCal_box' cellpadding='0' cellspacing='0' style='display: none;position:absolute;'><tr><td id='bNetCal_src'></td></tr></table>");
    });
    $(".prayerDatePicker").click(function() {
        var baseLink = $(this).attr("href");
        var linkRel = $(this).attr("rel");
        linkRel = linkRel.split(";");
        var pastDate = linkRel[0];
        if (typeof (linkRel[1]) != "undefined")
            weekendsOnly = true;
        else
            weekendsOnly = false;


        bnetCal_show('', '', '', baseLink, linkRel[0], weekendsOnly); positionCalBox(this); return false;
    });

    /* next bit is important */

    /* checking for cookie set on community site, if its there try to grab username */
    var userName = "";
    var loggedIn = "False";
    var fileExt = "aspx";

    if (location.host.search("blog.") == 0) {
        fileExt = "php";
    }

    if (readCookie("belief") && !readCookie("core_anon")) {
        loggedIn = "True";

        beliefnetcookie = urldecode(readCookie("belief")).split("&");

        for (i = 0; i < beliefnetcookie.length; i++) {
            if (beliefnetcookie[i].match("user_name=")) {

                userName = beliefnetcookie[i].replace("user_name=", "");

                setupLoginBox(loggedIn, userName);
            }
        }
    }
    else {
        $.ajax({ type: "GET", url: "/Handlers/SsoUser." + fileExt.replace("px", "hx"), dataType: "json", cache: false,
            success: function(userobj) {
                userName = userobj.UserName;
                loggedIn = userobj.LoggedIn;

                setupLoginBox(userobj.LoggedIn, userobj.UserName);
            }
        });
    }

    /* now we check to see if our userID cookie has been set, if not we request a new userID and make the cookie */
    if (readCookie("userID")) {
        userID = readCookie("userID");
        //sendToClick(userID);
        if (typeof (userName) != "undefined") {
            $.ajax({ type: "GET", url: "/Handlers/User." + fileExt, data: "userName=" + userName, dataType: "json", cache: false,
                success: function(userobj) {
                    userID = userobj.userId;
                }
            });
        }
        updateItemStatistics(true, true);
        //$(".pollContent form").each(function() {
            //initPoll(this);
        //});
    } else {
        if (userName == "undefined" || !userName)
            userName = "";

        $.ajax({ type: "GET", url: "/Handlers/User." + fileExt, data: "userName=" + userName, dataType: "json", cache: false,
            success: function(userobj) {
                userID = userobj.userId;
                //sendToClick(userID);
                createCookie("userID", userID, 365);

            }
        });
    }
	
	var pollModId = $("#PollModuleId").attr("value");
	var OnceVoteADay = $("#VoteOnceADay").attr("value");
	if(OnceVoteADay == "True"){
		if(readCookie(pollModId)){
			//updateItemStatistics(true, true);
			$(".pollContent form").each(function() {
				initPoll(this);
			});
		}
	}

    $(".bn-keyword").mousedown(function() {
        var keywordID = $(this).attr("id");
        var keyword = $(this).text();
        var destinationUrl = $(this).attr("href");
        var locationUrl = window.location.href; ;

        //alert(keywordID + " " + keyword + " " + destinationUrl + " " + locationUrl);
        $.ajax({ type: "GET", url: "/Handlers/CLTrack.ashx", data: "KeywordID=" + keywordID + "&keyword=" + keyword + "&destinationUrl=" + destinationUrl + "&locationUrl=" + locationUrl, dataType: "json", cache: false });
    });


    $("#referFriend form:first").each(function() {
        $(this).append("<input type='hidden' name='userId' value='" + userID + "' />");
    });


    $(".recommendationsModule:first").each(function() {
        updatePreferences();
    });


    $(".tabModuleGeneric").each(function(e) {
        var selfScope = $(".tabModuleGeneric:eq(" + e + ")");
        //$(".tabModuleGeneric:eq("+e+") .moduleTabContent").hide();
        $(".tabModuleGeneric:eq(" + e + ") .moduleTabContent:eq(0)").show();
        $(".tabModuleGeneric:eq(" + e + ") .moduleTabs a").click(function() {
            $(".tabModuleGeneric:eq(" + e + ") .moduleTabs li").removeClass("active");
            $(".moduleTabContent", selfScope).hide();
            $(this).parent().addClass("active");
            var findRef = $(this).attr("rel");
            $("." + findRef + "", selfScope).show();
            return false;
        });
    });

    $('a[@rel*=lightbox]').each(function() {
        $(this).lightBox();
    });

    // striping for newsletter rows
    $(".newsletter .row:odd").addClass("oddRow");

    // striping for calendar listings
    $("#calendarEventList li").each(function(i) {
        var tempHeight = $("#calendarEventList li:eq(" + i + ") .eventDate").height();
        if ($("#calendarEventList li:eq(" + i + ") .eventDetails").height() > tempHeight)
            tempHeight = $("#calendarEventList li:eq(" + i + ") .eventDetails").height();

        $("#calendarEventList li:eq(" + i + ") div").height(tempHeight);
    });

    $("#calendarEventList li:even").addClass("oddRow");

    // striping for forms
    $(".stripeRows .row:even").addClass("oddRow");

    //last class for all last LIs in header
    $("#siteHeader ul").each(function(i) {
        $("#siteHeader ul:eq(" + i + ") li:last").addClass("lastNavItem");
    });

    //last class image text vert module
    $(".imagetextVertManual").each(function(i) {
        $(".imagetextVertManual:eq(" + i + ") li:last").addClass("lastItem");
    });

    // adding classes for event cal module
    $(".eventCalendar tr").each(function(i) {
        $(".eventCalendar tr:eq(" + i + ") td:last").addClass("lastDay");
    });
    $(".eventCalendar tr:last td").addClass("lastWeek");


    /*************************************************************************/
    //$(".printModule").each(function(e) {
    $(".moduleWrap").each(function(e) {
        $(".moduleWrap:eq(" + e + ") .shareBarPrint a").each(function(i) {
            $(this).bind("click", function() {
                printModule(e);
                return false;
            });
        });
    });
    /*************************************************************************/
    $("a.articlePrintLink").each(function() {
        var articlePrintLink = $(this).attr("href");
        $(this).bind("click", function() {
            printArticle(articlePrintLink);
            return false;
        });
    });


    //for newsletter form
    var nlrandom_now = new Date();
    var nlrandom_seed = nlrandom_now.getSeconds();
    var nlrandom_number = Math.random(nlrandom_seed);
    var nlrandom_range = nlrandom_number * 1000000000;
    var newsletterRandom = Math.round(nlrandom_range);
    var currentNewsletterImgSrc = $("img#newsletterCaptchaImage").attr("src");
    $("img#newsletterCaptchaImage").attr("src", currentNewsletterImgSrc + newsletterRandom);
    $("img#newsletterCaptchaImage").css("visibility", "visible");
    $("input#newsletterValueField").attr("value", newsletterRandom);

    // striping rows for search results
    $(".searchResult:even").addClass("searchResultOddRow");

    $("#commentFormSignup").each(function() {
        if (userName)
            $("#commentFormSignup").replaceWith("<form action='/Handlers/Comment.aspx' method='get' id='commentFormInput' class='commentFormHidden'><p>You are posting this comment to a publicly viewable discussion.</p><p>You are logged in as " + userName + ". <a href='" + GetLogoutUrl() + "'>Logout</a></p><textarea name='comment' id='comment'></textarea><div class='genericButton'><button type='submit' class=''>Submit</button></div><div class='genericButton'><button type='reset' class='clearCommentFormButton'>Cancel</button></div><div class='clear'></div></form>");
    });


    $(".externalLogin").each(function() {
        var curHref = $(this).attr("href");
        var location = window.location.toString();
        location = URLEncodeThis(location);
        var itemURL = "http://www.beliefnet.com/sso.ashx?redirectto=" + location;
        itemURL = URLEncodeThis(itemURL);
        $(this).attr("href", curHref + itemURL)
    });

    $(".clearCommentFormButton").click(function() {
        $("#commentFormInput").hide();
        return true;
    });

    $(".externalLogout").each(function() {
        var curHref = $(this).attr("href");
        var location = window.location.toString();
        location = QueryStringURLEncodeForThis(location);
        var itemURL = "http://www.beliefnet.com/sso.ashx?logoutredirect=" + location;
        itemURL = $.base64Encode(itemURL);
        $(this).attr("href", curHref + itemURL)
    });

    $(".headerTabStyle2").toggle();

    /* Sub Nav module scripts */
    //$(".subNavLevel1 li ul").hide();

    $(".subNavModule ul").each(function(n) {
        $(".subNavModule ul:eq(" + n + ")>li:last").addClass("lastNavItem");
    });
    //	$(".subNavModule ul.subNavLevel1 li").each(function(s) {
    //		if($(this).children("ul").length > 0) {
    //			$(this).addClass("hasSub");
    //		}
    //	});
    //$(".subNavLevel1>li").each(function(s) {
    //		if($(".subNavLevel1>li:eq("+s+") .activeSubNav").length < 1) {
    //			$(".subNavLevel1>li:eq("+s+")").removeClass("subNavOpened");
    //		}
    //	});
    //$(".subNavModule ul.subNavLevel1>li").each(function(s) {
    //		if($(this).children("ul").length < 1) {
    //			$(this).addClass("noSub");
    //		} else {
    //			$(".subNavModule ul.subNavLevel1>li:eq("+s+")>a.subNavTrigger").click(function() {
    //				$(".subNavModule ul.subNavLevel1>li:eq("+s+") ul").toggle();
    //				$(".subNavModule ul.subNavLevel1>li:eq("+s+")").toggleClass("subNavOpened");
    /*var itemDisplay = $(".subNavModule ul.subNavLevel1>li:eq("+s+") ul").css("display");
    var isHidden = (itemDisplay=="none") ? true:false;
    if(!isHidden) {
    $(".subNavModule ul.subNavLevel1>li:eq("+s+") ul").animate({height: "toggle"}, 100, function() {
    $(".subNavModule ul.subNavLevel1>li:eq("+s+")").toggleClass("subNavOpened");
    });
    } else {
    $(".subNavModule ul.subNavLevel1>li:eq("+s+") ul").animate({height: "toggle"}, 100);
    $(".subNavModule ul.subNavLevel1>li:eq("+s+")").toggleClass("subNavOpened");
    }*/

    //return false;
    //			});
    //		}
    //	});
    /* **************** */

    $(".commentFormHidden").hide();

    $(".commentAddLink").click(function() {
        $(".commentFormHidden").animate({ opacity: 'show' }, "show");
        return true;
    });

    $(".shareBarRatings").each(function(e) {
        prepRatingSystem(e);
    });

    $("a.resizeMinus").click(function() {
        resizeArticle('minus');
        return false;
    });

    $("a.resizePlus").click(function() {
        resizeArticle('plus');
        return false;
    });

    $(".templateHeaderPrint").click(function() {
        window.print();
        return false;
    });

    $(".shareBarPrint").bind("click", function() {
        window.print();
        return false;
    });
    $(".moduleWrap .shareBarPrint").unbind("click");
    $("#articleDetailContent .shareBarPrint").unbind("click");
    $(".shareBarEmail").each(function(e) {
        var currentHref = $(".shareBarEmail:eq(" + e + ") a").attr("href");
        $(".shareBarEmail:eq(" + e + ") a").attr("href", currentHref + "?id=" + itemId);
    });


    $(".templateHeaderEmail").each(function(e) {
        var currentHref = $(this).attr("href");
        $(this).attr("href", currentHref + "?id=" + itemId);
    });

    $(".shareBarSocial a").click(function() {
        var thisPos = findPos(this);
        toggleShareBar(thisPos);
        return false;
    });
    $("#shareBox a").click(function(i) {
        $("#shareBox").hide();
        var trackType = $(this).attr("id");
        trackType = trackType.replace("Link", "");
        _scTrackClick("share", "share:" + trackType, "event10");
    });
    $(window).bind('resize', function() {
        $("#shareBox").hide();
    });

    $("#commentFormInput").submit(function() {
        if ($("#comment").val() != "") {
            var submitURL = $(this).attr("action");
            var commentString = $("#comment").val();
            commentStringEncoded = escape(commentString);
            $.ajax({ type: "GET", url: submitURL, data: "id=" + itemId + "&userid=" + userID + "&comment=" + commentStringEncoded, dataType: "json", cache: false,
                success: function(commentResponse) {
                    if (commentResponse.processed == true)
                    //updateItemStatistics(true, false);
                        addNewComment();
                    if (document.getElementById("articleDetailContent"))
                        _scTrackClick("comment", "comment:article", "event14");
                    else
                        _scTrackClick("comment", "comment:gallery", "event14");
                }
            });
        }
        return false;
    });

    $(".commentViewAll").click(function() {
        getAllComments();
        $(this).hide();
        return false;
    });
    // event cal module filter
    $(".eventsCalendarModule").each(function(f) {
        var filterID = $(".eventsCalendarModule:eq(" + f + ") .eventModuleFilter:first").attr("id");
        var contID = $(".eventsCalendarModule:eq(" + f + ") .eventModuleItems:first").attr("id");
        var eventFilters = new Filter(filterID, "eventModuleItem", contID, 5, false);
    });


    // preload rating loader icon
    rateLoadIcon = new Image();
    rateLoadIcon.src = "/media/backgrounds/rating_loader.gif";

    // preload lightbox background
    lightboxBg = new Image();
    lightboxBg.src = "/media/backgrounds/lightbox_bg.png";

    // preload lightbox loader icon
    lightboxBg = new Image();
    lightboxBg.src = "/media/backgrounds/lightbox_loader.gif";

    // preload homepage scroller box loader icon
    homeScrollIconBg = new Image();
    homeScrollIconBg.src = "/media/backgrounds/home_tab_loader.gif";

    var newScroller = [];
    $(".imageTextCarousel").each(function(i) {
        var newScroller = new scrollObj(i);
    });
    var homeScroller;
    $("#homeTabbedScrollOuter").each(function() {
        homeScroller = new homeScroll();
    });
    //form reset
    if ($('form')) resetFields();

    //footer calc
    footerCalc();

    //newsletter click check
    if ($('#newsletterForm')) var form = new monitorChecks();



    $("#calendarEventList").each(function() {
        filterItems = $(".calFilterItem");
        maxItems = 10;
        calFilter(filterItems, maxItems);
    });

    if (!$('#siteNavMain')) sfHover("siteNavMain");

    $(".subNavLevel1").each(function(e) {
        var newID = "subNavLevel1_" + e;
        this.id = newID;
        sfHover(newID);
    });

    $("#siteNavMain>li>a").click(function() {
        var tempTitle = $(this).html();
        _scTrackNavigationMenuClick(tempTitle)
    });

    $("#siteNavMain .subnav a").click(function() {
        var tempTitle2 = $(this).html();
        var thisParent = $(this).parent("li").parent("ul").parent("li");
        var tempTitle1 = $(thisParent).children("a:first").html();
        var tempTitle = tempTitle1 + ":" + tempTitle2;
        _scTrackNavigationMenuClick(tempTitle)
    });

    $("#headerSearch button").click(function() {
        _scTrackClick("search", "search-button", "event3");
    });

    $(".vidPlayPlaylistCont ul li:even").addClass("oddRow");

    $("#homeTabbedScrollTabs li a").click(function() {
        $("#homeTabbedScrollTabs li a.activeHomeTab").removeClass("activeHomeTab");
        $(this).addClass("activeHomeTab");
        var ajaxURL = $(this).attr("href");
        //$("#homeTabScrollLeft").animate({opacity: 'hide'}, "fast").unbind("click");
        //$("#homeTabScrollRight").animate({opacity: 'hide'}, "fast").unbind("click");
        $("#homeTabScrollLeft").hide().unbind("click");
        $("#homeTabScrollRight").hide().unbind("click");
        $("#homeTabbedScrollContent").animate({ opacity: 'hide' }, "fast");
        $("#homeTabbedScrollIndicators").html("");
        $("#homeTabbedScrollHide").html("<div id='homeTabScrollerLoaderIcon'></div>");
        $.ajax({ type: "GET", url: ajaxURL, cache: false,
            success: function(newHomeScrollContent) {
                $("#homeTabbedScrollHide").html(newHomeScrollContent);
                //$("#homeTabScrollLeft").animate({opacity: 'show'}, "fast");
                //$("#homeTabScrollRight").animate({opacity: 'show'}, "fast");
                $("#homeTabScrollLeft").show();
                $("#homeTabScrollRight").show();
                $("#homeTabbedScrollContent").animate({ opacity: 'show' }, "fast");
                homeScroller = new homeScroll();
            }
        });
        return false;
    });

    $("#galleryNavPage").each(function() {
        if (!document.getElementById("galleryNavSponsor"))
            $(this).css("width", "189px");
    });

    $(".savePreferences").click(function() {
        savePreferences();
        $(".customizeCont").animate({ height: "toggle" }, "normal");
        return false;
    });
	
	var currentSection = (document.URL.replace(document.domain,"").replace("http://","").split("/")[1]).toLowerCase();

	
	/**
	This self-invoking function sets the page number.
	**/
	(
		function(){

			var PageVisit =parseInt($.cookie("PageVisit"));
			if( isNaN(PageVisit) )
			{
				$.cookie("PageVisit",1,{ path:"/"});
			}
			else
			{
				if(PageVisit<3)
				{
					$.cookie("PageVisit",++PageVisit,{ path:"/"});
				}
				else if(PageVisit==3)
				{
					$.cookie("PageVisit",99,{ path:"/"}); // No more page counting
				}
			}
		}
	)();
	/*
	if(typeof(TheFooterIsGoingToBeShown)!="undefined" && TheFooterIsGoingToBeShown)
	{
		//var footerLocation = "http://" + location.host.replace(/blog/, "www") + "/newsletter/Footer/footerinclude.js";
		//$.getScript(footerLocation);
	}
	else
	{
		var modalLocation = "http://" + location.host.replace(/blog/, "www") + "/newsletter/ModalOverlay/modalinclude.js";
		$.getScript(modalLocation);
	}
	*/
    var printvers = $.getQueryString({ id: "printvers" });

    if (printvers == "true") {
        self.focus();
        self.print();
    }

});
/*************************************************
END OF DOC READY
*************************************************/
function setupLoginBox(loggedIn,userName){
	if(loggedIn == "True"){
		$("#headerUserInfo").html(
			"<div class=\"welcomeUser\">Welcome " 
			+ userName 
			+" <img width='20' height='20' src='http://wa4.images.onesite.com/community.beliefnet.com/user/" 
			+userName 
			+ "/avatar.jpg?type=user&amp;ts=0212-0105' alt=''>"
			+ " <a id='headerUsernameLink' href='http://community.beliefnet.com/" 
			+ userName 
			+ "?pref_tab=my_site'>My Profile</a> | " 
			+ " <a id='headerUsernameLink' href='http://community.beliefnet.com/" 
			+ userName 
			+ "/admin/?pref_tab=my_hub'>My Home</a> | "
			
			+ " <a id='headerUsernameLink' href='http://community.beliefnet.com/" 
			+ userName 
			+ "/mail/'>My Inbox</a></div>"
		);
		$(".loggedInState").show();
		$(".loggedOutState").hide();
		
		$("#loggedin").css("display", "block");
		$("#notloggedin").css("display", "none");
		$("#notloggedin").html("");	
	}
	else
	{
		$("#headerUserInfo").hide();
		
		$("#loggedin").css("display", "none");
		$("#loggedin").html("");
		$("#notloggedin").css("display", "block");		
	}
}
function updatePreferences() {
	$.ajax({type: "GET", url: "/Handlers/Preferences.aspx",data:"userid="+userID,dataType:"json",cache:false,
	   success: function(updatedPreferences){
			var allPrefs = updatedPreferences.preferences.split("_");
			$(".customizeCont input:checkbox").attr("checked", "");
			for(i=0;i<=allPrefs.length;i++) {
				$("#"+allPrefs[i]+":checkbox").attr("checked", "true");
			}
		}
	});
	getNewPreferenceContent("preferenceContentWrap");
}
function savePreferences() {
	var updatedPrefs = new Array();
	$(".customizeCont:first input:checkbox").each(function(i) {
		if($(this).attr("checked") == true)
			updatedPrefs.push($(this).attr("name"));
	});
	var joinedUpdatedPrefs = updatedPrefs.join("_");
	$.ajax({type: "GET", url: "/Handlers/SavePreferences.aspx",data:"userid="+userID+"&preferences="+joinedUpdatedPrefs,dataType:"json",cache:false,
	   success: function(savedPreferences){
			if(savedPreferences.processed == true)
				updatePreferences();
		}
	});
}
function getNewPreferenceContent(custCont) {
	var preferenceContentPage = "/System/My-Recommendations/Settings.aspx";
	$("."+custCont).html("<li class='preferencesLoad'><img src='/media/backgrounds/home_tab_loader.gif' /></li>");
	$.ajax({type: "GET", url: preferenceContentPage ,data:"userid="+userID,
	   success: function(updatedPreferenceContent){
			$("."+custCont).html(updatedPreferenceContent);
			$(".imagetextVertManual").each(function(i) {
				$(".imagetextVertManual:eq("+i+") li:last").addClass("lastItem");
			});
		}
	});
}

function positionCalBox(el) {
	var thisPos = findPos(el);
	newPositionCal(thisPos);
}
function newPositionCal(coords) {
	var calBox = $("#bNetCal_box");
	calBox.css("left",coords[0] -128);
	calBox.css("top",(coords[1] - 210));		
	$("#bNetCal_box").show();
}
function printArticle(printHref) {
	
	var url = ""+window.location;
	if(printHref=="#")
	{
		if(url.indexOf("?")!=-1)
			printHref =url+"&printvers=true";
		else
			printHref =url+"?printvers=true";
	}
	var printWindow = window.open(printHref,"","width=1024,height=768,scrollbars=1");
	
}
function printModule(e) {
	var testRail = $(".moduleWrap:eq("+e+")").attr("class");
	if(/rail3Size|rail1Size/.test(testRail) == false) {
		window.print();
		return;
	}
	var bodyClassName = $("body").attr("class");
	var printContentHeader = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en-US' lang='en-US'><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><meta name='author' content='Matthew Ausonio - Digitaria' /><meta name='Copyright' content='' /><meta name='description' content='' /><meta name='keywords' content='' /><meta http-equiv='imagetoolbar' content='false' /><meta name='MSSmartTagsPreventParsing' content='true' /><title>Beliefnet</title><link rel='stylesheet' type='text/css' href='/includes/cssbin/screen_default.css' media='all' /></head><body id='printWrapper' class="+bodyClassName+"><div class='moduleWrap'>";
	var printContent = $(".moduleWrap:eq("+e+")").html();
	var printContentFooter = "</div></body></html>";
	var printWindow = window.open("","Module","width=600,height=500");
	printWindow.document.write(printContentHeader+printContent+printContentFooter);
}
function scrollObj(i) {
	this.scrollWidth = $(".imageTextCarouselHide:eq("+i+")").width();
	this.currentPane = 1;
	this.totalScrollPanes = $(".imageTextCarouselHide:eq("+i+") .carouselItem").length;
	this.paneWidth = $(".imageTextCarouselHide:eq("+i+") .carouselItem:first").width() + parseInt($(".imageTextCarouselHide:eq("+i+") .carouselItem:first").css("margin-left")) + parseInt($(".imageTextCarouselHide:eq("+i+") .carouselItem:first").css("margin-right"));
	this.totalScrollPanes = parseInt(this.totalScrollPanes) * this.paneWidth;
	
	this.paneCount = Math.ceil(this.totalScrollPanes / this.scrollWidth);
	
	this.scrollHide = $(".imageTextCarouselHide:eq("+i+")");
	this.scrollWrap = $(".imageTextCarouselHide:eq("+i+") .imageTextCarouselWrap");
	$(this.scrollWrap).width(this.totalScrollPanes+"px");
	
	this.okToScroll = true;
	this.scrollLeftButton = $(".imageTextCarousel:eq("+i+")>.scrollCarouselLeft:first");
	this.scrollRightButton = $(".imageTextCarousel:eq("+i+")>.scrollCarouselRight:first");
	var self= this;
	$(this.scrollLeftButton).click(function() {
		self.scrollCarousel(1);
		return false;
	});
	$(this.scrollRightButton).click(function() {
		self.scrollCarousel(-1);
		return false;
	});
	
	if(this.paneCount > 1)
		$(this.scrollRightButton).show();
}


scrollObj.prototype = {
	scrollCarousel: function(dir) {
		var cssDir= (dir==-1) ? 'right':'left';
		var scrollWidth = this.scrollWidth;
		var scrollSpeed = this.scrollWidth;
		var scrollWrapLeft = $(this.scrollWrap).css("left");

		if(this.okToScroll == false) {
			return;
		}
		var newScrollWrapLeft = (parseInt(scrollWrapLeft) + (dir * scrollWidth));
		if(cssDir == "left") {
			if(this.currentPane <= 1) {
				return;
			} else {
				$(this.scrollRightButton).show();
				var self = this;
				this.okToScroll = false;
				$(this.scrollWrap).animate({left: newScrollWrapLeft+"px"}, "slow", function() {
					self.okToScroll = true;
				});
				this.currentPane--;
			}
		}
		if(cssDir == "right") {
			if(this.currentPane >= this.paneCount) {
				return;
			} else {
				$(this.scrollLeftButton).show();
				this.okToScroll = false;
				var self = this;
				$(this.scrollWrap).animate({left: newScrollWrapLeft+"px"}, "slow", function() {
					self.okToScroll = true;
				});
				this.currentPane++;
			}
		}
		
		this.checkCurrentPane(this.currentPane, this.paneCount);
	},
	checkCurrentPane: function(currentPane, paneCount) {
		if(currentPane == 1) {
			$(this.scrollLeftButton).hide();
		} else if(currentPane == paneCount) {
			$(this.scrollRightButton).hide();
		}
	}
}
function prepRatingSystem(e) {
	var rateInfo = $(".shareBarRatings:eq("+e+") li a:first");
		
	$(".shareBarRatings:eq("+e+") ul").mouseover(function() {
		$(".shareBarRatings:eq("+e+") ul").addClass("ratingHover");				   
	});
	
	$(".shareBarRatings:eq("+e+") ul").mouseout(function() {
		$(".shareBarRatings:eq("+e+") ul").removeClass("ratingHover");		
		$(".ratingDescription").html("");
		$(".ratingTotalVotes").show();
	});
	
	$(".shareBarRatings:eq("+e+")>ul>li a").mouseover(function() {
		$(".ratingTotalVotes").hide();
		var thisDesc = $(this).attr("title");
		thisDesc = "&raquo; "+thisDesc;
		$(".ratingDescription").html(thisDesc);
	});
	
	$(".shareBarRatings:eq("+e+")>ul>li a").click(function() {
		rateContent(this);
		if(document.getElementById("articleDetailContent"))
			_scTrackClick("rate", "rate:article", "event14");
		else
			_scTrackClick("rate", "rate:gallery", "event14");
		return false;
	});
}
function sendToClick(userID) {
	$.ajax({type: "GET", url: "/Handlers/Click.aspx", data:"id="+itemId+"&userid="+userID,dataType:"json",cache:false});
}
function updateItemStatistics(updateComments, updateRating) {
	var itemStatisticsUrl = "/Handlers/ItemStats.aspx";
	$.ajax({type: "GET", url: itemStatisticsUrl, data:"id="+itemId+"&userid="+userID,dataType:"json",cache:false,
	   success: function(updatedItemStatistics){
			itemStatistics = updatedItemStatistics;
			if(updateComments)
				updateCommentsCount();
			if(updateRating)
				updateRatingCount();
			return true;
		}
	});
	if(document.getElementById("comments")) {
		getComments(itemId, 1, 4);
	}
}
function getAllComments() {
	getComments(itemId, 1, "");
}
function getComments(id, from, count) {
	var commentsRequestUrl = "/Handlers/Comments.aspx";
	$.ajax({type: "GET", url: commentsRequestUrl, data:"id="+id+"&from="+from+"&count="+count,dataType:"json",cache:false,
	   success: function(requestedComments){
			outputComments(requestedComments);
		}
	});
}
function outputComments(requestedCommentsObj) {
	var commentsSource = new Array;
	
	for (i = 0; i < requestedCommentsObj.comments.length; i++) {
	    commentsSource.push("<li><p class='commentID'>" + requestedCommentsObj.comments[i].id + "</p><p class='commentName'><a href='http://community.beliefnet.com/" + requestedCommentsObj.comments[i].username + "'>" + requestedCommentsObj.comments[i].username + "</a></p><p class='commentTimeStamp'>" + requestedCommentsObj.comments[i].date + "</p><p class='commentDetails'>" + requestedCommentsObj.comments[i].comment + "</p><p class='commentDetails'><a style='cursor:pointer;' onclick='showReportAbusive()' title='Report Abuse' ><img src='/imgs/icn_flag_gray.png' /></a></p></li>");
	}
	commentsSource.push("<div id=\"modalAbusiveReport\">");
	commentsSource.push("<form action=\"/Handlers/AbusiveComments.ashx\" method=\"POST\" onSubmit=\"return sendReportAbusive();\" name=\"formReportAbusive\">");
		commentsSource.push("<div class=\"mainContent\" style=\"background-color:#FFFFFF; width:500px; padding:1px 1px 1px 1px;\">");
				commentsSource.push("<div class=\"hd\" >Report as Inappropriate</div>");
				commentsSource.push("<div class=\"bd\" >");
				commentsSource.push("<input type=\"hidden\" value=\"" + document.location.href + "\"  name=\"referrer\"/>");
					commentsSource.push("<div class=\"flag_header_div\">");
						commentsSource.push("<p>You are reporting this content because it violates the <a target=\"_BLANK\" href=\"http://www.beliefnet.com/About-Us/Terms-of-Service.aspx\">Terms of Service</a>.</p>");
						commentsSource.push("<p>All reported content is logged for investigation.</p>");
					commentsSource.push("</div>");
					commentsSource.push("<div class=\"flaggingMainForm\">");
					commentsSource.push("<div class=\"flaggingFormRow\">");
							commentsSource.push("<label class=\"labelT\" for=\"reportName\">Your Name: </label>");
							commentsSource.push("<input type=\"text\" value=\"\" class=\"flag_form\" name=\"reportName\" id=\"reportName\"/>");
						commentsSource.push("</div>");
						commentsSource.push("<div class=\"flaggingFormRow\">");
							commentsSource.push("<label class=\"labelT\" for=\"reportFrom\">Your Email: </label>");
							commentsSource.push("<input type=\"text\" value=\"\" class=\"flag_form\" name=\"reportFrom\" id=\"reportFrom\"/>");
						commentsSource.push("</div>");
						commentsSource.push("<div class=\"flaggingFormRow\">");
							commentsSource.push("<label class=\"labelT\" for=\"reportAbuser\">Name of the Abuser: </label>");
							commentsSource.push("<input type=\"text\" value=\"\" class=\"flag_form\" name=\"reportAbuser\" id=\"reportAbuser\"/>");
						commentsSource.push("</div>");
						commentsSource.push("<div class=\"flaggingFormRow\">");
							commentsSource.push("<label class=\"descriptionLabel\" for=\"reportDescription\">Description: Please be as detailed as possible in your description</label>");
						commentsSource.push("</div>");
						commentsSource.push("<div class=\"flaggingFormRow\">");
							commentsSource.push("<textarea class=\"descriptionText\" rows=\"8\" cols=\"55\" name=\"reportDescription\" id=\"reportDescription\">Describe why content is inappropriate here...</textarea>");
						commentsSource.push("</div>");
						commentsSource.push("<div class=\"flaggingButtonRow\">");
							commentsSource.push("<input style=\"float:right;\" type=\"submit\" class=\"flagButtonSubmit\" value=\"Send\" />");
							commentsSource.push("<input style=\"float:left;\" type=\"reset\" class=\"flagButtonSubmit\" onclick=\"closeReportAbusive();\" value=\"Cancel\" />");
						commentsSource.push("</div>");
						commentsSource.push("<div class=\"flaggingFormRow\"><br />");
						commentsSource.push("</div>");
					commentsSource.push("</div>");
				commentsSource.push("</div>");
		commentsSource.push("</div>");
		commentsSource.push("</form>");
		commentsSource.push("</div>");
	$("#commentsContent ul").html(commentsSource.join(""));
	if(parseFloat(itemStatistics.comments) < 5)
		$(".commentViewAll").hide();
	else
	    $(".commentViewAll").show();
	    
	


}


function showReportAbusive() {
    $('#modalAbusiveReport').modal();
}


function closeReportAbusive() {
    $("#modalOverlay").click();
}

function sendReportAbusive() {
    var _regex = /^([a-zA-Z0-9_\.-])+@([a-zA-Z0-9_-])+(\.([a-zA-Z]))+/;
    
    var reWhiteSpace = /^\s+$/;

    if (reWhiteSpace.test(document.formReportAbusive.reportFrom.value) || reWhiteSpace.test(document.formReportAbusive.reportName.value) || reWhiteSpace.test(document.formReportAbusive.reportAbuser.value) || reWhiteSpace.test(document.formReportAbusive.reportDescription.value))
    {
        alert('Please fill all the fields.');
        return false;
    }

    if (document.formReportAbusive.reportFrom.value != "" && document.formReportAbusive.reportName.value != "" && document.formReportAbusive.reportAbuser.value != "" && document.formReportAbusive.reportDescription.value != "") 
    {
       if (_regex.test(document.formReportAbusive.reportFrom.value))
            return true
        else
            alert('Please enter a valid email address.');
            return false;
     }else{
         alert('Please fill all the fields.');
         return false;
     }
}



function addNewComment(userNameComment, commentContent) {
	/*if(userNameComment == "")
		userNameComment = "Unknown User";
	var dateStamp = new Date();
	var correctHour = dateStamp.getHours();
	if(correctHour > 12)
		correctHour = correctHour - 12;
	dateStamp = dateStamp.getMonth()+"/"+dateStamp.getDay()+"/"+dateStamp.getYear()+" "+correctHour+":"+dateStamp.getMinutes()+":"+dateStamp.getSeconds();
	$("#commentsContent ul").prepend("<li><p class='commentName'><a href='#'>"+userNameComment+"</a></p><p class='commentTimeStamp'>"+dateStamp+"</p><p class='commentDetails'>"+commentContent+"</p></li>");*/
	updateItemStatistics(true, false);
	$("#comment").val("");
	$(".commentFormHidden").hide();
}
function updateCommentsCount() {
	if(itemStatistics.comments != 0)
		$(".shareCommentsCount").html(itemStatistics.comments);
	else
		$(".shareCommentsCount").html("0");
	
}
function toggleShareBar(coords) {
	var shareBox = $("#shareBox");
	var shareBoxDisplay = shareBox.css("display");
	var shareBoxTop = parseFloat(shareBox.css("top")) - 24;
	var shareBoxLeft = parseFloat(shareBox.css("left")) - 24;
	
	if(shareBoxDisplay == "none") {
		shareBox.css("left",coords[0]);
		shareBox.css("top",(coords[1] + 24));
		$("#shareBox").show();
	} else {
		if(shareBoxTop != coords[1] && shareBoxTop != coords[0]) {
			shareBox.css("left",coords[0]);
			shareBox.css("top",(coords[1] + 24));
		} else
			$("#shareBox").hide();
	}
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	return [curleft,curtop];
	}
}
function openWin(url,wName,para)
{
	if(typeof(arguments[2]) == "object")
		var values = _parameters(arguments[2]);
	window.open(url,wName,values);
}
function _parameters(attributes)
{
	var values = [];
	for(attribute in attributes)
	{
		values.push(attribute + "=" + attributes[attribute].toString());
	}
	return values.join(",");
}
function resizeArticle(size) {
	var articleFontSizing = $("#articleDetailContent").attr("class");
	if(size == "plus") {
		switch(articleFontSizing) {
			case "articleDetailSmall":
			articleFontSizing = "articleDetailMedium";
			break;
			case "articleDetailMedium":
			articleFontSizing = "articleDetailLarge";
			break;
		}
	}
	if(size == "minus") {
		switch(articleFontSizing) {
			case "articleDetailMedium":
			articleFontSizing = "articleDetailSmall"
			break;
			case "articleDetailLarge":
			articleFontSizing = "articleDetailMedium"
			break;
		}
	}
	$("#articleDetailContent").attr("class", articleFontSizing);
}


// update user rating, usually fired during item statistics update
function updateRatingCount() {
	var rateResultPage = "/Handlers/Rate.aspx";
	var ratingPos = 12 * itemStatistics.rating;
	var ratingResults = new Array();
	var ratingDesc = ['Poor', 'Fair', 'Good', 'Great', 'Excellent'];
	var ratingDescCount = parseInt(itemStatistics.rating) - 1;
	ratingResults.push("<ul><li style='width:"+ratingPos+"px;' class='currentRating'>"+ratingDesc[ratingDescCount]+"</li>");
	for(i=1;i<=5;i++) {
		ratingResults.push("<li class='ratingUnit"+i+"'>");
		
		if(!itemStatistics.userVoted)
			ratingResults.push("<a title='"+ratingDesc[(i-1)]+"' href='"+rateResultPage+"?score="+i+"&id="+itemId+"&userID="+userID+"'>"+i+"</a>");
			
		ratingResults.push("</li>");
	}
	ratingResults.push("</ul><p>Rate<span class='ratingTotalVotes' style='display: inline;'>("+itemStatistics.votes+" votes)</span><span class='ratingDescription'/></p>");
	var ratingResult = ratingResults.join("");
	$(".shareBarRatings").html(ratingResult);
	$(".shareBarRatings").each(function(e) {
		if(!itemStatistics.userVoted)
			prepRatingSystem(e);
	});
}
// function to submit rating
function rateContent(el) {
	var rateResultPage = $(el).attr("href");	
	$(".shareBarRatings").html("<p><img src='/media/backgrounds/rating_loader.gif' class='loaderIcon' />Calculating...</p>");
	$.ajax({
		type: "GET",url: rateResultPage,dataType: "json",cache:false,
		success: function(rateJSON){
			if(rateJSON.processed == true) {
				updateItemStatistics(false, true);
			} else if(rateJSON.processed == false) {
				$(".shareBarRatings").html("Error. Please try again later.");
			}
		}
	});
}

// check if user has voted on poll, run on page load
function initPoll(form) {
	var pollurl = $(form).attr("action");
	var pollID = $(form).attr("id");
	var pollContainer = $(form).parent(".pollContent");
	var myForm = form;
	$.ajax({
		type: "GET",url: "/Handlers/Poll.aspx",dataType: "json",cache:false,data:"id="+pollID+"&userID="+userID,
		success: function(pollJSON){
			pollJSON.userClicked = true;
			if(pollJSON.userClicked == true) {
				pollAnswerTexts = getPollAnswerTexts(myForm, pollID);
				pollResults = buildPollResults(pollJSON, pollAnswerTexts, pollID);
				var form = $(form);
				$(pollContainer).html(pollResults);
				$(pollContainer).next(".pollResultRelated").show();
			}
		}
	});
}
// get new poll results, used after a successful vote
function getNewPollResults(form) {
	var pollurl = $(form).attr("action");
	var pollID = $(form).attr("id");
	var pollContainer = $(form).parent(".pollContent");
	var thisModuleContainer = $(pollContainer).parent(".moduleContentInner");
	var pollName = $(".modPollQuestion:first", thisModuleContainer).html();
	var myForm = form;
	$.ajax({
		type: "GET",url: "/Handlers/Poll.aspx",dataType: "json",cache:false,data:"id="+pollID+"&userID="+userID,
		success: function(pollJSON){
			if(pollJSON.userClicked == true) {
				pollAnswerTexts = getPollAnswerTexts(myForm, pollID);
				pollResults = buildPollResults(pollJSON, pollAnswerTexts, pollID);
				var form = $(form);
				$(pollContainer).animate({opacity: 'hide'}, "fast", function() {
					$(pollContainer).html(pollResults);
					$(pollContainer).animate({opacity: 'show'}, "slow", function() {
						$(pollContainer).next(".pollResultRelated").animate({height: 'show'}, "slow");
					});
					
				});
				// track poll
				pollName = pollName.replace(/^\s*|\s*$/g, "");
				_scTrackClick("poll submit", "poll:"+pollName, "event14");
			}
		},
		error: function() {
			$(form).html("<br />Error processing request.  Please try again later.");
		},
		timeout: function() {
			$(form).html("<br />Error processing request.  Please try again later.");
		}
	});
}
// function to build poll result
function buildPollResults(pollJSON, pollAnswerTexts, pollID) {
	var pollResultsSource = new Array;
	var pollAnswersCount = 0;
	
	for(i=0;i<pollJSON.poll.length;i++) {
		pollPercentage = pollJSON.poll[i].percentage - 20;
		if(pollPercentage < 10) 
			pollPercentage = 10;
		var idRef = pollJSON.poll[i].itemId;
		pollResultsSource[pollAnswerTexts[idRef]] = "<div class='pollResultRow'><div class='pollResultBar' style='width:"+pollPercentage+"%;'><div></div></div> <span>"+pollJSON.poll[i].percentage+"%</span><p>"+pollAnswerTexts[idRef]+"</p></div>";
		
		pollAnswersCount++;
	}
	var pollResultsSourceOrdered = new Array();
	// re-order to match initial state
	for(i=0;i<=pollJSON.poll.length;i++) {
		var sourceKey = pollAnswerTexts[pollID+i];
		var addSource = pollResultsSource[sourceKey];
		pollResultsSourceOrdered.push(addSource);
	}
	return pollResultsSourceOrdered.join("");
}
// this gets the answer text from each poll question to use in results source
function getPollAnswerTexts(form, pollID) {
	var labels = $("label", form);
	var labelTexts =new Object;
	var labelTextsOrder = new Array;
	for(i=0; i<labels.length;i++) {
		var answerID = $("label:eq("+i+") input", form).attr("value");
		var answerText = $("label:eq("+i+") span", form).html();
		labelTexts[answerID] = answerText;
		labelTexts[pollID+i] = answerText;
	}
	$(form).html("<div class='pollError'></div>");
	return labelTexts;
}
// function to submit poll
function getPollResults(form) {
	var pollValue;
	var pollResultPage = $(form).attr("action");
	var pollID = $(form).attr("id");
	var pollModuleId = $("#PollModuleId").attr("value");
	var voteOnceADay = $("#VoteOnceADay").attr("value");
	$(".pollContent input:radio").each( function(f) {
		if($(".pollContent input:radio:eq("+f+")").attr("checked")) {
			pollValue = $(this).attr("value");
		}
		
	});
	if(!pollValue) {
		alert("Please select a poll answer");
	} else {
		$.ajax({
			type: "GET",
			url: pollResultPage,
			data: "id=" + pollID + "&choiceId="+pollValue +"&userId="+userID,
			cache:false,
			success: function(pollResults){
				if(pollResults.processed = true)
					getNewPollResults(form);
			}
		});
		if(voteOnceADay){
			createCookie(pollModuleId,pollModuleId,1);
		}
	}
	return false;
}
/*----------------------*/
function createCookie(name,value,days)
{
	if(days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else
		var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
}
/*----------------------*/

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length,c.length);
	}
	return false;
}
// empties a text field of it's default value when a user first clicks into the text field
// when the text field loses focus, the default value is written back if no user defined value is entered
function scanInputs()
{
	var combinedFields = new Array();		// going to hold the the NodeLists for both inputs[text] and textareas

	// grab all inputs with a type of text and push the returned NodeList to the array. Repeat for textareas
	var inputs = document.getElementsByTagName("input");
	for(var i = 0; i < inputs.length; i++)
	{
		combinedFields.push(inputs[i]);
	}
	var textAreas = document.getElementsByTagName("textarea");
	for(var i = 0; i < textAreas.length; i++)
	{
		combinedFields.push(textAreas[i]);
	}

	inputValuesArray = new Array();		// holds the associative array [name] = value/innerHTML

	for(var i = 0; i < combinedFields.length; i++)
	{

		// check to see if it's a text field. The first part of the statement is so we don't throw an error when on textareas since they don't have type attr
		if(combinedFields[i].getAttribute("type") && combinedFields[i].getAttribute("type").toLowerCase() == "text" && inputs[i])
		{
			inputValuesArray[inputs[i].getAttribute("name")] = inputs[i].value;
			combinedFields[i].onfocus = function()
			{
				if(this.value == inputValuesArray[this.getAttribute("name")]) {
					this.value = "";
				}
			}
			combinedFields[i].onblur = function()
			{
				if(this.value == "") {
					if((inputValuesArray[this.getAttribute("name")] == undefined) && (this.id = "otherField")) {
						this.value = "Other*";
					} else {
						this.value = inputValuesArray[this.getAttribute("name")];	
					}
				}
			}
		}
		else if(combinedFields[i].nodeName.toLowerCase() == "textarea")
		{
			inputValuesArray[combinedFields[i].getAttribute("name")] = combinedFields[i].innerHTML;
			combinedFields[i].onfocus = function()
			{
				if(this.innerHTML == inputValuesArray[this.getAttribute("name")]) 
					this.innerHTML = "";
				
			}
			combinedFields[i].onblur = function()
			{
				if(this.innerHTML == "") {
					this.innerHTML = inputValuesArray[this.getAttribute("name")];
				}
			}
		}
	}
}
/*----------------------*/

var globalTileCount = 1;
var tileArray = new Array();
function getNextTileId(url) {
       if(tileArray.length > 0)
       {
               if(tileArray[1][0] == url)
               {
                       return tileArray[1][1];
               }
               else
               {
                       for(var i = 2; i < tileArray.length; i++)
                       {
                               if(tileArray[i][0] == url)
                               {
                                       return tileArray[i][1];
                               }
                               else
                               {
                                       tileArray[i] = new Array();
                                       tileArray[i][0] = url;
                                       tileArray[i][1] = globalTileCount++;
                                       return tileArray[i][1];
                               }
                       }
               }
       }
       else
       {
               tileArray[1] = new Array();
               tileArray[1][0] = url;
               tileArray[1][1] = globalTileCount++;
               tileArray[2] = new Array();
               return tileArray[1][1];
       }
}
/*----------------------*/
function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    
    var ret = str;
       
    ret = ret.replace(/\+/g, '%20');
    ret = decodeURIComponent(ret);
    ret = ret.toString();
 
    return ret;
}

/*----------------------*/	
function queryStr(parameter) 
{
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) 
    {
        ft = gy[i].split("=");
        if (ft[0] == parameter)
        {return ft[1];}
    }
}

/* BEGIN: Search Tracking
/*-----------------------------*/
function searchTracking() {
	var url = window.location.toString();
	var urlArray = url.split('?q=');
	var cat;
	var search = urlArray[1];
	if(urlArray[0].match('Site') || urlArray[0].match('Articles')) {
		cat = 1;
	} else if(urlArray[0].match('Images')) {
		cat = 2;
	} else if(urlArray[0].match('Videos')) {
		cat = 3;
	} else if(urlArray[0].match('Audios')) {
		cat = 4;
	} 
	var tracking = '/System/Search/Save%20Search%20Term.aspx?q='+search+'&cat='+cat;
	$.ajax({
		type: "GET",
		url: tracking,
		dataType: "script"
	});
}
function calFilter(filterItems, maxItems) {
	$("#calFilterBox select").change(function(e) {
		$(filterItems).hide();
		$(filterItems).removeClass("shown");
		var regexp = [];
		$("#calFilterBox select").each(function(s) {
			var tempValue = $("#calFilterBox select:eq("+s+") option:selected").val();
			regexp[s] = new RegExp("_"+tempValue+"_","i");
		});
		var count = 0;
		for(var i = 0; i < filterItems.length && count < maxItems; i++)
		{
			if(filterItems[i].id.match(regexp[0]) && filterItems[i].id.match(regexp[1])) {
				$(filterItems[i]).show();
				$(filterItems[i]).addClass("shown");
				count++;
			}
		}
		restripeCalRow();
	});
}
function restripeCalRow() {
	$("#calendarEventList li").removeClass("oddRow");
	$("#calendarEventList li.shown:even").addClass("oddRow");	
}
sfHover = function(elID) {
	var sfEls = document.getElementById(elID).getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp("sfhover\\b"), "");
		}
	}
}

/* BEGIN: Form Validation
/*-----------------------------*/
function echeck(str) {
	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+$/;		
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false
	 }
	
	 if (str.indexOf(" ")!=-1){
		return false
	 }
	 if(!pattern.test(str)){        
		return false;     
	}

	 return true					
}
function validateForm(form)
{
	var errorMessage = new Array();
	var requiredCheck = /\*/;
	for(var i = 0; i < form.elements.length; i++)
	{
		if(form.elements[i].name != null)
		{
			 if(form.elements[i].name.match("email") &&
			 (form.elements[i].value != 'Email Address of Recipient') &&
			  !echeck(form.elements[i].value))
			{
				form.elements[i].style.color="red";
				errorMessage.push('Please make sure you have entered a valid email address.');
			}
			else if(form.elements[i].name.match("zip") && form.elements[i].value.length > 10)
			{
				errorMessage.push('Please enter a valid zip code');
			}
			else if(form.elements[i].name.match("captcha") &&
			 (form.elements[i].value.length != 4))
			{
				form.elements[i].style.color="red";
				errorMessage.push('Please make sure you entered the correct 4 characters from the image below.');
			}
			else if(requiredCheck.test(form.elements[i].value)) {
				form.elements[i].style.color="red";
				errorMessage.push("Please enter "+form.elements[i].title.replace(" *", ""));
			}
			else if(form.elements[i].tagName.toLowerCase == "textarea" && requiredCheck.test(form.elements[i].value)) {
				form.elements[i].style.color="red";
				errorMessage.push("Please enter"+form.elements[i].title.replace(" *", ""));
			}
			else {
				form.elements[i].style.color="#999999";
			}
			if(form.elements[i].getAttribute("type") == "checkbox" && requiredCheck.test(form.elements[i].title))
			{
				if(!form.elements[i].checked)
				{
					errorMessage.push("Please "+form.elements[i].title.replace(" *", ""));
				}	
			}
		}
	}
	if(errorMessage.length > 0) {
		outputMessage = errorMessage.join("\n");
		alert(outputMessage);
		_scTrackFormError(outputMessage);
		return false;
	}
}



//********************************************************************************************************************************************
//********************************************************************************************************************************************
//********************************************************************************************************************************************
//********************************************************************************************************************************************
// homepage stuff
function homeScroll() {
	this.scrollWidth = 597;
	this.currentPane = 1;
	this.dynCount = 1;
	this.paneWidth = 199;
	this.scrollHide = $("#homeTabbedScrollHide");
	this.scrollWrap = $("#homeTabbedScrollHide #homeTabbedScrollContent");
	this.removeNodesFrom;
	this.prepForScrolling();
	this.paneCount = Math.ceil(this.totalScrollPanesWidth / this.scrollWidth);
	if(this.totalScrollPanes < (this.paneCount*3)) {
			this.addEmptyPanes((this.paneCount*3) - this.totalScrollPanes);
			this.prepForScrolling();
	}
	//this.allSource = $(this.scrollWrap).html();
	//this.allSource = this.allSource.toString();
	
	this.okToScroll = true;
	this.scrollLeftButton = $("#homeTabScrollLeft");
	this.scrollRightButton = $("#homeTabScrollRight");
	
	if(this.totalScrollPanes <=3) {
		$(this.scrollLeftButton).hide();
		$(this.scrollRightButton).hide();
		return;
	}
	
	var self= this;
	$(this.scrollLeftButton).bind("click", function() {
		self.startScrollCarousel(1);
		return false;
	});
	$(this.scrollRightButton).bind("click", function() {
		self.startScrollCarousel(-1);
		return false;
	});
//	$(this.scrollLeftButton).click(function() {
//		self.startScrollCarousel(1);
//		return false;
//	});
//	$(this.scrollRightButton).click(function() {
//		self.startScrollCarousel(-1);
//		return false;
//	});
	this.checkCurrentPane();
}

	function QueryStringURLEncodeForThis(location) {
		location = location.replace(/\?/g,"%3F");
		location = location.replace(/&/g,"%26");
		return location;
	}
	function URLEncodeThis(location) {
		location = QueryStringURLEncodeForThis(location);
		location = location.replace(/%/g,"%25");
		return location;
	}

homeScroll.prototype = {
	scrollCarousel: function(dir, isTheEnd) {
		var cssDir= (dir==-1) ? 'right':'left';
		var scrollWidth = this.scrollWidth;
		var scrollSpeed = this.scrollWidth;
		var scrollWrapLeft = $(this.scrollWrap).css("left");

		if(this.okToScroll == false) {
			return;
		}
		if(cssDir == "left") {
			var tempLeftPos = parseFloat($(this.scrollWrap).css("left"));
			if(isTheEnd) {
				//alert("left arrow");
				var startFromCount = (this.totalScrollPanes) - 3;
				this.removeNodes(startFromCount, tempLeftPos);
			}
			var newScrollWrapLeft = (parseFloat(scrollWrapLeft) + scrollWidth);
			$(this.scrollRightButton).show();
			var self = this;
			this.okToScroll = false;
			$(this.scrollWrap).animate({left: newScrollWrapLeft+"px"}, "slow", function() {
				self.okToScroll = true;
			});
			if(this.currentPane == 1) {
				this.currentPane = this.paneCount;
			} else {
				this.currentPane--;
			}
			if(this.dynCount != 1)
				this.dynCount--;
		}
		if(cssDir == "right") {
			var tempLeftPos = parseFloat($(this.scrollWrap).css("left"));
			if(isTheEnd) {
				var changeLeftTo = tempLeftPos + this.scrollWidth;
				scrollWrapLeft = changeLeftTo;
				this.removeNodes(0, changeLeftTo);
			}
			var newScrollWrapLeft = (parseFloat($(this.scrollWrap).css("left")) - scrollWidth);

			$(this.scrollLeftButton).show();
			this.okToScroll = false;
			var self = this;
			$(this.scrollWrap).animate({left: newScrollWrapLeft+"px"}, "slow", function() {
				self.okToScroll = true;
			});
			
			if(this.currentPane == this.paneCount) {
				this.currentPane = 1;
			} else {
				this.currentPane++;
			}
			if(this.dynCount != this.paneCount)
				this.dynCount++;
		}
		
		this.checkCurrentPane(this.currentPane, this.paneCount);
	},
	addEmptyPanes:function(thisMany) {
		for(i=0;i<thisMany;i++) {
			$("<li></li>").insertAfter("#homeTabbedScrollContent li:last");
		}
		this.totalScrollPanes = $("#homeTabbedScrollContent li").length;
		this.totalScrollPanesWidth = parseInt(this.totalScrollPanes) * this.paneWidth;
		this.paneCount = Math.ceil(this.totalScrollPanesWidth / this.scrollWidth);
	},
	removeNodes: function(n, newLeft) {
		for(i=n;i<(n + 3);i++) {
			$("#homeTabbedScrollContent li:eq("+n+")").remove();
		}
		if(n >= 0)
			$(this.scrollWrap).css("left", newLeft);
	},
	startScrollCarousel: function(dir) {
		if(this.okToScroll) {
			if(dir<0 && this.dynCount == this.paneCount) { // right arrow
				var tempSource = new Array();
				for(i=0;i<3;i++) {
					tempSource.push("<li>"+$("#homeTabbedScrollContent li:eq("+i+")").html()+"</li>");
				}
				$("#homeTabbedScrollContent li:last").after(tempSource.join(""));
				
				this.scrollCarousel(dir, true);
			}
			else if(dir>0 && this.dynCount == 1) { // left arrow
				var tempSource = new Array();
				var startingPoint = this.totalScrollPanes - 3;
				for(i=startingPoint;i<this.totalScrollPanes;i++) {
					tempSource.push("<li>"+$("#homeTabbedScrollContent li:eq("+i+")").html()+"</li>");
				}
				var tempLeftPos = parseFloat($(this.scrollWrap).css("left"));
				$("#homeTabbedScrollContent li:first").before(tempSource.join(""));
				this.prepForScrolling();
				$(this.scrollWrap).css("left", tempLeftPos - this.scrollWidth);
				//alert($(this.scrollWrap).css("left"));
				this.scrollCarousel(dir, true);
			}
			else {
				this.scrollCarousel(dir);
			}
			this.prepForScrolling();
		}
	},
	prepForScrolling:function() {
		this.totalScrollPanes = $("#homeTabbedScrollContent li").length;
		this.totalScrollPanesWidth = parseInt(this.totalScrollPanes) * this.paneWidth;
		
		$(this.scrollWrap).width(this.totalScrollPanesWidth+"px");
	},
	checkCurrentPane: function(currentPane, paneCount) {
		var tempIndicatorSource = new Array();
		for(i=1;i<=this.paneCount;i++) {
			if(i == this.currentPane)
				tempIndicatorSource.push("<span class='activeIndicator'></span>");
			else
				tempIndicatorSource.push("<span></span>");	
		}
		$("#homeTabbedScrollIndicators").html(tempIndicatorSource.join(""));
	}
}
  	}catch (_err2) {}
/***********************************************
*
*File: beliefnet.js Ends
*
***********************************************/  

/***********************************************
*
*File: newsletter.js Starts
*
***********************************************/  

/***********************************
*  Beliefnet Newsletter JS
*  Created on: 07/30/08
*  Rich Rudzinski
***********************************/
try {
function resetFields() {
	//var inputArray = document.getElementsByTagName('input');
	var inputArray = $("#newsletterForm input, #manageNewsletters input");
	for(j=0;j<inputArray.length;j++){
		if(inputArray[j].type == 'text') {
			inputArray[j].onfocus = function() {
				if (this.value == this.defaultValue) this.value = '';
			}
			inputArray[j].onblur = function() {
				if(this.value == '') this.value = this.defaultValue;
			}
		}
	}
	//var textareaArray = document.getElementsByTagName('textarea');
	var textareaArray = $("#newsletterForm textarea, #manageNewsletters textarea");
	for(j=0;j<textareaArray.length;j++){
		textareaArray[j].onfocus = function() {
			if (this.value == this.defaultValue) this.value = '';
		}
		textareaArray[j].onblur = function() {
			if(this.value == '') this.value = this.defaultValue;
		}
	}		
}
var checkTally = 0;
function monitorChecks() {
	var checkArr = [];
	//var inputArr = document.getElementsByTagName('input');
	var inputArr = $("#newsletterForm input, #manageNewsletters input");
	for(var i=0; i<inputArr.length; i++) {
		if(inputArr[i].type == 'checkbox' && !inputArr[i].className.match('noTally')) checkArr.push(inputArr[i]);
	}
	for(var m=0; m<checkArr.length; m++) {
		if(checkArr[m].checked) checkTally++;
		checkArr[m].onclick = function() {
			if(this.checked) {
				if(checkTally + 1 > 10) {
					this.checked = '';
					if(!this.parentNode.className.match('error')) {
						this.parentNode.className = this.parentNode.className + ' error';
						createError(this.parentNode);
					}
				} else {
					checkTally++;
				}
			} else if(checkTally != 0) {
				checkTally--;
				var errors = $('.errorDiv');
				if(errors.length > 0) removeError(errors);
			}
		}
	}
}
function createError(cont) {
	var errorDiv = document.createElement('div');
	errorDiv.className = 'errorDiv';
	var par = document.createElement('p');
	par.innerHTML = 'You can only subscribe to 10 newsletters at the same time. Please uncheck another newsletter if you want to receive this one.'
	errorDiv.appendChild(par);
	cont.appendChild(errorDiv);
}
function removeError(errors) {
	for(var n=0; n<errors.length; n++) {
		errors[n].parentNode.className = errors[n].parentNode.className.replace('error', '');
		errors[n].parentNode.removeChild(errors[n]);
	}
}
function footerCalc() {
	var total = 0;
	$('#footerColumns div').each(function(i) {
		total = total + $(this).width() + parseInt($(this).css('padding-right')) + parseInt($(this).css('padding-left'));
	});
	$('#footerColumns').width(total + 'px');
}

	}catch (_err) {}

/***********************************************
*
*File: newsletter.js Ends
*
***********************************************/  

/***********************************************
*
*File: internal.js Starts
*
***********************************************/  

//sets up js function includion for pages
//*********************************
// a "vars" attribute will be passed to the calling function as paramaters

//array to store the function names and the action event
//FunctionList["NAME-Of-FUNCTION"] = "ACTION";

try {
var FunctionList = new Array();
FunctionList["URLOnChange"] = "change";
FunctionList["avPlayer"] = "click";
FunctionList["videoPopup"] = "click";
FunctionList["openNewWin"] = "click";

//function wrapper to map the vars to paramaters, and appends the Item
function CallWrap(FunctionName, Item)
{
  var fcnCall = FunctionName+"(";
  if ($(Item).attr('vars') != undefined && $(Item).attr('vars') != "")
    fcnCall += $(Item).attr('vars')+",";
  fcnCall += "Item)";
  
  try
  {
    return eval(fcnCall);
  }
  catch (err)
  {
    if (console) console.error("JS CallWrap: "+err.message);
    return false;
  }
}

// changes the URL when a list value is changed
// NewWin - set to true to open link in a new window (optional)
// Item - the item containing the date,
function URLOnChange(NewWindow, Item)
{
  if (typeof(Item) == "undefined")
    Item = NewWindow;

  if (typeof(NewWindow) != "boolean")
    NewWindow = false;
  
  if (Item.value != undefined && Item.value != "" && Item.value.search(/(^\/)|(^http)/) == 0)
    if (NewWindow)
    {
      var WinName = "URLWindow";
      if (Item.id != "")
        WinName = Item.id;

      var newWin = window.open(Item.value,WinName);
      newWin.focus();
    }
    else
      location.href = Item.value;
}


// genericmedia player
// the following are the available paramaters
// mediaURL - url of media(REQUIRED)
// mediaCaption - optional text to show below the clip,limited to 50 characters -must use \" to show a " and \' to show a '
// audPic - the Image to use (default: http://images.beliefnet.com/imgs/v4/broadband/bbSwirl.swf')
// wid - video width - default to '320'
// hei - video width - default to '320'
// av - 'aud' for audio  or 'vid' - default is 'aud'
// mediaType - 'rm' or 'flash' - default to 'rm'
// logoURL - default is none
// sqAd - square ad tag code - default to '00/13/21/79'
// bnrAd - bottom banner ad tag code - default to '00/13/21/78'
function avPlayer(mediaURL, mediaCaption, audPic, wid, hei, av, mediaType, logoURL, sqAd, bnrAd) {
  if (!mediaCaption)
    mediaCaption = '';
  if (!audPic)
    audPic = '/imgs/v4/broadband/bbSwirl.swf';
  if (!wid)
    wid = '320';
  if (!hei)
    hei = '240';
  if (!av)
    av = 'aud';
  if (!mediaType)
    mediaType = 'rm';
  if (!logoURL)
    logoURL = 'none';
  if (!sqAd)
    sqAd = '00/13/21/79';
  if (!bnrAd)
    bnrAd = '00/13/21/78';
  if (mediaURL && mediaURL != '')
  {
    var tmpLoc = '/Tools/bnetPlayer.aspx?mediaType=' + mediaType + '&mediaURL=' + escape(mediaURL); tmpLoc = tmpLoc + '&mediaCaption=' + escape(mediaCaption) + '&av=' + av + '&audPic=' + escape(audPic);
    tmpLoc = tmpLoc + '&wid=' + wid + '&hei=' + hei + '&logoURL=' + escape(logoURL) + '&sqAd=' + sqAd + '&bnrAd=' + bnrAd; avWin = window.open(tmpLoc, 'avPlayerWin', 'height=570,width=770,resizable=yes');
  }
}

//code to embed a video in a page, still requires the brightcove javascript include in the page
// arguments
// vid - the brightcove video ids ()Required
// pid - the brightcove playerID defaults to '1460867924'
function embedVideo(vid,pid)
{
  var config = new Array();
  config["videoId"] = vid;
  config["videoRef"] = null;
  config["lineupId"] = null;
  config["playerTag"] = null;
  config["autoStart"] = false;
  config["preloadBackColor"] = "#FFFFFF";
  config["width"] = 486;
  config["height"] = 412;

  config["wmode"] = "transparent";
  config["transparentBackground"] = true; 
 
  if (typeof(pid) == "undefined")
    config["playerId"] = 1460867924;
  else
    config["playerId"] = pid;
  
  //if the brightcove coad is loaded
  if (typeof(createExperience) != "undefined")
    createExperience(config, 8);
  else //write a place holder
    document.write ("<!-- brightcove functions not found -->");
}

//a wrapper for openNewWin() that is spicific to brightcove video
// arguments
// videoID - the brightcove Video ids
// loadPage - bool saying weather a page will be loaded under the popup
function videoPopup(videoID,loadPage)
{
  AdStr = "";
  if(document.body)
  {
    adCdBase=document.body.innerHTML;
    adStrt=adCdBase.search("src=\"http://ad.doubleclick.net");
    if(adStrt>-1)
    {
      adCdBase=adCdBase.substr(adStrt+30);
      adCdBase=adCdBase.substr(0,adCdBase.search("pos"));
      if(adCdBase.charAt(0)=="/")
        AdStr="&AdCode="+adCdBase;
    }
  }
 
  openNewWin('/Tools/popupplayer.aspx?videoId='+videoID+AdStr,'popupplayer',845,455);
  
  if (loadPage)
    return true;
  else
    return false;
}

//opens a web page in a popup window
function openNewWin(page,win_name,width,height,scrollbars)
{
  var remote;
  
  //spicificly to support video popups under brightcove
  if (page.toLowerCase().indexOf("/av/popupplayer.aspx") > -1)
  {
    page = page.replace("/av/popupplayer.aspx","/Tools/popupplayer.aspx")
    page = page.replace("/video/AstrologyPopupPlayer.aspx","/Tools/AstrologyPopupPlayer.aspx")
    width=845;
    height=455;
  }
  
  if(win_name=="login_popup")
  {
	startIndex=page.indexOf("?");
	parent.document.location.href="/login.asp\?"+page.substring(startIndex+1,page.length);
  }
  else
  {
    var xMax=screen.width;xMax=xMax-(width+15);
	if(scrollbars)
    {
      remote=window.open(page,win_name,"width="+width+",height="+height+",scrollbars,dependent=yes,left="+xMax+",screenX="+xMax+",top=0,screenY=0");
    }
    else 
    {
      remote=window.open(page,win_name,"width="+width+",height="+height+",scrollbars=auto,resize=no,dependent=yes,left=" +xMax+ ",screenX=" +xMax+ ",top=0,screenY=0");
    }
	remote.focus();
  }
}

//attaches functions to html objects
if (CallWrap != undefined)
  for (var tmpFcnName in FunctionList)
    try
    {
      eval(tmpFcnName);
      eval("$('.js-"+tmpFcnName+"')."+FunctionList[tmpFcnName]+"(function(){return CallWrap('"+tmpFcnName+"',this)})");
    }
    catch (err)
  {
  if (console) console.error("JS Attach Function: "+err.message);
}

function getIstValue() 
{
	var overlayCookie = $.cookie("ModalOverlay");
	var result = "";
	
	if (overlayCookie !=  undefined  && overlayCookie != '' && overlayCookie.indexOf('viewed') >=0)
	   result = "ist";
   
   return result;
}
function checkAllOrUncheckAll()
{
    var link = document.getElementById("newsletterManageCheckAll");
	if(link.innerHTML=="Check All")
	{
		CheckAllCheckboxes(true);
        link.innerHTML="Uncheck All";
    }else
    {
        CheckAllCheckboxes(false);
	link.innerHTML="Check All";
    }
}

function CheckAllCheckboxes(value)
{
    var form = document.getElementById("manageNewsletters");
    for(i=0; i<form.elements.length; i++)
    {
        if(form.elements[i].type=="checkbox")
        {
            form.elements[i].checked=value;
        }
    }
}      
  
  	}catch (_err) {}

/***********************************************
*
*File: internal.js Ends
*
***********************************************/  



/***********************************************
*
*File: datePicker.js Ends
*
***********************************************/  
try {
var globalBaseLink;
// Get the date
var bnetCal_curdate = new Date();
bnetCal_curMonth = bnetCal_curdate.getMonth() + 1;
bnetCal_curYear = bnetCal_curdate.getFullYear();

var pastTestDate;
var weekdaysOnly;

var todaysDate = new Date();
todaysDateNum = todaysDate.getDate();
// array to hold final source
var bnetCal_source = [];

var bnetCal_monthNames = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];

var bnetCal_dayNames = [
'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'
];


function bnetCal_create(m, y) {
	// we need to clear the source before we make a new calendar
	bnetCal_source = [];
	
	// make top of calendar table
	bnetCal_source.push("<table width='100%' cellpadding='0' cellspacing='0' class='bNetCal'><tr><th><a href='#' onclick='bnetCal_prevMonth(); return false;'>&laquo;</a></th><th colspan='4'>" + bnetCal_monthNames[m - 1] +" " + y + "</th><th><a href='#' onclick='bnetCal_nextMonth(); return false;'>&raquo;</a></th><th><a href='#' id='bNetCal_close' onclick='bnetCal_Hide(); return false;'>X</a></th></tr><tr>");
	
	// add day column headers
	for (i = 0; i < 7; i ++) {
		bnetCal_source.push("<td class='calDayHeaders'>"+bnetCal_dayNames[i]+"</td>");
	}
	//get starting point for calendar cells
	bnetCal_curdate.setMonth(m - 1);
	bnetCal_curdate.setFullYear(y);
	bnetCal_curdate.setDate(1);
	
	//set correct number of days depending on month
	if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
		days = 31;
	} else if (m == 4 || m == 6 || m == 9 || m == 11) {
		days = 30;
	} else {
		days = (y % 4 == 0) ? 29 : 28;
	}
	// get first day
	var firstDay = bnetCal_curdate.getDay();

	if(m < 10)
		m = "0"+m;	
	
	// start weeks row
	bnetCal_source.push("</tr><tr>");
	// if the first day isnt sunday we make a spacer cell to fill in the week up until the first day
	if (firstDay != 0) 
		bnetCal_source.push("<td class='spacerBlock' colspan='" + firstDay + "'></td>");
	for (i = 0; i < days; i ++) {
		// check for end of week, if true start new row
		if (firstDay == 0) {
			bnetCal_source.push("</tr><tr>");
		}
		// next we make a test date to see if each outputted day is in the future or not, we also check to see if it is today
		var futureTestDate = new Date(y,(m-1),(i+1));
		
		if(!pastTestDate)
			pastTestDate = new Date(2000,0,1);
		
		/*pastTestDate = */
		
		if((i+1) < 10)
			preI = "0";
		else
			preI = "";
		
		if(y == todaysDate.getFullYear() && (m-1) == todaysDate.getMonth() && (i+1) == todaysDate.getDate()) {
			if(weekdaysOnly == true) {
				if(firstDay == 0 || firstDay == 6)
					bnetCal_source.push("<td class='todaysDate'>" + (i + 1) + "</td>");
				else
					bnetCal_source.push("<td class='todaysDate'><a href='"+globalBaseLink + y + "" + m + "" + preI + (i + 1) + "'>" + (i + 1) + "</a></td>");
		}
		else
			bnetCal_source.push("<td class='todaysDate'><a href='"+globalBaseLink + y + "" + m + "" + preI + (i + 1) + "'>" + (i + 1) + "</a></td>");
		}
		else if(futureTestDate > todaysDate || pastTestDate >= futureTestDate)
			bnetCal_source.push("<td class='futureDate'>" + (i + 1) + "</td>");
		else {
			if(weekdaysOnly == true) {
				if(firstDay == 0 || firstDay == 6)
					bnetCal_source.push("<td>" + (i + 1) + "</td>");
				else
					bnetCal_source.push("<td><a href='"+globalBaseLink + y + "" + m + "" + preI + (i + 1) + "'>" + (i + 1) + "</a></td>");
			}
			else
				bnetCal_source.push("<td><a href='"+globalBaseLink + y + "" + m + "" + preI + (i + 1) + "'>" + (i + 1) + "</a></td>");
		}
		if((i + 1) == days) {
			var colSpan = 7 - (firstDay + 1);
			if(colSpan>0)
				bnetCal_source.push("<td class='spacerBlock' colspan='"+colSpan+"'>&nbsp;</td>")
		}
		// add the day cell
		
		//increment and continue
		firstDay ++;
		firstDay %= 7;
	}
	// Do the footer
	bnetCal_source.push("</tr></table>");
	//output source and clean
	$('#bNetCal_src').html(bnetCal_source.join(""));
	bnetCal_source = [];
}

// function to show the calendar, this is the function attached to DOM element event
function bnetCal_show(requestedYear, requestedMonth, requestedDay,baseLink, pastDate, ifWeekdaysOnly) {
	weekdaysOnly = ifWeekdaysOnly
	if(pastDate) {
		pastDateVals = pastDate.split(",");
		pastTestDate = new Date(pastDateVals[0], pastDateVals[1], pastDateVals[2]);
	}
	globalBaseLink = baseLink;
	if(!requestedMonth && !requestedYear && !requestedDay) {
		// Make a new date, and set the current month and year.
		var bnetCal_date = new Date();
		bnetCal_curMonth = bnetCal_date.getMonth() + 1;
		bnetCal_curYear = bnetCal_date.getFullYear();
	} else {
		bnetCal_curMonth = requestedMonth;
		bnetCal_curYear = requestedYear;
		
	}
	// build calendar
	bnetCal_create(bnetCal_curMonth, bnetCal_curYear);
	// show calendar
	$('#bNetCal_box').show();
}

// Hide the calendar. separate function because it can be called from within the page.
function bnetCal_Hide() {
	$('#bNetCal_box').hide();
}

// Moves to the next month...
function bnetCal_nextMonth() {
	// Increase the current month.
	bnetCal_curMonth ++;
	// We have passed December, let's go to the next year.
	// Increase the current year, and set the current month to January.
	if (bnetCal_curMonth > 12) {
		bnetCal_curMonth = 1; 
		bnetCal_curYear++;
	}
	// build new calendar.
	bnetCal_create(bnetCal_curMonth, bnetCal_curYear);
}

// Moves to the previous month...
function bnetCal_prevMonth() {
	bnetCal_curMonth = bnetCal_curMonth - 1;
	// We have passed January, let's go back to the previous year.
	// Decrease the current year, and set the current month to December.
	if (bnetCal_curMonth < 1) {
		bnetCal_curMonth = 12; 
		bnetCal_curYear = bnetCal_curYear - 1;
	}
	// build new calendar.
	bnetCal_create(bnetCal_curMonth, bnetCal_curYear);
}

// Moves to the next year...
function bnetCal_nextYear() {
	// Increase the current year.
	bnetCal_curYear++;
	// build new calendar.
	bnetCal_create(bnetCal_curMonth, bnetCal_curYear);
}

// Moves to the previous year...
function bnetCal_prevYear() {
	// Decrease the current year.
	bnetCal_curYear = bnetCal_curYear - 1;
	// build new calendar.
	bnetCal_create(bnetCal_curMonth, bnetCal_curYear);
}
}catch (_err) {}
/***********************************************
*
*File: datePicker.js Ends
*
***********************************************/  


/***********************************************
*
*File: Main Carousel Starts
*
***********************************************/  
try {
//Define namespace 
if(typeof(Beliefnet) == 'undefined') { Beliefnet = {}; }

if(typeof(Beliefnet.MainCarousel) == 'undefined') 
{ 
	Beliefnet.MainCarousel = function()
	{
		var slideIndex = 0;
		var timerId = 0;
		var elementId = '';
		var monitor = true;
		var animationIsPlaying = true;
		
		//Private Methods
		function wireEvents() 
		{			
			$('#imageRotator-controls-prev').click(
				function() {
					goToSlide(slideIndex - 1, "1");					
				}
			);	
				
			$('#imageRotator-controls-next').click(
				function() {									
					goToSlide(slideIndex + 1, "1");				
				}
			);
			
			$('#imageRotator-controls-pause_play').click(
				function() {					
			    $('#imageRotator-controls #imageRotator-controls-pause_play').toggleClass("resume");
          if(animationIsPlaying) 
					{						
						animationIsPlaying = false;
						stopAnimation();
					} else
					{						
						animationIsPlaying = true;
						startAnimation();
					}
				}
			);
			
			$('#navMenu>li').each( function(i) {		
				$(this).click (function() {
					goToSlide( $('#navMenu>li').index(this), "1");	
					
					if(animationIsPlaying) {
						stopAnimation();
						startAnimation();
					}
          return false;
				});
			});					
		}
		
		function goToSlide(index, speed)
		{		
			if(index >= $('#navMenu>li').size()) { index = 0; }		
			if(index < 0) { index = $('#navMenu>li').size() - 1; }
			
			if(monitor) {			
				monitor = false;			
				
				$('#MainCarousel>li:visible').fadeOut(speed, function() {					
					
					try {
						$('#MainCarousel>li').eq(index).fadeIn(speed); 
						$('#navMenu>li.selected').removeClass("selected");
						$('#navMenu>li').eq(index).addClass("selected");
					} finally {
						monitor = true;
					}
				});			
				
				slideIndex = index;										
			}
		}
			
		function startAnimation()
		{	
			timerId = setInterval(function() { goToSlide(slideIndex + 1, 'slow')  }, 6000);
		}
			
		function stopAnimation()
		{
			clearInterval(timerId);
		}
			
		return {
			initialize : function(id)
			{
				elementId = id;
				wireEvents();
				startAnimation();				
			}
		};		
	}();	
}


if(typeof(Beliefnet.CarouselManager) == 'undefined') { 
	Beliefnet.CarouselManager = function() {
		
		return {	
			initialize : function() {
				$(".hslice").each( function(){
					var elementId = $(this).attr('id');
					if (elementId != "")				
	         		eval('Beliefnet.' + elementId + '.initialize("'+ elementId +'");');	
				});
			}				
		};

	}();
}

Beliefnet.CarouselManager.initialize();
	}catch (_err) {}
/***********************************************
*
*File: Main Carousel Ends
*
***********************************************/  





/***********************************************
*
*File: ExternalAdHandel 
***********************************************/  

// this contains the code to place an external ad outside of the brightcove video player
// to enable you need a div with the id of expandedBanner that can only contain a space
// this ads a config variable to the brightcove config list
//   config["onLoad"] - the name of the function to run when the onTemplateLoaded function is called 

var debugFlg = 0;
var debugIE = 1;
if (debugFlg == 0 && (location.search.indexOf("debug=") > -1))
  debugFlg = location.search.substr(location.search.indexOf("debug=") + 6, 1);

//prints debuging messages
function logMsg(msgTxt, blockLabel) {
  //if firebug is installed then use the console
  if ((debugFlg > 0) && (typeof (console) != "undefined")) {
    if (blockLabel)
      console.group(blockLabel);

    console.log(msgTxt);

    if (blockLabel)
      console.groupEnd();
  }
  //else create a div and use that
  else if (debugFlg && debugIE) {
    if (!document.getElementById("msgLog")) {
      debug = document.createElement("div");
      debug.id = "msgLog";
      debug.style.clear = "both";
      debug.style.color = "black";
      debug.style.backgroundColor = "white";
      document.body.appendChild(debug);
    }

    if (blockLabel == null)
      document.getElementById("msgLog").innerHTML += msgTxt + "<br />";
    else {
      msgTxt = msgTxt.replace(/</g, "&lt;");
      msgTxt = msgTxt.replace(/>/g, "&gt;");
      document.getElementById("msgLog").innerHTML += blockLabel + "<div style='font-size: 10px; margin-left: 10px;'>" + msgTxt + "</div>";
    }
  }
}

// called when template loads, we use this to store a reference to     
// the player and modules and add event listeners for external Ads
//if a placement is present for external ads then define the external ad calls
if (typeof (onTemplateLoaded) == "undefined")
{
  onTemplateLoaded = function(experienceID) {
    logMsg("Player Template Loaded");

    var player = brightcove.getExperience(experienceID);
    var adModule = player.getModule(APIModules.ADVERTISING);
    var videoPlayer = player.getModule(APIModules.VIDEO_PLAYER);
    var videoExperience = player.getModule(APIModules.EXPERIENCE);

    var VideoAction = new Array;
    var AdPrefix = "AD:";

    //logs an action with the video stream
    function videoActionLog(event) {
      var rtnInfo = "";
      
      var VideoTitle =  VideoAccountName.replace(" ","").toUpperCase() + ":" + videoPlayer.getCurrentVideo().displayName;
      var VideoPlayer = videoExperience.getExperienceID();
      var VideoLength = videoPlayer.getCurrentVideo().length/1000;
      var VideoLocation = event.position;
      
      if (event.type.indexOf("ad") == 0) {
        VideoTitle = AdPrefix + VideoTitle;
        
        VideoLength = 0;
        if (event.type != "adComplete")
        {
          var currentAd = adModule.getCurrentAdProperties();
          if (typeof(currentAd) == "object")
            VideoLength = currentAd.duration;
        }
      }

      rtnInfo += "Title: " + VideoTitle + "\n";
      rtnInfo += "Player: " + VideoPlayer + "\n";
      rtnInfo += "Length: " + VideoLength + "\n";
      rtnInfo += "Location: " + VideoLocation;

      switch (true)
      {
        case (event.type.indexOf("Start") > -1 || event.type.indexOf("Resume") > -1):
          if (!VideoAction[VideoTitle] || VideoAction[VideoTitle] == "Complete")
          {
              logMsg(rtnInfo,"Video Start");
              _scTrackMediaStart(VideoTitle,VideoLength,VideoPlayer,"videoStart")
              VideoAction[VideoTitle] = "Play";
          }
          else if (VideoAction[VideoTitle] == "Stop")
          {
            logMsg(rtnInfo,"Video Resume");
            _scTrackMediaResume(VideoTitle,VideoLocation)
            VideoAction[VideoTitle] = "Play";
          }
        break;

        case (event.type.indexOf("Stop") > -1 || event.type.indexOf("Pause") > -1):
          if (VideoAction[VideoTitle] != "Stop")
          {
            logMsg(rtnInfo,"Video Pause");
            _scTrackMediaPause(VideoTitle,VideoLocation)
            VideoAction[VideoTitle] = "Stop";
          }
        break;

        case (event.type.indexOf("Complete") > -1):
          if (VideoAction[VideoTitle] != "Complete")
          {
            logMsg(rtnInfo,"Video Complete");
            _scTrackMediaComplete(VideoTitle,"videoComplete")
            VideoAction[VideoTitle] = "Complete";
          }
        break;
      }
    }
    
    // Set a callback functions for the Video Events
    videoPlayer.addEventListener(BCVideoEvent.VIDEO_START,videoActionLog);
    videoPlayer.addEventListener(BCVideoEvent.VIDEO_STOP,videoActionLog);
    videoPlayer.addEventListener(BCVideoEvent.VIDEO_COMPLETE,videoActionLog);
    
    // Set a callback functions for the Ad Events
    adModule.addEventListener(BCAdvertisingEvent.AD_START, videoActionLog); 
    adModule.addEventListener(BCAdvertisingEvent.AD_PAUSE, videoActionLog); 
    adModule.addEventListener(BCAdvertisingEvent.AD_RESUME, videoActionLog); 
    adModule.addEventListener(BCAdvertisingEvent.AD_COMPLETE, videoActionLog); 

    //ads the external ad handelers in to the page
    if (document.getElementById("expandedBanner")) 
    {
      //call that handels an external ad
      function onExternalAd(event) {
        logMsg("External Ad Event");
      
        logMsg(event.ad, "Ad code");
      
        //code to create the ad object here, sets the ad object to false if invalid
        var AdObject = ExternalAd(event.ad);

        if (typeof(AdObject) == "object") 
        {
          logMsg("Type: " + AdObject.type + "\nVideoURL: " + AdObject.videoURL + "\nVideoClickURL: " + AdObject.videoClickURL + "\nDuration: " + AdObject.duration,"Displaying Ad");
          AdDuration = AdObject.duration;
          adModule.showAd(AdObject);
        }
        else
        {
          logMsg("Invalid Ad Code Provided");
          adModule.resumeAfterExternalAd(); 
        }
      }
      
      //resumes playback after the ad completes
      function onExternalAdComplete(event)
      {
        logMsg("External Ad Completed");
        adModule.resumeAfterExternalAd(); 
      }

      // ads in the correct type of ad
      adModule.enableAdFormats(6);
      
      logMsg("Supported Ad Formats: "+ adModule.getEnabledAdFormats().toString() );

      // Set a callback function for the externalAd event 
      adModule.addEventListener(BCAdvertisingEvent.EXTERNAL_AD, onExternalAd);
      adModule.addEventListener(BCAdvertisingEvent.AD_COMPLETE, onExternalAdComplete); 

    }
    else
      logMsg("External Ads Disabled");


  }
}
else
  logMsg("onTemplateLoaded already Defined");

/***********************************************
*
*File: ExternalAdHandel ends
***********************************************/  