/*
 FCBKcomplete 2.6
 - Jquery version required: 1.2.x, 1.3.x
 
 Changelog:
 
 - 2.00	new version of fcbkcomplete
 
 - 2.01 fixed bugs & added features
 		fixed filter bug for preadded items
 		focus on the input after selecting tag
 		the element removed pressing backspace when the element is selected
 		input tag in the control has a border in IE7
 		added iterate over each match and apply the plugin separately
 		set focus on the input after selecting tag
 
 - 2.02 fixed fist element selected bug
 		fixed defaultfilter error bug
 
 - 2.5 	removed selected="selected" attribute due ie bug
 		element search algorithm changed
 		better performance fix added
 		fixed many small bugs
 		onselect event added
 		onremove event added
 		
 - 2.6 	ie6/7 support fix added
 		added new public method addItem due request
 		added new options "firstselected" that you can set true/false to select first element on dropdown list
 		autoexpand input element added
 		removeItem bug fixed
 		and many more bug fixed
 		
 */

/* Coded by: emposha <admin@emposha.com> */
/* Copyright: Emposha.com <http://www.emposha.com/> - Distributed under MIT - Keep this message! */
/*
 * json_url         - url to fetch json object
 * cache       		- use cache
 * height           - maximum number of element shown before scroll will apear
 * newel            - show typed text like a element
 * firstselected	- automaticly select first element from dropdown
 * filter_case      - case sensitive filter
 * filter_selected  - filter selected items from list
 * complete_text    - text for complete page
 * maxshownitems	- maximum numbers that will be shown at dropdown list (less better performance)
 * onselect			- fire event on item select
 * onremove			- fire event on item remove
 */
 

jQuery(
    function ($) 
    {
	    $.fn.fcbkcomplete = function (opt)
	    {
    		return this.each(function()
			{
		        function init()
		        {
		           createFCBK();       
	               preSet();
	               addInput(0); 
		        }
	        	
		        function createFCBK()
		        {	    
		           element.hide();
		           //element.attr("multiple","multiple");
		           if (element.attr("name").indexOf("[]") == -1)
		           {
		           	   element.attr("name",element.attr("name")+"[]");
		           }
	        	   
		           holder = $(document.createElement("ul"));
	               holder.attr("class", "holder");
	               element.after(holder);
	               
	               complete = $(document.createElement("div"));
	               complete.addClass("facebook-auto");
	               complete.append('<div class="default">'+ options.complete_text +"</div>");
	               
				   if (browser_msie)
	               {
	                    complete.append('<iframe class="ie6fix" scrolling="no" frameborder="0"></iframe>');
	                    browser_msie_frame = complete.children('.ie6fix');
						//$("input:checkbox").parent().css("z-index","-1");
	               }
				   
	               feed = $(document.createElement("ul"));
	               feed.attr("id", elemid + "_feed");
	               
	               complete.prepend(feed);
	               holder.after(complete);
				   feed.css("width",complete.width());
		        }
	        	
		        function preSet()
		        {								
		            element.children("option").each( 
		                function(i,option) 
		                {						                    
							option = $(option);												
		                    if (option.hasClass("selected"))
		                    {																															
		                        addItem (option.text(), option.val(), true);
								option.attr("selected","selected");
		                    } 
							else
							{
								option.removeAttr("selected");	
							}

							cache.push({
								caption: option.text(),
								value: option.val()
							});
							search_string += "" + (cache.length - 1) + ":" + option.text() + ";";                
		                }
		            );
		        }
				
				//public method to add new item
				this.addItem = function(title, value)
				{
					addItem(title, value);
				};
	        	
		        function addItem (title, value, preadded)
		        {		        	
	                var li = document.createElement("li");
	                var txt = document.createTextNode(title);
	                var aclose = document.createElement("a");       
	                
	                $(li).attr({"class": "bit-box","rel": value});
	                $(li).prepend(txt);        
	                $(aclose).attr({"class": "closebutton","href": "#"});
	                
	                li.appendChild(aclose);
	                holder.append(li);
	                
	                $(aclose).click(
	                    function(){
	                        $(this).parent("li").fadeOut("fast", 
	                            function(){
									removeItem($(this));	                                
	                            }
	                        );
	                        return false;
	                    }
	                );
					
	                
	                if (!preadded) 
	                {						
	                    $("#"+elemid + "_annoninput").remove();
						var _item;
	                    addInput(1);                        
	                    if (element.children("option[value=" + value + "]").length)
	                    {   
							_item = element.children("option[value=" + value + "]");            
	                        _item.get(0).setAttribute("selected", "selected");
							if (!_item.hasClass("selected")) 
							{
								_item.addClass("selected");
							}
	                    }
	                    else
	                    {
	                        var _item = $(document.createElement("option"));
	                        _item.attr("value", value).get(0).setAttribute("selected", "selected");
							_item.attr("value", value).addClass("selected");
	                        _item.text(title);              
	                        element.append(_item);
	                    }
						if (options.onselect.length)
						{
							funCall(options.onselect,_item)
						}	
	                }					     
	                holder.children("li.bit-box.deleted").removeClass("deleted");
	                feed.hide();
					browser_msie?browser_msie_frame.hide():'';
	            }
	        	
				function removeItem(item)
				{					
					if (options.onremove.length)
					{
					    var _item = element.children("option[value=" + item.attr("rel") + "]");
						funCall(options.onremove,_item)
					}
					// IE6 issues W/ removeAttr
					//element.children("option[value=" + item.attr("rel") + "]").removeAttr("selected");
					//element.children("option[value=" + item.attr("rel") + "]").removeClass("selected");
					element.children("option[value=" + item.attr("rel") + "]").remove();
                    item.remove();					
					deleting = 0;					
				}
				
		        function addInput(focusme)
		        {
		            var li = $(document.createElement("li"));
	                var input = $(document.createElement("input"));
	                
	                li.attr({"class": "bit-input","id": elemid + "_annoninput"});        
	                input.attr({"type": "text","class": "maininput","size": "1"});        
	                holder.append(li.append(input));

					//single autocomplete
	                var firstVal = holder.children("li[rel]:first");
	                
	                input.focus(
	                    function()
	                    {
	                    	if(element.attr("url")){ options.json_url = element.attr("url"); }
	                        complete.fadeIn("fast");
	                    }
	                );
	                
	                input.blur(
	                    function()
	                    {
							if( typeof(input.valKeeper) != "undefined" &&  this.value == input.valKeeper) addItem(this.value, holder.relKeeper);
	                    	this.value = ""; 
	                        complete.fadeOut("fast");
	                    }
	                );
	                
	                holder.click(
	                    function()
	                    { 
	                    	//single autocomplete
	    		        	if(!element.attr("multiple") && firstVal.length ) 
	    		        	{
		    		        	firstVal.fadeOut("fast",
		    		        			function(){ 
		    								var inner = this.innerHTML; 
		    								var btnPos = inner.indexOf("<"); 
											
											holder.relKeeper = firstVal.attr("rel");
											input.valKeeper = inner.substring(0,btnPos);
		    		        				removeItem($(this));   

		    		        				input.parent("li").css({"width":"100%"});
		    		        				input.css({"width":"100%"});
		    		        				input.val(input.valKeeper);
		    		        				input.select();
		    		        			} 
		    		        	); 
	    		        	}
	    		        	
	                        input.focus();
							
				            if (feed.length && input.val().length) 
				            {
					            feed.show();
				            }
				            else 
				            {				
					            feed.hide();
								browser_msie?browser_msie_frame.hide():'';
					            complete.children(".default").show();
				            }
	                    }
	                );
	                
	                //single autocomplete
	                holder.focus( function(){  input.select(); }  );
	                
					input.keypress(
	                    function(event)
	                    {							
	                        if (event.keyCode == 13)
							{
							    return false;
							}
	                        
	                        //single autocomplete
	    		        	if(!element.attr("multiple") && firstVal.length && event.keyCode!=9 ) 
	    		        	{
		    		        	firstVal.fadeOut("fast" ); 
		    		        	removeItem($(firstVal));
	    		        	}

							//auto expand input							
							input.attr("size",input.val().length + 1);							
	                    }
	                );
					
					input.bind("keydown",
	                    function(event)
	                    {	
							//prevent to enter some bad chars when input is empty
							if(event.keyCode == 191)
							{								
								event.preventDefault();
								return false;
							}	                       					
	                    }
	                );
					
	                input.keyup(
	                    function(event)
	                    {
							var etext = xssPrevent(input.val());
														
							if (event.keyCode == 8 && etext.length == 0)
							{			
								feed.hide();
								browser_msie?browser_msie_frame.hide():'';				
								if (holder.children("li.bit-box.deleted").length == 0) 
								{
									holder.children("li.bit-box:last").addClass("deleted");
									return false;
								}
								else 
								{
									if (deleting)
								    {
								        return;
								    }
									deleting = 1;
									holder.children("li.bit-box.deleted").fadeOut("fast", function()
									{
										removeItem($(this));
										return false;
									});
								}
							}
							
	                        if (event.keyCode != 40 && event.keyCode != 38 && etext.length != 0) 
	                        {
	                            counter = 0;									                            
								
	                            if (options.json_url) 
	                            {
	                                if (options.cache && json_cache) 
	                                {
	                                    addMembers(etext);
	                                    bindEvents();
	                                }
	                                else 
	                                {
	                                	var precursor =  (options.json_url.indexOf("?")==-1)?  "?" : "&";
	                                    $.getJSON(options.json_url + precursor + "q=" + etext, null, 
	                                        function(data)
	                                        {
	                                            addMembers(etext, data);
	                                            json_cache = true;
	                                            bindEvents();
	                                        }
	                                    );
	                                }
	                            }
	                            else 
	                            {
									addMembers(etext);
	                                bindEvents();
	                            }
	                            complete.children(".default").hide();
								feed.show();
	                        }
	                    }
	                );
					if (focusme)
					{
						setTimeout(function(){
							input.focus();
							complete.children(".default").show();
						},1);
					}						    
		        }
	        	
				function addMembers(etext, data)
				{
					feed.html('');
					
					if (!options.cache) 
					{
						cache = new Array();
						search_string = "";
					}
					
					addTextItem(etext);
					
					if (data != null && data.length)
					{
						$.each(data, 
	                    	function(i, val)
	                    	{
								cache.push (
									{
										caption: val.tn,
										value: val.tguid
									}
								);
								search_string += "" + (cache.length - 1) + ":" + val.tn + ";";
							}
						);	
					}
					
					var maximum = options.maxshownitems<cache.length?options.maxshownitems:cache.length;
					var filter = "i";
					if (options.filter_case)
					{
						filter = ""; 
					}
					
					var myregexp, match;
					try {
						myregexp = eval('/(?:^|;)\\s*(\\d+)\\s*:[^;]*?' + etext + '[^;]*/g' + filter);
						match = myregexp.exec(search_string);
					} catch(ex){};
										
					var content = '';
					while (match != null && maximum > 0) 
					{
						var id = match[1];						
						var object = cache[id];	
						if (options.filter_selected && element.children("option[value=" + object.value + "]").hasClass("selected")) 
						{
							//nothing here...
						}
						else 
						{
							content += '<li rel="' + object.value + '">' + itemIllumination(object.caption, etext) + '</li>';
							counter++;
							maximum--;
						}						
						match = myregexp.exec(search_string);
					}
					feed.append(content);
					
					if (options.firstselected)
					{
					    focuson = feed.children("li:visible:first");
					    focuson.addClass("auto-focus");
					}
					
					if (counter > options.height) 
	                {
	                    feed.css({"height": (options.height * 24) + "px","overflow": "auto"});
						if (browser_msie)
	                    {
	                        browser_msie_frame.css({"height": (options.height * 24) + "px", "width": feed.width() + "px"}).show();
	                    }
	                }
	                else 
	                {
	                    feed.css("height", "auto");
						if (browser_msie)
	                    {
	                        browser_msie_frame.css({"height": feed.height() + "px", "width": feed.width() + "px"}).show();
	                    }
	                }				
				}
				
				function itemIllumination(text, etext)
				{
					if (options.filter_case) 
                    {     
						try {
							eval("var text = text.replace(/(.*)(" + etext + ")(.*)/gi,'$1<em>$2</em>$3');");
						} catch(ex){};
                    }
                    else 
                    {    
						try {
							eval("var text = text.replace(/(.*)(" + etext.toLowerCase() + ")(.*)/gi,'$1<em>$2</em>$3');");
						}catch(ex){};
                    }					
					return text;
				}
	        	
		        function bindFeedEvent() 
		        {		
			        feed.children("li").mouseover(
			            function()
			            {
				            feed.children("li").removeClass("auto-focus");
	                        $(this).addClass("auto-focus");
	                        focuson = $(this);
	                    }
	                );
	        		
			        feed.children("li").mouseout(
			            function()
			            {
	                        $(this).removeClass("auto-focus");
	                        focuson = null;
	                    }
	                );
		        }
	        	
		        function removeFeedEvent() 
		        {       	
			        feed.children("li").unbind("mouseover");	
			        feed.children("li").unbind("mouseout");
			        feed.mousemove(
			            function () 
			            {
				            bindFeedEvent();
				            feed.unbind("mousemove");
			            }
			        );	
		        }
	        	
		        function bindEvents()
		        {
		            var maininput = $("#"+elemid + "_annoninput").children(".maininput");	                 	
	       	        bindFeedEvent();      	
	                feed.children("li").unbind("mousedown");        
	                feed.children("li").mousedown( 
	                    function()
	                    {
	                        var option = $(this);
	                        addItem(option.text(),option.attr("rel"));
	                        feed.hide();
							browser_msie?browser_msie_frame.hide():'';
	                        complete.hide();
	                    }
	                );
	                
	                maininput.unbind("keydown");
	                maininput.bind("keydown",
	                    function(event)
	                    {		
							if(event.keyCode == 191)
							{								
								event.preventDefault();
								return false;
							}
												
							if (event.keyCode != 8) 
							{
								holder.children("li.bit-box.deleted").removeClass("deleted");
							}
							
	                        if (event.keyCode == 13 && checkFocusOn()) 
	                        {
	                            var option = focuson;
	                            addItem(option.text(), option.attr("rel"));
	                            complete.hide();
	                            event.preventDefault();
								focuson = null;
								return false;
	                        }
							
							if (event.keyCode == 13 && !checkFocusOn()) 
	                        {
								if (options.newel) 
								{
									var value = xssPrevent($(this).val());
									addItem(value, value);
									complete.hide();
									event.preventDefault();
									focuson = null;
								}
								return false;							
	                        }
	                        
	                        if (event.keyCode == 40) 
	                        {      
								//console.log("down");
					            removeFeedEvent();
	                            if (focuson == null || focuson.length == 0) 
	                            {
	                                focuson = feed.children("li:visible:first");
						            feed.get(0).scrollTop = 0;
	                            }
	                            else 
	                            {
	                                focuson.removeClass("auto-focus");
	                                focuson = focuson.nextAll("li:visible:first");
						            var prev = parseInt(focuson.prevAll("li:visible").length,10);
						            var next = parseInt(focuson.nextAll("li:visible").length,10);
						            if ((prev > Math.round(options.height /2) || next <= Math.round(options.height /2)) && typeof(focuson.get(0)) != "undefined") 
						            {
							            feed.get(0).scrollTop = parseInt(focuson.get(0).scrollHeight,10) * (prev - Math.round(options.height /2));
						            }
	                            }
					            feed.children("li").removeClass("auto-focus");
	                            focuson.addClass("auto-focus");
	                        }
	                        if (event.keyCode == 38) 
	                        {
					            removeFeedEvent();
	                            if (focuson == null || focuson.length == 0) 
	                            {
	                                focuson = feed.children("li:visible:last");
						            feed.get(0).scrollTop = parseInt(focuson.get(0).scrollHeight,10) * (parseInt(feed.children("li:visible").length,10) - Math.round(options.height /2));
	                            }
	                            else 
	                            {
	                                focuson.removeClass("auto-focus");
	                                focuson = focuson.prevAll("li:visible:first");
						            var prev = parseInt(focuson.prevAll("li:visible").length,10);
						            var next = parseInt(focuson.nextAll("li:visible").length,10);
						            if ((next > Math.round(options.height /2) || prev <= Math.round(options.height /2)) && typeof(focuson.get(0)) != "undefined") 
						            {
							            feed.get(0).scrollTop = parseInt(focuson.get(0).scrollHeight,10) * (prev - Math.round(options.height /2));
						            }
	                            }
					            feed.children("li").removeClass("auto-focus");
	                            focuson.addClass("auto-focus");
	                        }													
	                    }
	                );
		        }
	        	
		        function addTextItem(value)
		        {					
	                if (options.newel) 
	                {
	                    feed.children("li[fckb=1]").remove();
	                    if (value.length == 0)
	                    {
	                    	return;
	                    }
	                    var li = $(document.createElement("li"));
	                    li.attr({"rel": value,"fckb": "1"}).html(value);
	                    feed.prepend(li);
				        counter++;
	                } else 
					{
						return;
					}
	            }
	        	
				function funCall(func,item)
				{	
					var _object = "";			
					for(i=0;i < item.get(0).attributes.length;i++)
					{	
						if (item.get(0).attributes[i].nodeValue != null) 
						{
							_object += "\"_" + item.get(0).attributes[i].nodeName + "\": \"" + item.get(0).attributes[i].nodeValue + "\",";
						}
					}
					_object = "{"+ _object + " notinuse: 0}";
					try {
						eval(func + "(" + _object + ")");
					}catch(ex){};
				}
				
				function checkFocusOn()
		        {
		            if (focuson == null)
		            {
		                return false;
		            }
		            if (focuson.length == 0)
		            {
		                return false;
		            }
		            return true;
		        }
				
				function xssPrevent(string)
                {					
                    string = string.replace(/[\"\'][\s]*javascript:(.*)[\"\']/g, "\"\"");
                    string = string.replace(/script(.*)/g, "");    
                    string = string.replace(/eval\((.*)\)/g, "");
                    string = string.replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '');
                    return string;
                }
				
		        var options = $.extend({
				        json_url: null,
				        cache: false,
				        height: "10",
				        newel: false,
						firstselected: false,
				        filter_case: false,
				        filter_hide: false,
				        complete_text: "Start to type...",
						maxshownitems:  30,
						onselect: "",
						onremove: ""
			        }, opt);
	        	
		        //system variables
		        var holder     		= null;
		        var feed       		= null;
		        var complete   		= null;
		        var counter    		= 0;
		        var cache      		= new Array();
				var json_cache		= false;
				var search_string	= "";
		        var focuson    		= null;
	        	var deleting		= 0;
				var browser_msie	= "\v"=="v";
				var browser_msie_frame;
				
		        var element = $(this);
		        var elemid = element.attr("id");
		        init();

		        return this;
			});
	    };
    }
);
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();
	
	$(".advSearchAuto").fcbkcomplete({
		json_url: $(".advSearchAuto").attr("url"), 
		filter_hide: true,
		firstselected: true,
		newel: false
	});
	
	$(".customize").click(function() {
		$(".customizeCont").animate({height: "toggle"}, "normal");
		return false;
	});
		
	$(".pqSearchCal").datepicker({showOn: 'button', buttonImage: 'http://jqueryui.com/demos/datepicker/images/calendar.gif', buttonImageOnly: true, maxDate:''});
	
	$(".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 */
	if(readCookie("belief")) {
		beliefnetcookie = urldecode(readCookie("belief")).split("&");
		for(i=0; i< beliefnetcookie.length; i++) {
			if(beliefnetcookie[i].match("user_name="))
				userName = beliefnetcookie[i].replace("user_name=", "");
                $("#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();
		}
	}
	else
	{
		$("#headerUserInfo").hide();
	}
	
	/* 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.aspx",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.aspx",data:"userName="+userName,dataType:"json",cache:false,
		   success: function(userobj){
			   	userID = userobj.userId;
				//sendToClick(userID);
				createCookie("userID", userID, 365);
				
			}
		});
		updateItemStatistics(true, true);
		$(".pollContent form").each(function() {
			initPoll(this);
		});
	}
	
	$("#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;
		});
	});

    try { 
	    $('a[@rel*=lightbox]').each(function() {
    		$(this).lightBox();
    	});
	}
	catch (err) {}
	
	// 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").show();
	
	/* 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");
		_scTrackClick("share:"+trackType, shareTitle, "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:Article", shareTitle, "event14");
					else
						_scTrackClick("Comment:Gallery", shareTitle, "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");
	
	
	$(".layoutA #mainContentColExtra .moduleWrap").addClass("rail3Size");
	$(".layoutA #mainContentCol1 .moduleWrap").addClass("rail3Size");
	$(".layoutAa #mainContentCol2 .moduleWrap").addClass("rail3Size");
	$(".layoutAa #mainContentCol3 .moduleWrap").addClass("rail3Size");
	$(".layoutB #mainContentCol1 .moduleWrap").addClass("rail3Size");
	$(".layoutB #mainContentCol2 .moduleWrap").addClass("rail3Size");
	$(".layoutC #mainContentCol2 .moduleWrap").addClass("rail3Size");
	$(".layoutC #mainContentCol3 .moduleWrap").addClass("rail3Size");
	$(".layoutDa #mainContentCol3 .moduleWrap").addClass("rail3Size");
	$(".layoutDa #mainContentCol4 .moduleWrap").addClass("rail3Size");
	
	$(".layoutA #mainContentCol2 .moduleWrap").addClass("rail1Size");
	$(".layoutAa #mainContentColExtra .moduleWrap").addClass("rail1Size");
	$(".layoutB #mainContentCol3 .moduleWrap").addClass("rail1Size");
	$(".layoutC #mainContentColExtra .moduleWrap").addClass("rail1Size");
	$(".layoutD #mainContentCol1 .moduleWrap").addClass("rail1Size");
	$(".layoutDa #mainContentCol1 .moduleWrap").addClass("rail1Size");
	$(".layoutE #mainContentCol2 .moduleWrap").addClass("rail1Size");
	$(".layoutF #mainContentCol1 .moduleWrap").addClass("rail1Size");
	$(".layoutG #mainContentCol1 .moduleWrap").addClass("rail1Size");
	
	$("#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 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 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");
			});
		}
	});
}

/* next bit is for brightcove player in modules, no touchy */
var globalPosHolder;
var mediaName = "unspecified"
var mediaLength;
var mediaPlayerName;
function updateVideoDetails(el) {
	$(".vidPlayPlaylistCont ul li a").removeClass("activeVideo");
	$(el).addClass("activeVideo");
	var newTitle = $(el).html();
	var newLink = $(el).attr("href");
	var newDesc = $(el).attr("title");
	$(".videoPlayerModuleDetails").html(
		"<h3><a href='"+newLink+"'>"+newTitle+"</a></h3><p>"+newDesc+"</p>"
	);
}
var loadNewVideo = false;
function showNewVideo(titleID, el) {
	callFlash("fetchTitleById", titleID);
	loadNewVideo = true;
	updateVideoDetails(el);
	return false;
}
function fetchTitleById_Result(TitleDTO) {
	if(typeof(TitleDTO.displayName) != "undefined")
		mediaName = TitleDTO.displayName;
	mediaLength = TitleDTO.length;
	if(loadNewVideo == true)
		callFlash("loadTitleById", TitleDTO.id);
	loadNewVideo = false;
}
var globalPosHolder;
var mediaName = "unspecified"
var mediaLength;
var mediaPlayerName;

function onTemplateLoaded(message) {
	// track start or resume of ad/pre-roll
	callFlash("addEventListener", "adStart", "onAdStart");
	//track stop/pause of ad/pre-roll
	callFlash("addEventListener", "adStop", "onAdStop");
	//track completion of ad/pre-roll
	callFlash("addEventListener", "adComplete", "onAdComplete");
	//track start of video
	callFlash("addEventListener", "streamStart", "onStreamStart");
	// track resume of video
	callFlash("addEventListener", "mediaStart", "onMediaStart");
	//track stop/pause of video
	callFlash("addEventListener", "mediaStop", "onMediaStop");
	//track completion of video
	callFlash("addEventListener", "mediaComplete", "onMediaComplete");
	//updating info on title load
	callFlash("addEventListener", "titleLoad", "onTitleLoad");
	//fetch title
	callFlash("fetchTitleById", title_id);
	//callFlash("getTitleById", title_id);
}
function onTitleLoad(infoObj) {
	callFlash("getPlayerId");
}
function getPlayerId_Result(playerId) {
	mediaPlayerName = playerId;
}
function getVideoPosition_Result(time) {
	globalPosHolder = time;
} 
function onAdStart() {
	callFlash("getVideoPosition", true);
	if(typeof(globalPosHolder) != "undefined") {
		if(parseFloat(globalPosHolder.replace(":","")) > 0)
			_scTrackMediaResume("preroll-"+mediaName,globalPosHolder)
		else
			_scTrackMediaStart("preroll-"+mediaName,mediaLength,mediaPlayerName,"videoStart")
	}
}
function onAdStop() {
	callFlash("getVideoPosition", true);
	_scTrackMediaPause("preroll-"+mediaName,globalPosHolder)
}
function onAdComplete() {
	_scTrackMediaComplete("preroll-"+mediaName,"videoComplete")
}
function onStreamStart() {
	_scTrackMediaStart(mediaName,mediaLength,mediaPlayerName,"videoStart")
}
function onMediaStart() {
	callFlash("getVideoPosition", true);
	if(typeof(globalPosHolder) != "undefined") {
		if(parseFloat(globalPosHolder.replace(":","")) > 0)
			_scTrackMediaResume(mediaName,globalPosHolder)
	}
}		
function onMediaStop() {
	callFlash("getVideoPosition", true);
	_scTrackMediaPause(mediaName,globalPosHolder)
}
function onMediaComplete() {
	_scTrackMediaComplete(mediaName,"videoComplete")
}
/* ***************************************************************************** */
/* end brightcove code */

function getTitleById_Result(infoObj) {
	// If the title isn't already loaded, fetch it
	if (infoObj == undefined) {
		callFlash("fetchTitleById", title_id);
	// otherwise, play it
	} else {
		callFlash("loadTitleById", title_id);
	}
}
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");
	printWindow.print();
}
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");
			_scTrackClick("Rate", shareTitle, "event14");
		else
			//_scTrackClick("rate", "rate:gallery", "event14");
			_scTrackClick("Rate", shareTitle, "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></li>");
	}
	$("#commentsContent ul").html(commentsSource.join(""));
	if(parseFloat(itemStatistics.comments) < 5)
		$(".commentViewAll").hide();
	else
		$(".commentViewAll").show();
}
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){
			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");
				_scTrackClick("PollRespond", 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");
	$(".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);
			}
		});
	}
	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 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
	 }

	 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 valid email addresses.');
			}
			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 digit number from the picture in the bottom.');
			}
			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(""));
	}
}

/***************************
	FORM SEARCHING
***************************/

/**
* Date() extension to allow for sql formats :: JTG 20091029
*/ 
Date.prototype.sqlForm = function(d)
{
	if(d==null)
	{
		var month = this.getMonth()+1; 
		return this.getFullYear()+month.toString()+this.getDate();
	}
	else
	{
		var dparse = d.split("/");
		return dparse[2]+dparse[0]+dparse[1];
	}
};

/**
* FORM QUERY PROCESSING :: JTG 20091030
* &q=fighting &d=20070919|20080919 &t=Entertainment|Article|Advertising
* 	
* Rules: 
* - query types: q=queries t=tags d=dates 
* - input form field requires a rel tag assignment
* 
* REL TAG REGERENCE:
* tag OR auto: appends to tag params (t=) :: delim: "|" 
* query : append to query params (q=) :: delim: " " 
* date OR dateCombo : append to data params (d=) :: delim: "|" 
* 
*/ 
formSuccess = true; 
formProcess = {
	/**
	* @param object form
	* @return boolean
	*/ 
	submitted : function(form)
	{

		var fp = formProcess; 
		fp.dt = new Date(); fp.q = new Array(); fp.d = new Array(); fp.t = new Array(); 
		
		var formId = "#"+form.id;
		var fieldsTypes = new Array();
		fieldsTypes.push(formId+" input");
		fieldsTypes.push(formId+" select");
		var formFields = fieldsTypes.join(", ");
		
		var fieldsObj = $(formFields);
		
		fieldsObj.each(this.handleField);
		
		if(fp.q.length>0 )  
		{
			if( !$("input#q").length ) $(formId).append('<input type="hidden" id="q" name="q" />');
			$("input#q").val(fp.q.join(" "));
		}
		if(fp.d.length>0)  
		{
			if( !$("input#d").length ) $(formId).append('<input type="hidden" id="d" name="d" />'); 
			$("input#d").val(fp.d.join("|"));
		}
		if(fp.t.length>0)  
		{
			if( !$("input#t").length ) $(formId).append('<input type="hidden" id="t" name="t" />'); 
			$("input#t").val(fp.t.join("|"));
		} 
	
	    if(formSuccess) form.submit(); else formSuccess = true; 
		return false;
	},
	
	/**
	 *  DATE validation :  requires mm/dd/yyyy
	 */
	valid_date : function(dateObj)
	{
		if( typeof(dateObj.value)=="undefined" ) dateObj.value = dateObj.val();
		
		var valid_date_format_exp = /(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d/;
		if(dateObj.value!="" && !valid_date_format_exp.test(dateObj.value))
		{
			alert( "Please format dates as: mm/dd/yyyy " );
			dateObj.select();
			
			return false;
		}
		return true; 
	},
	
	/**
	* HANDLE FORM FIELD BASED ON REL TAG ASSIGNMENT 
	* 
	* @return void
	*/
	handleField : function()
	{
		var fp = formProcess; 
		var dt = fp.dt; 
		var rel = this.getAttribute("rel");
		var formId = "#" + this.form.id; 
		
		try
		{
			switch(rel)
			{
				case "query": if(this.value!="") fp.q.push(this.value); break;
				case "tag": if(this.value!="") fp.t.push(this.value); break;
				case "date": 
						if(this.value!="" )
						{ 
							if(fp.valid_date(this)) 
							{
								formSuccess =true; 
								fp.d.push(dt.sqlForm(this.value));  
							}
							else
							{	formSuccess = false; return; }
						}
				 break;
				case "dateCombo": 
					var mainDateId = formId +" input[rel='date']";
					var otherDateId = formId + " input:not(#"+this.id+")[rel="+rel+"]";
					var otherDateVal = $(otherDateId).val(); 
					
					if(formSuccess && fp.d.length==0 && $(mainDateId).val()=="" && this.value!="" && otherDateVal!="" )
					{
						if( fp.valid_date(this) && fp.valid_date($(otherDateId)) )
						{
							formSuccess =true; 
							fp.d.push( dt.sqlForm(this.value)); fp.d.push(dt.sqlForm(otherDateVal) );
						}
						else {formSuccess = false; }; 
					}
				break;
				case "auto":
				case "auto_tag": 
				case "auto_query": 
					var autoCompleteItems = $('#'+formId+' div.advancedSearchFormRow:has(#'+this.id+') ul.holder li:not(#'+this.id+'_annoninput)'); 
					
					autoCompleteItems.each
					( 
						function()
						{ 
							var inner = this.innerHTML; 
							var btnPos = inner.indexOf("<"); 
							
							if(rel=="auto_query")  fp.q.push(inner.substring(0,btnPos));
							else fp.t.push(inner.substring(0,btnPos)) ; 
						} 
					);
				break;
			}
		} catch (e){ }
		
	}
	
};


/**
 *  info button handling
 */
function what_info(obj)
{
    var html = "<div class='what_info' >" ;

    html += "<span>" + $(obj).attr("rel") + "</span>" ;
    html += "<img src='/Media/buttons/close.png' onclick='what_info_close()' />"; 
    
    html += "</div> ";
    html += "<div class='what_info shaddow' >&nbsp;</div>";
    
	if(!$('.what_info').length)  $(html).insertAfter(obj);
	$(obj).parent("label").css("z-index", "9999");
	return false;
}

function what_info_close() { $(".what_info").parent("label").css("z-index", "0");  $(".what_info").remove(); }