
$(function(){
  // Pulic Issues Accordion
  $('.accordion dt a').click(function(){
    $('.accordion dl.selected dd').slideUp(300);
    $('.accordion dl.selected').removeClass('selected')
    $(this).parents('dl').find('dd').slideDown(300).parents('dl').addClass('selected');
  })  
  
  // Tab Widget
  $('.tab_widget_nav a').click(function(){
    tab = $(this).attr('tab');
    $('.tab_pane').removeClass('active');
    $('.'+tab).addClass("active");
    
    $('.tab_widget_nav li').removeClass("active");
    $(this).parent().addClass("active");
  })
});


$(function() {    
    $('.focus').css({'backgroundImage':'url('+$('.media_widget_nav li:first a img').attr('src')+')'})
   
    $('.media_widget_nav li a').click(function(){
      $('.focus').css({'backgroundImage':'url('+$(this).find('img').attr('src')+')'});
    })
    
   
   if($('#widget_2_carousel')){
     $('#widget_2_carousel').cycle({
         fx:     'fade',
         timeout: 10000,
         pager:  '#widget_2_carousel_nav'
     });     
   }
   
   if($('#widget_3_carousel')){
    $('#widget_3_carousel').cycle({
        fx:     'scrollHorz',
        timeout: 0,
        pager:  '#widget_3_carousel_nav'
    });
    }
	
   if($('#widget_search_top_carousel')){
    $('#widget_search_top_carousel').cycle({
        fx:     'scrollHorz',
        timeout: 0,
        pager:  '#widget_search_top_carousel_nav'
    });
    }
	
		
   if($('#widget_essays_carousel')){
    $('#widget_essays_carousel').cycle({
        fx:     'scrollHorz',
        timeout: 0,
        pager:  '#widget_essays_carousel_nav'
    });
    }
	
    /*if($('#trending_topics')){
		var speed = 1000;
		
		if(jQuery.browser.msie) {
			speed = 300;
		}
    $('#trending_topics').cycle({
        fx:     'fade',
		cleartypeNoBg: true,
        timeout: 6000,
		speed: speed 
    });
  }*/
    
});

$(function(){
  // Search Box behavior
  $("#searchbox").focus( function() {
		if($("#searchbox").attr("value") == "Search") {
			$("#searchbox").attr("value", "")
			$("#searchbox").css('color','white');
		}
	});

	$("#searchbox").blur( function() {
		if($("#searchbox").attr("value") == "") {
			$("#searchbox").attr("value", "Search");
			$("#searchbox").css('color','#9d9d9d');
		}
	});
});

$(function(){
	$('.pagination-ellipses').click(function(e) {
		e.preventDefault();
	});
	$('#feedback-wrapper > a').click(function(e) {
		e.preventDefault();
		$('#feedback').toggle();
	})
});

$(function(){
    $('.video-thumb-future')
    	.children()
    	.after('<a class="play-button" href="/"></a>');
    $('.video-thumb .play-button').click(function(evt) {
    	evt.preventDefault();
    });
});

$(function(){
    $('.audio-thumb')
    	.children()
    	.after('<a class="play-button" href="/"></a>');
    $('.audio-thumb .play-button').click(function(evt) {
    	evt.preventDefault();
    });
});

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
// feedback cookie management
$(function() {
	$('#feedback ul li:nth-child(2)').click(function(e) {
		e.preventDefault();
		$.cookie('hide_feedback',1,{expires: 10});
		$('#feedback-wrapper').remove();
	})
	$('#feedback ul li:nth-child(3)').click(function(e) {
		e.preventDefault();
		$.cookie('hide_feedback',1,{expires: 365});
		$('#feedback-wrapper').remove();
	})
	if($.cookie('hide_feedback') != null) {
		$('#feedback-wrapper').remove();
	}
});

$(function() {
	var apCurrentPage = 1;
	var apTotalPages = $('.ajax_pagination > span.number').length;
	if(apTotalPages == 0) { apTotalPages = 1; }
	var button = {
		prev : $('.ajax_pagination > span.prev'),
		next : $('.ajax_pagination > span.next')
	};
	var apButtonRefresh = function() {
		apCurrentPageWithinLimits();
		button.prev.show();
		button.next.show();
		if(apCurrentPage == 1) {
			button.prev.hide();
		}
		if(apCurrentPage == apTotalPages) {
			button.next.hide();
		}

		// make everything a link, unlink the current page
		$('.ajax_pagination > span.number').each(function() {
			var pageNumber = $(this).text();
			if(pageNumber == apCurrentPage) {
				$(this).empty().html(pageNumber);
			} else {
				$(this).empty().html('<a href="#">'+pageNumber+'</a>');
			}
		});		
	};
	var apFirstRefresh = function() {
		$('.article-group').hide();
		$('.article-group[rel='+apCurrentPage+']').show();
	};
	var apArticleRefresh = function() {
		$('#explore-wrapper').hide(0, function() {
			$('.article-group').hide();
			$('.article-group[rel='+apCurrentPage+']').show(0, function() {
				$('#explore-wrapper').show(0);
			});
		});
	};
	
	var apCurrentPageWithinLimits = function() {
		if(apCurrentPage <= 0) {
			apCurrentPage = 1;
		} else if(apCurrentPage > apTotalPages) {
			apCurrentPage = apTotalPages;
		}
	};
	
	button.prev.click(function() {
		apCurrentPage -= 1;
		apButtonRefresh();
		apArticleRefresh();
		/*$('html, body').animate({
			scrollTop: $("#explore").offset().top
		}, 1000);*/
		return false;
	});
	
	button.next.click(function() {
		apCurrentPage += 1;
		apButtonRefresh();
		apArticleRefresh();
		/*$('html, body').animate({
			scrollTop: $("#explore").offset().top
		}, 1000);*/
		return false;
	});
	
	$('.ajax_pagination > span.number').click(function() {
		if($(this).children('a').length == 0) { return false; } // if there is no link as a child then this wasn't a real click
		var thisPage = parseInt($(this).text());
		apCurrentPage = thisPage;
		apButtonRefresh();
		apArticleRefresh();
		/*$('html, body').animate({
			scrollTop: $("#explore").offset().top
		}, 1000);*/
		return false;
	});
	
	apButtonRefresh();
	apFirstRefresh();
});

$(document).ready(function(){
	
	var stat_map = '<div id="statistical_map"><h2>Global Statistical Map</h2><form id="stats_form"><input type="checkbox" id="temples"/><label>Temples</label><input type="checkbox" id="meetinghouses"/><label>Meetinghouses</label><input type="checkbox" id="familyhistorycenters"/><label>Family History</label><input type="checkbox" id="historicplaces"/><label>Historical Places</label><input type="checkbox" id="familyservicecenters"/><label>LDS Family Services</label><input type="checkbox" id="institutes"/><label>Institutes of Religion</label><input type="checkbox" id="deseretindustries"/><label>Deseret Industries</label></form><iframe src="http://lds.org/maps/client.jsf?expand=0&marker=0&legend=0&email=0&print=0&zoomscale=0&client=newsroom#expand=1" width="960" height="645" frameborder="0" id="map_frame"><p>No Frame</p></iframe></div>';
	
	var ie_map = '<div id="statistical_map"><h2 style="border-top: 1px solid #bbb; border-bottom: 1px solid #bbb; color: #999; text-align: center; padding: 20px 0; font-size: 18px; width: 98%;">Facts and stats map is not available for Internet Explorer</h2></div>';
	
	if($(".worldmap").length){
		if(jQuery.browser.msie) {
			$(ie_map).insertBefore($(".front_page_head_outer"));
		}else{
			$(stat_map).insertBefore($(".front_page_head_outer"));
		}
	}
	

	$("#map_frame").delay(800).attr("src","http://new.lds.org/maps/client.jsf?expand=0&marker=0&legend=0&email=0&print=0&zoomscale=0&client=newsroom#expand=1");

	$(".print-this").click(function(event){
		window.print();
		event.preventDefault();
	});
	
	$("#to-mobile").click(function (e) {
    var href = window.location.href;
    window.location.href =
      (href.indexOf("#") === -1 ? href : href.substring(0, href.indexOf("#")))
      + "?force_view=phone";
    e.preventDefault();
  });


//LANGUAGE DROP CLICK
	$("#language-select").click(function(event){
		if($("#language-select.lang-dropped").length){
			$("#language-select-list").hide();
			$("#language-select").removeClass("lang-dropped");
		}else{
			$("#language-select-list").show();
			$("#language-select").addClass("lang-dropped");
		}
		event.stopPropagation();
	});
	
	//Country Selection size adjustments
	var country_cols = $("#header #language-select-list ul").length;
	var country_cols_width = country_cols * 239;
	$("#header #language-select-list").css("width",country_cols_width+"px");
	
	
	
	
	$(window).load(function(){
		$(".image_wrap").css("visibility","visible");
	});
	
$('#newsroom-updates-input .input-field').focus(function(){
    if($(this).attr('title')==$(this).val())
        $(this).val('');    
}).blur(function() {
    if($(this).val() == '') {
        $(this).val($(this).attr('title'));
    }
});

	$("#search_form").submit(function(event){
		if($("#searchbox").val() == "" || $("#searchbox").val() == "search" || $("#searchbox").val() == "Search"){
			event.preventDefault();
		}
	});

	//SEARCH AS YOU TYPE DROPDOWN
	
	// the line below is the packed code for the jQuery Ajax Manager plugin (http://www.protofunc.com/scripts/jquery/ajaxManager/)
	(function($){var managed={},cache={};$.manageAjax=(function(){function create(name,opts){managed[name]=new $.manageAjax._manager(name,opts);return managed[name]}function destroy(name){if(managed[name]){managed[name].clear(true);delete managed[name]}}var publicFns={create:create,destroy:destroy};return publicFns})();$.manageAjax._manager=function(name,opts){this.requests={};this.inProgress=0;this.name=name;this.qName=name;this.opts=$.extend({},$.ajaxSettings,$.manageAjax.defaults,opts);if(opts&&opts.queue&&opts.queue!==true&&typeof opts.queue==='string'&&opts.queue!=='clear'){this.qName=opts.queue}};$.manageAjax._manager.prototype={add:function(o){o=$.extend({},this.opts,o);var origCom=o.complete||$.noop,origSuc=o.success||$.noop,beforeSend=o.beforeSend||$.noop,origError=o.error||$.noop,strData=(typeof o.data=='string')?o.data:$.param(o.data||{}),xhrID=o.type+o.url+strData,that=this,ajaxFn=this._createAjax(xhrID,o,origSuc,origCom);if(this.requests[xhrID]&&o.preventDoubbleRequests){return}ajaxFn.xhrID=xhrID;o.xhrID=xhrID;o.beforeSend=function(xhr,opts){var ret=beforeSend.call(this,xhr,opts);if(ret===false){that._removeXHR(xhrID)}xhr=null;return ret};o.complete=function(xhr,status){that._complete.call(that,this,origCom,xhr,status,xhrID,o);xhr=null};o.success=function(data,status,xhr){that._success.call(that,this,origSuc,data,status,xhr,o);xhr=null};o.error=function(ahr,status,errorStr){var httpStatus='',content='';if(status!=='timeout'&&ahr){httpStatus=ahr.status;content=ahr.responseXML||ahr.responseText}if(origError){origError.call(this,ahr,status,errorStr,o)}else{setTimeout(function(){throw status+'| status: '+httpStatus+' | URL: '+o.url+' | data: '+strData+' | thrown: '+errorStr+' | response: '+content;},0)}ahr=null};if(o.queue==='clear'){$(document).clearQueue(this.qName)}if(o.queue){$.queue(document,this.qName,ajaxFn);if(this.inProgress<o.maxRequests){$.dequeue(document,this.qName)}return xhrID}return ajaxFn()},_createAjax:function(id,o,origSuc,origCom){var that=this;return function(){if(o.beforeCreate.call(o.context||that,id,o)===false){return}that.inProgress++;if(that.inProgress===1){$.event.trigger(that.name+'AjaxStart')}if(o.cacheResponse&&cache[id]){that.requests[id]={};setTimeout(function(){that._complete.call(that,o.context||o,origCom,cache[id],'success',id,o);that._success.call(that,o.context||o,origSuc,cache[id]._successData,'success',cache[id],o)},0)}else{if(o.async){that.requests[id]=$.ajax(o)}else{$.ajax(o)}}return id}},_removeXHR:function(xhrID){if(this.opts.queue){$.dequeue(document,this.qName)}this.inProgress--;this.requests[xhrID]=null;delete this.requests[xhrID]},_isAbort:function(xhr,o){var ret=!!(o.abortIsNoSuccess&&(!xhr||xhr.readyState===0||this.lastAbort===o.xhrID));xhr=null;return ret},_complete:function(context,origFn,xhr,status,xhrID,o){if(this._isAbort(xhr,o)){status='abort';o.abort.call(context,xhr,status,o)}origFn.call(context,xhr,status,o);$.event.trigger(this.name+'AjaxComplete',[xhr,status,o]);if(o.domCompleteTrigger){$(o.domCompleteTrigger).trigger(this.name+'DOMComplete',[xhr,status,o]).trigger('DOMComplete',[xhr,status,o])}this._removeXHR(xhrID);if(!this.inProgress){$.event.trigger(this.name+'AjaxStop')}xhr=null},_success:function(context,origFn,data,status,xhr,o){var that=this;if(this._isAbort(xhr,o)){xhr=null;return}if(o.abortOld){$.each(this.requests,function(name){if(name===o.xhrID){return false}that.abort(name)})}if(o.cacheResponse&&!cache[o.xhrID]){cache[o.xhrID]={status:xhr.status,statusText:xhr.statusText,responseText:xhr.responseText,responseXML:xhr.responseXML,_successData:data};if(xhr.getAllResponseHeaders){var responseHeaders=xhr.getAllResponseHeaders();$.extend(cache[o.xhrID],{getAllResponseHeaders:function(){return responseHeaders},getResponseHeader:(function(){var parsedHeaders={};$.each(responseHeaders.split("\n"),function(i,headerLine){var delimiter=headerLine.indexOf(":");parsedHeaders[headerLine.substr(0,delimiter)]=headerLine.substr(delimiter+2)});return function(name){return parsedHeaders[name]}}())})}}origFn.call(context,data,status,xhr,o);$.event.trigger(this.name+'AjaxSuccess',[xhr,o,data]);if(o.domSuccessTrigger){$(o.domSuccessTrigger).trigger(this.name+'DOMSuccess',[data,o]).trigger('DOMSuccess',[data,o])}xhr=null},getData:function(id){if(id){var ret=this.requests[id];if(!ret&&this.opts.queue){ret=$.grep($(document).queue(this.qName),function(fn,i){return(fn.xhrID===id)})[0]}return ret}return{requests:this.requests,queue:(this.opts.queue)?$(document).queue(this.qName):[],inProgress:this.inProgress}},abort:function(id){var xhr;if(id){xhr=this.getData(id);if(xhr&&xhr.abort){this.lastAbort=id;xhr.abort();this.lastAbort=false}else{$(document).queue(this.qName,$.grep($(document).queue(this.qName),function(fn,i){return(fn!==xhr)}))}xhr=null;return}var that=this,ids=[];$.each(this.requests,function(id){ids.push(id)});$.each(ids,function(i,id){that.abort(id)})},clear:function(shouldAbort){$(document).clearQueue(this.qName);if(shouldAbort){this.abort()}}};$.manageAjax._manager.prototype.getXHR=$.manageAjax._manager.prototype.getData;$.manageAjax.defaults={beforeCreate:$.noop,abort:$.noop,abortIsNoSuccess:true,maxRequests:1,cacheResponse:false,domCompleteTrigger:false,domSuccessTrigger:false,preventDoubbleRequests:true,queue:false};$.each($.manageAjax._manager.prototype,function(n,fn){if(n.indexOf('_')===0||!$.isFunction(fn)){return}$.manageAjax[n]=function(name,o){if(!managed[name]){if(n==='add'){$.manageAjax.create(name,o)}else{return}}var args=Array.prototype.slice.call(arguments,1);managed[name][n].apply(managed[name],args)}})})(jQuery);
	$("#search_form").attr("autocomplete", "off");
	var ajaxManager = $.manageAjax.create('cacheQueue', { abortOld: true, cacheResponse: true }); //and add an ajaxrequest with the returned object
	$("#searchbox").keyup(function(){
				
		var search_term = $("#searchbox").val();
		if(search_term != ""){	
			ajaxManager.add({
				url: '/json?q=' + search_term,
				dataType: 'json',
				success: function(data,status,req) {
				  if (data == null || data.results == null) {
					  return;
				  }
					var numTopResults = 0;
					if(data.results['top-results'] != null) {
						numTopResults = data.results["top-results"].hit.length;
						if (numTopResults == null) {
							numTopResults = 1;
						}
					}
					
					var numSuggestedResults = 0;
					if (data.results["suggested-results"] != null && data.results["suggested-results"].hit != null) {
						numSuggestedResults = data.results["suggested-results"].hit.length;
						if (numSuggestedResults == null) {
							numSuggestedResults = 1;
						}
					}
					
					if((numTopResults > 0 || numSuggestedResults > 0) && $("#search-drop").length == 0){
						var search_drop = '<div id="search-drop"><div id="suggestion-wrapper"><div class="search-heading"><p>SUGGESTIONS</p></div><ul class="search-dropdown-list suggested-results-list"><li><a href="#">Book of Mormon</a></li></ul></div><div class="search-heading top-results"><p>TOP RESULTS</p></div><ul class="search-dropdown-list top-results-list"><li><a href="#">Book of Mormon</a></li></ul></div>';
						
						
						$("#search_form").append(search_drop);
						//$(".search").append(search_drop);
						
						if(jQuery.browser.msie && jQuery.browser.version == 7.0) {
							$(".worldmap").attr("style","z-index: -1;");
							$("#multimedia_top_section").attr("style","z-index: -1;");
							$(".worldmap, .countrylist").css("z-index",-1);
							$("#newsroom-updates #newsroom-updates-input").css("z-index",-1);
							$("#newsroom-updates #newsroom-updates-input").attr("style","z-index: -1;");
						}
						
					}
					
					if(data.results['top-results'] != null) {
						$('.top-results').hide();
						$(".top-results-list").empty();
						for (var i=0; i<numTopResults; i++) {
							$('.top-results').show();
							 var hit = null;
							 if (numTopResults == 1) {
								hit = data.results["top-results"].hit;
							}
							else {
								hit = data.results["top-results"].hit[i];
							}
						
							$(".top-results-list").append('<li><a href="' + hit.url + '">' + hit.title + '</a></li>');
						}
					}
					
					if(numSuggestedResults == 0) {
						$('#suggestion-wrapper').hide();
					} else {
						$('#suggestion-wrapper').show();
						$(".suggested-results-list").empty();
						for (var i=0; i<numSuggestedResults; i++) {
							 var hit = null;
							 if (numSuggestedResults == 1) {
								hit = data.results["suggested-results"].hit;
							}
							else {
								hit = data.results["suggested-results"].hit[i];
							}
						
							$(".suggested-results-list").append('<li><a href="' + hit.url + '">' + hit.title + '</a></li>');
						}
					}
					
				
					var all_results = '<div class="search-footer"><a href="/search-results.xqy?q=' + search_term + '">SEE ALL RESULTS »</a></div>';
					if($(".search-footer").length == 0){
						$(".search-dropdown-list:last").append(all_results);
					}else{
						$(".search-footer").replaceWith(all_results);
					}
				}
			});
		}
		if(search_term == ""){
			$("#search-drop").remove();
			if(jQuery.browser.msie && jQuery.browser.version == 7.0) {
				$(".worldmap").attr("style","z-index: 0;");
				$("#multimedia_top_section").attr("style","z-index: 0;");
				$(".worldmap, .countrylist").css("z-index",0);
				$("#newsroom-updates #newsroom-updates-input").css("z-index",0);
							$("#newsroom-updates #newsroom-updates-input").attr("style","z-index: 0;");
			}
		}
	});
	
	$(document).click(function(){
		$("#search-drop").remove();
		if(jQuery.browser.msie && jQuery.browser.version == 7.0) {
			$(".worldmap").attr("style","z-index: 0;");
			$("#multimedia_top_section").attr("style","z-index: 0;");
			$(".worldmap, .countrylist").css("z-index",0);
			$("#newsroom-updates #newsroom-updates-input").css("z-index",0);
							$("#newsroom-updates #newsroom-updates-input").attr("style","z-index: 0;");
		}
		$("#language-select-list").hide();
		$("#language-select").removeClass("lang-dropped");
	});
	
	$("#search-drop").click(function(){
		return false;
	});
	$("#searchbox").click(function(){
		return false;
	});
	//END SEARCH AS YOU TYPE DROPDOWN
	
	$(".mmedia_search_results_head em:nth-child(3)").prepend("'").append("'");
	$(".mmedia_search_results_head .plural em").prepend("'").append("'");
	
	
	//MULTIMEDIA SEARCH RESULTS TOOLTIPS
	$(".mmedia_search_results li a").mouseenter(function(){
		//find element position and switch position of tooltip if past half way
		var pos = $(this).parent().position();
		if(pos.left > 480){
			$(this).parent().find(".mmedia-info").addClass("mmedia-right");
		}
		
		$(this).parent().find(".mmedia-info").delay(250).show(1);
	});
	$(".mmedia_search_results li a").mouseleave(function(){
		$(this).parent().find(".mmedia-info").stop(true, true).hide();
	});
	
	
	$(".mm-search-bounding a").mouseenter(function(){
		//find element position and switch position of tooltip if past half way
		var pos = $(this).parent().parent().position();
		if(pos.left > 480){
			$(this).parent().parent().find(".mmedia-info").addClass("mmedia-right");
		}
		
		$(this).parent().parent().find(".mmedia-info").delay(250).show(1);
	});
	$(".mm-search-bounding a").mouseleave(function(){
		$(this).parent().parent().find(".mmedia-info").stop(true, true).hide();
	});
	//END MULTIMEDIA SEARCH RESULTS TOOLTIPS
	
	
	if(jQuery.browser.msie && jQuery.browser.version == 8.0) {
		$("#newsroom-updates li#newsroom-updates-input").css("top","32px");
	}
	if(jQuery.browser.mozilla) {
		$("#newsroom-updates li#newsroom-updates-input").css("top","42px");
	}
	
	//FIX IE7 Z-INDEX PROBLEM ON MULTIMEDIA FILTER DROPDOWN
	if(jQuery.browser.msie && jQuery.browser.version == 7.0) {
		$("#topics_background, #leadership_organization").hover(function(){
			$("#multimedia_top_section").css("z-index",-1);
		},
		function(){
			$("#multimedia_top_section").css("z-index",0);
		});
		
		$(".top_story_large.banner_960.no-background").css("padding-bottom","35px");
		
		$(".mmfilter ul li").hover(function(){
			$("#multimedia_bottom_section").css("z-index",-1);
		},
		function(){
			$("#multimedia_bottom_section").css("z-index",0);
		});
		
		$(".mmedia_search_results li a").hover(function(){
			$(".mmedia_search_results li").css("position","static");
			$(".mm-search-play-button").css("top","30px");
			$(".mm-search-play-button").css("right","16px");
		},
		function(){
			$(".mmedia_search_results li").css("position","relative");
			$(".mm-search-play-button").css("top","6px");
			$(".mm-search-play-button").css("right","32px");
		});
		
		$("#add_maps").css("float","right").css("margin","0 10px 0 0").css("z-index","1");
		$("#maps_list li input").css("margin","0");
		$("#statistical_map input").css("margin","-4px 5px 0 15px");
		$(".article .mm-scroller").css("margin-bottom","10px");
		$("ul.report-list li span span").css("margin","-15px 0px 10px");
		$("#facts_and_stats h2, #contacts h2").css("line-height","30px").css("margin","20px 0 18px");
		$("#lo-line").css("margin-top","15px");
		$("#leadership_quicklook h4").css("width","65%").css("float","left");
		$("#topic_overview .body").css("float","left");
		$(".article #article_body").css("float","left");
		$("#facts_stats_table td img").css("margin-top","13px");
			$(".report-select ul").css("position","relative");
			$(".report-select ul").css("background-color","#515151");
			$(".report-head").css("z-index","0");
			$(".report-select").css("z-index","1001");
			$(".report-select ul").css("z-index","1000");
			$(".report-select ul li").css("background-color","#515151");
			$(".report-year").css("line-height","24px");
		$(".article p.style_guide").css("width","100%").css("margin-top","30px");
		$(".error_page #footer_top").css("margin-top","-96px");
		$(".article .mmslider-caption .img-caption").css("bottom","128px");
		$("#newsroom-updates li#newsroom-updates-input").css("top","42px");
		
		$(".facebook_like_button").parent().css("width","90px");
		
	}
	//END FIX IE7 Z-INDEX PROBLEM ON MULTIMEDIA FILTER DROPDOWN
	
	$("#stats_form input[type=checkbox]").removeAttr("checked");
	
	//LIMIT SEARCH TERM TEXT LENGTH
	if($(".mmedia_search_results_head p em").text().length/2 > 34){
		var term = $(".mmedia_search_results_head p em:first").text();
		var shorter = $(".mmedia_search_results_head p em").text().substr(0,34) + "...'";
		$(".mmedia_search_results_head p em").attr("title",term);
		$(".mmedia_search_results_head p em").text(shorter);
	}
	
	if($("#search_results_header .result").text().length/2 > 28){
		var term = $("#search_results_header .result").text();
		var shorter = $("#search_results_header .result").text().substr(0,28) + "...'";
		$("#search_results_header .result").attr("title",term);
		$("#search_results_header .result").text(shorter);
	}
	
	if($("#trending_topics a em").text().length > 42){
		var term = $("#trending_topics a em").text();
		var shorter = $("#trending_topics a em").text().substr(0,39) + "...";
		$("#trending_topics a em").text(shorter);
	}
	

	//END LIMIT SEARCH TERM TEXT LENGTH
	
	//CAPTION EXPANDER ON BIG TOP STORY TEMPLATE
	
	$(".caption-button").click(function(){
		$(".show-caption, .mmslider-caption .img-caption").slideToggle();
		if($(".caption-button img").hasClass("caption-shown")){
			$(".caption-button img").attr("src","/assets/images/caption-block-right.png");
			$(".caption-button img").removeClass("caption-shown");
		}else{
			$(".caption-button img").attr("src","/assets/images/caption-block-up.png");
			$(".caption-button img").addClass("caption-shown");
		}
		
	});
	
	//END CAPTION EXPANDER ON BIG TOP STORY TEMPLATE
	
	
	//WORLD REPORT WIDGET
	$("ul.report-list-head li .report-select").hover(function(){
		$(this).find("ul").toggle();
	}, function(){
		$(this).find("ul").toggle();
	});
	
	$("a[tab=tab_2]").click(function(){
		$(".tab_widget_foot a").css("visibility","hidden");
	});
	$("a[tab=tab_1]").click(function(){
		$(".tab_widget_foot a").css("visibility","visible");
	});
	
	
	$("ul.report-list li.clear").click(function(){
		if($(this).hasClass("report-current")){
			var videolink = "noid";
			var flashvars = {
				xmlSource: videolink
			};
			var params = {
				menu: "false",
				allowScriptAccess: "always",
				scale: "noscale",
				allowFullScreen: "true"
			};
			// set up expressinstall.swf
			swfobject.embedSWF("/assets/videos/uvp/ldsUniversalPlayer.swf", "ldsUniversalPlayer", "640", "360", "9.0.0", "http://www.ldsavd.org/ldsUniversalPlayer/swf/expressInstall.swf", flashvars, params);
			
			//init the youTubeLoader javascript methods
			SWFID = "ldsUniversalPlayer"
			
			$("#ldsUniversalPlayer").hide();
			$("#report-video").toggle("slow");
			$(".report-play").removeClass("report-play");	
			$(".report-current").removeClass("report-current");	
			
		}else{
			var videolink = $(this).attr("url");
			var flashvars = {
				xmlSource: videolink
			};
			var params = {
				menu: "false",
				allowScriptAccess: "always",
				scale: "noscale",
				allowFullScreen: "true"
			};
			// set up expressinstall.swf
			swfobject.embedSWF("/assets/videos/uvp/ldsUniversalPlayer.swf", "ldsUniversalPlayer", "640", "360", "9.0.0", "http://www.ldsavd.org/ldsUniversalPlayer/swf/expressInstall.swf", flashvars, params);
			
			//init the youTubeLoader javascript methods
			SWFID = "ldsUniversalPlayer"
			
			if($("#report-video").is(":visible")){
			
			}else{
				$("#report-video").toggle("slow");
			}
			$(".report-play").removeClass("report-play");	
			$(this).find("span.shell").addClass("report-play");
			$(".report-current").removeClass("report-current");	
			$(this).addClass("report-current");	
			
			var title_change = $(this).find(".report-title").text();
			$("#report-video-title h3").text(title_change);
			$("#ldsUniversalPlayer").show();
		}
	});
	
	$("#report-video-closer").click(function(){
		$("#ldsUniversalPlayer").hide();
		$("#report-video").toggle("slow");
		$(".report-play").removeClass("report-play");
	});
	
	
		//CLICKING NEW MONTH
	
		$(".report-select").click(function(event){
			event.stopPropagation();
		});
		
		$(".report-select li").click(function(event){
			var dates = $(this).text().split(" ",2);
			$(".report-month").text(" " + dates[0]);
			$(".report-year").text(dates[1]);
			var hide_this = $(".report-list:not(.standby)");
			$(".report-list.standby").removeClass("standby");
			hide_this.addClass("standby");
			
				$("#ldsUniversalPlayer").hide();
			if($("#report-video").is(":visible")){
				$("#report-video").toggle("slow");
			}
			$(".report-play").removeClass("report-play");	
			$(".report-current").removeClass("report-current");	
			
			
			var videolink = "noid";
			var flashvars = {
				xmlSource: videolink
			};
			var params = {
				menu: "false",
				allowScriptAccess: "always",
				scale: "noscale",
				allowFullScreen: "true"
			};
			swfobject.embedSWF("/assets/videos/uvp/ldsUniversalPlayer.swf", "ldsUniversalPlayer", "640", "360", "9.0.0", "http://www.ldsavd.org/ldsUniversalPlayer/swf/expressInstall.swf", flashvars, params);
			
			SWFID = "ldsUniversalPlayer"
			
			
			event.stopPropagation();
		});
	
		//END CLICKING NEW MONTH
		
		if(jQuery.browser.msie || jQuery.browser.mozilla) {
			if(jQuery.browser.msie && jQuery.browser.version == 7.0) {
				$("ul.report-list li span.shell").css("margin","11px 16px 0px 12px");
				$("ul.report-list li span.shell.report-play").css("margin","14px 16px 0px 12px");
			}else{
				$("ul.report-list li span.shell").css("margin","12px 16px 0px 12px");
			}
		}
		
		
	
	//END WORLD REPORT WIDGET
	
	//FACTS AND STATS MAP
	$("#maps_list li input").click(function(event){
		event.stopPropagation();
	});
	$("#maps_list li").click(function(){
		if($(this).find("input").attr("checked")){
			$(this).find("input").removeAttr("checked");
		}else{
			$(this).find("input").attr("checked","checked");
		}
	});
	
	$("#statistical_map input").change(function(){
		var place = $(this).attr("id");
		var frame = $("#map_frame").attr("src");
		var frame_split1 = frame.split("places=")[0];
		var frame_split2 = frame.split("places=")[1];
		
		var frame_splitA = frame.split("#")[0];
		var frame_splitB = frame.split("#")[1];
		
		var frame_splitI = frame.split(place)[0];
		var frame_splitII = frame.split(place)[1];
		
		if(frame_split2 != undefined){
			show_item = frame_split1 + "places=" + place + "," + frame_split2;
		}else{
			show_item = frame_splitA + "#places=" + place + "&" + frame_splitB;
		}
		
		if($(this).attr("checked")){
			
			$("#map_frame").attr("src",show_item);
		}else{
			var show_item = frame_splitI + frame_splitII;
			$("#map_frame").attr("src",show_item);
		}
	});
	
	//END FACTS AND STATS MAP
	
	//FACTS AND STATS INFO
	
	var mem = $("#stat_membership").text();
	var mem = mem.substring(0,4);
	var mem = mem.replace(",",".");
	
	var cong = $("#stat_congregations").text();
	var mis = $("#stat_missionaries").text();
	
	$("#mem_stat span").text(mem).show();
	$("#cong_stat").text(cong).show();
	$("#mis_stat").text(mis).show();
	
	//END FACTS AND STATS INFO
	
	//PRINT ICON ADDING
	/* the following check makes sure to not append the print link on the front page top story */
	if($('.social-media, .social_media').parents('#top_story').length == 0) {
		$(".social-media, .social_media").after("<a href='#' class='print_this' title='Print Page'>PRINT&nbsp;&nbsp;&nbsp;&nbsp; |</a>");
	
		$(".print_this").click(function(event){
			window.print();
			event.preventDefault();
		});
	}
	if($('#sm-top')) {
		$("#sm-top").after("<a style='font-size:10px;margin-top:2px;text-decoration:none;' href='#' class='print_this' title='Print Page'>PRINT&nbsp;&nbsp;&nbsp;&nbsp; |</a>");
	
		$(".print_this").click(function(event){
			window.print();
			event.preventDefault();
		});
	}
	if($('#sm-bottom')) {
		$("#sm-bottom").after("<a style='font-size:10px;margin-top:2px;text-decoration:none;' href='#' class='print_this' title='Print Page'>PRINT&nbsp;&nbsp;&nbsp;&nbsp; |</a>");
	
		$(".print_this").click(function(event){
			window.print();
			event.preventDefault();
		});
	}
	//END PRINT ICON ADDING
	var scroll_count = $(".scrollable img").length;
	
	
	if(scroll_count == 1){
		$(".article .mmslider-caption .img-caption, #topic_overview .mmslider-caption .img-caption").css("bottom","46px");
	}
	
	

});
