/**
 * @fileoverview Main JavaScript file for sacbee.com.  Houses global functions.
 */

// Deprecated navbar vars
var topnav_default = '';
var topnav_over_main = '';
var topnav_over_sub = '';
var subnav_default = jQuery('#main-nav .subnav li.active');
var subnav_over = '';
var subsubnav_default = jQuery('.subsubnav li.active');
var subsubnav_over = '';

// configuration variables (should all be deprecated now)
var multimediabar_enabled = false;
var mini_slideshow_enabled = false;

/**
 * Enables the main (top) bar of the navigation bar.
 *
 * @deprecated Use the new Sacbee.enable_navbar() code now.
 */
function manage_topnav(){
	var showmenu = '';
	if(topnav_over_main || topnav_over_sub){
		if(topnav_over_main && !topnav_over_sub){
			showmenu = topnav_over_main;
		}else if(!topnav_over_main && topnav_over_sub){
			showmenu = topnav_over_sub;
		}else{
			if(topnav_over_main==topnav_over_sub){
				showmenu = topnav_over_main;
			}
		}
		jQuery('#main-nav>ul>li.active').removeClass('active');
		jQuery(showmenu).addClass('active')
	}else{
		if(jQuery(topnav_default).attr('class') != 'active'){
			jQuery('#main-nav>ul>li.active').removeClass('active');
			jQuery(topnav_default).addClass('active');
		}
	}
}

/**
 * Enables the subnav bar.
 *
 * @deprecated Use the new Sacbee.enable_navbar() code now.
 */
function manage_subnav(){
	var showmenu = '';

	if(subnav_over) {
		var html = jQuery('#main-nav .subnav li.active').eq(0).html();
			if(jQuery(subnav_over).html() != html){
			jQuery('#main-nav .subnav li.active').removeClass('active');
			jQuery(subnav_over).addClass('active')
		}
	} else {
		if(!jQuery(subnav_default).hasClass('active')){
			jQuery('#main-nav .subnav li.active').removeClass('active');
			jQuery(subnav_default).addClass('active');
		}
	}
}

/**
 * Enables the sub-subnav bar (which we don't use).
 *
 * @deprecated Use the new Sacbee.enable_navbar() code now.
 */
function manage_subsubnav(){
	var showmenu = '';

	if(subsubnav_over) {
		var html = jQuery('.subsubnav li.active').eq(0).html();
			if(jQuery(subsubnav_over).html() != html){
			jQuery('.subsubnav li.active').removeClass('active');
			jQuery(subsubnav_over).addClass('active')
		}
	} else {
		if(!jQuery(subsubnav_default).hasClass('active')){
			jQuery('.subsubnav li.active').removeClass('active');
			jQuery(subsubnav_default).addClass('active');
		}
	}
}

/**
 * Highlights the proper tab in the navbar.  Called after the navbar loads,
 * usually via the navigation_highlight Page Element.
 * @param {String} nav_id the ID of the top tab to highlight
 * @param {String} subnav_str a substring of the subnav link to highlight
 *
 * @deprecated Use Sacbee.set_nav_subnav() instead.
 */
function set_nav_subnav (nav_id, subnav_str) {
	// Call thre new navbar stuff...
	Sacbee.set_nav_subnav("main-navbar", nav_id.replace("#", ""), subnav_str);

	// Deprecated code below...
	jQuery("#main-nav li").removeClass("active");
	topnav_default = nav_id;

	if (subnav_str) {
		var subnav_element = jQuery(topnav_default + " li a:contains(" + subnav_str + ")").parent();

		subnav_default = subnav_element;
		subnav_element.addClass("active").parent().parent().addClass("active");
	}

	manage_topnav();
}

/**
 * Enables the main navigation bar.  Fired inline on all pages just after the navbar loads.
 *
 * @deprecated Use the new Sacbee.enable_navbar() code now.
 */
function enable_navbar () {
	// Top navigation menu
	topnav_default = '#' + jQuery('div#main-nav ul li.active').attr('id');
	var timeo;
	jQuery('div#main-nav ul:first>li').hover(
		//function(){ topnav_over_main = '#'+jQuery(this).attr('id'); manage_topnav(); },
		function(){ topnav_over_main = '#'+jQuery(this).attr('id'); clearTimeout(timeo); manage_topnav(); },
		//function(){ topnav_over_main = ''; manage_topnav(); }
		function(){ topnav_over_main = ''; timeo = setTimeout("manage_topnav();", 500); }
	);
	jQuery('div#main-nav ul ul').hover(
		function(){ topnav_over_sub = '#'+jQuery(this).parents('li').attr('id'); manage_topnav(); },
		function(){ topnav_over_sub = ''; manage_topnav(); }
	);

	// Sub navigation menu
	subnav_default = jQuery('#main-nav .subnav li.active');
	jQuery('#main-nav .subnav li').hover(
		function(){ subnav_over = jQuery(this); manage_subnav(); },
		function(){ subnav_over = ''; manage_subnav(); }
	);

	// Optional third level navigation menu
	if(jQuery('.subsubnav').length) {
		subsubnav_default = jQuery('.subsubnav li.active');
		jQuery('.subsubnav li').hover(
			function(){ subsubnav_over = jQuery(this); manage_subsubnav(); },
			function(){ subsubnav_over = ''; manage_subsubnav(); }
		);
	}
}

/**
 * Enables the dynamic search box.  Fired inline on all pages.
 *
 * @deprecated Wrapper for Sacbee.enable_searchbox() now.
 */
function enable_searchbox () {
	//searchbox = 1;
	Sacbee.enable_searchbox();
}

/**
 * Enables the Reader Servives menu(s).  Fired inline on all pages on all pages.
 *
 * @deprecated  Yep, just a wrapper now.
 */
function enable_readerservices_menus () {
	Sacbee.enable_readerservices_menus();
}

/**
 * Enables the Multimedia Bar.  Called either inline immediatly after the
 * multimedia bar (in the page element) or from the ready() function below.
 *
 * @deprecated  Yep, just a wrapper now.
 */
function enable_multimediabar () {
	Sacbee.enable_multimediabar();

	// set this so we can test for it in the ready() function belore and not run twice
	multimediabar_enabled = true;
}

/**
 * Enables a mini-slideshow.  Called either inline immediatly after the mini-slideshow
 * or from the ready() function.
 *
 * @deprecated Is a wrapper for Sacbee.enable_mini_slideshow() now.
 */
function enable_mini_slideshow () {
	// gross little workaround for old slideshows that don't have the new
	// classes and if you're here, you're an old slideshow...
	jQuery('#mini-slideshow').addClass("mini-slideshow");
	jQuery('#mini-slideshow-loader').addClass("mini-slideshow-loader");

	Sacbee.enable_mini_slideshow("mini-slideshow");

	// set this so we can test for it in the ready() function below and not run twice
	mini_slideshow_enabled = true;
}

/**
 * Enable a full-sized slideshow.  Called inline on gallery-detail pages.  Note: this function will look for
 * a GET param called "image" and, if present, use that frame as a starting slide.
 * @param {Number} [index=0] zero-based index of the first slide to be displayed.  Will override the "image" GET param.
 *
 * @deprecated Is a wrapper for Sacbee.enable_big_slideshow(index)
 */
function enable_big_slideshow2 (index) {
	Sacbee.enable_big_slideshow(index);
}

/**
 * Returns a pretty "Monday, November 24, 2008".  Called inline on all pages.
 * @return {String} a date string
 *
 * @deprecated Use Sacbee.display_date_str().
 */
function display_date_str () {
	return Sacbee.display_date_str();
}

/**
 * Enables the button that toggles comments on and off.  Called in the main ready loop.  Assumes a button construct on the page along the lines of:
 * <pre>&lt;div id="comment_toggle" style="display: none"&gt;
 *     &lt;img src="http://media.sacbee.com/static/images/hide_comments_btn.gif" alt="hide comments" /&gt;
 * &lt;/div&gt;</pre>
 *
 * @deprecated Use Sacbee.enable_comment_toggle().
 */
function enable_comment_toggle () {
	Sacbee.enable_comment_toggle();
}

/**
 * Reengineered implementation of MI's miScriptScheduler class.
 *
 * @class Provides a way to test to see if a script has been loaded previously, and if so, does not load it again.
 * Checks for the object that will be created by a script, if the object exists, the script has been loaded.
 *
 * Note: this is used by the MI Poll
 *
 * @deprecated This is an MI custom function, included here only for performance reasons.
 */
function miScriptScheduler() {
	/** value of function check (eg. window.jQuery). */
	this.scriptCheck = "";
	/** file path to required script. */
	this.scriptPath = "";
}

/**
 * If {@link scriptCheck} doesn't exist, injects the script set by {@link scriptPath} into the DOM.
 */
miScriptScheduler.prototype.scheduleScript = function () {
	if (!this.scriptCheck) {
		/* script test function not found, load script with no waiting */
		var tempElement = document.createElement("script");
		tempElement.src = this.scriptPath;

		var bases = document.getElementsByTagName('base');
		if (bases.length && bases[0].childNodes.length) {
		   bases[0].appendChild(tempElement);
		} else {
			document.getElementsByTagName('head')[0].appendChild(tempElement);
		}
	} else {
		return(0);
	}
}


/*
 * jQuery ready-loop code
 */
jQuery(document).ready(function(){
// zebra lists and tables
	jQuery('ul.zebra').each(function(){
		jQuery('li:nth-child(odd)',this).addClass('odd');
	});
	jQuery('table.zebra').each(function(){
		jQuery('tr:nth-child(odd)',this).addClass('odd');
	});

// create tabbed content areas
// uses jQuery UI tabs plugin - http://ui.jquery.com/
	if (jQuery('div.tabbed').length) {
		jQuery('div.tabbed').tabs();
		//jQuery('div.tabbed').tabs();		// ui.tabs 1.7
		//jQuery('div.tabbed>ul').tabs();		// ui.tabs 1.5
		jQuery('div.tabbed ul.tabs li a').focus(function(){
			this.blur();
		});
	}

// social bookmark tool
	jQuery('div#socialwidget li#social-dropdown div.ctrl a').toggle(
		function(){
			jQuery(this).addClass('active');
			jQuery(this).parents('li#social-dropdown').find('div.dropdown').show();
		},
		function(){
			jQuery(this).removeClass('active');
			jQuery(this).parents('li#social-dropdown').find('div.dropdown').hide();
		}
	);
	jQuery('div#socialwidget li#social-dropdown div.ctrl a').focus(function(){
		this.blur();
	});

// close open dropdowns when clicking empty space
	jQuery('body').click(function(){
		if(jQuery('li#social-dropdown div.dropdown:visible').get(0)){
			jQuery('div#socialwidget li#social-dropdown div.ctrl a').trigger('click');
		}

		jQuery.each(jQuery('div.readerservices-menu'), function(){
			if(jQuery(this).parent('.active').get(0)){
				jQuery(this).find('a').trigger('click');
			}
		});
	});

// multimedia bar
// @deprecated shouldn't be used anywhere
	if (jQuery('#multimediabar').length && !multimediabar_enabled)
		enable_multimediabar();

// mini-slideshow
// @deprecated shouldn't be used anywhere
	if (jQuery('#mini-slideshow').length && !mini_slideshow_enabled)
		enable_mini_slideshow();

//Factbox Expander
	jQuery('div.factbox_header a').click( function() {
		var id = this.id;
		if (jQuery('div.'+id).is(":hidden")) {
			jQuery('span.'+id).removeClass('icon-down');
			jQuery('span.'+id).addClass('icon-up');
		}
		else {
			jQuery('span.'+id).removeClass('icon-up');
			jQuery('span.'+id).addClass('icon-down');
		}
		jQuery('div.'+id).slideToggle("normal");
	});

	// open the first factbox...
	jQuery('div.factbox_header a:first').click();

//Comment Guidelines Expander
	jQuery('div.comment_guidelines a').click( function() {
		var id = this.id;
		if (jQuery('div.'+id).is(":hidden")) {
			jQuery('span.'+id).removeClass('icon-down');
			jQuery('span.'+id).addClass('icon-up');
		}
		else {
			jQuery('span.'+id).removeClass('icon-up');
			jQuery('span.'+id).addClass('icon-down');
		}
		jQuery('div.'+id).slideToggle("normal");
	});


	// Fix up the story list .stories class list items to have a last class, per the
	// NavArts design.
	// Easier to use jquery for this than trying to get the tmplsys to put class="last"
	// on every  variant story stack.
	jQuery(".stories li:last-child").addClass("last");
	jQuery(".links li:last-child").addClass("last");

	jQuery(".highlights .story:last").addClass("last");
	jQuery(".gallery_index .grid-a .story:last").removeClass("last");
	jQuery(".gallery_index .grid-d .story:last").removeClass("last");
	jQuery("#bloggers dd:last").addClass("last");
	jQuery("#commented li:last").addClass("last");
	jQuery(".cartoon").removeClass("last");
	jQuery(".story-top").removeClass("last");
	jQuery("div.boxshade .story-top").addClass("last");

	var count = jQuery("#latest li").length;
	if(count < 10) {
		jQuery("#latest .stories >li:last").removeClass("last");
		jQuery("#extrastories >li:last").addClass("last");
	}

	jQuery("div.button a button").click(function () {
		document.location = jQuery(this).parent().attr("href");
	});

	Sacbee.enable_comment_toggle();
});


/**
 * @namespace Sacbee namespace to isolate our stuff.
 */
var Sacbee = function() {
	/**
	 * Internal var for HTTP GET params.
	 * @private
	 */
	var $_GET = {};

	/*
	 * Load any HTTP GET params
	 */
	document.location.search.replace(/\??(?:([^=]+)(?:=([^&]*))?&?)/g, function () {
		function decode(s) {
			if (typeof(s) !== 'undefined') {
				return decodeURIComponent(s.split("+").join(" "));
			}
		}

		$_GET[decode(arguments[1])] = decode(arguments[2]);
	});

	/**
	 * Resets the navbar to the "default_active" highlights.
	 * @private
	 */
	function navbar_reset_highlights (element) {
		jQuery('#' + element + ' li').removeClass('active');
		jQuery('#' + element + ' .subnav').removeClass('active');
		jQuery('#' + element + ' .default_active').addClass('active');
		jQuery('#' + element + ' .default_active .subnav').addClass('active');
	}

	return {
		/**
		 * Name/value array of HTTP GET parameters.
		 */
		GET: $_GET,

		/**
		 * Script node util function via Script DOM Element and Script onLoad techniques.
		 * @param {String} url Script source.
		 * @param {Function} cbfunc Callback function.
		 *
		 * @see Even Faster Web Sites, Souders
		 */
		addScriptNode: function(url, cbfunc) {
			var doc = document;
			var domscript = doc.createElement('script');
			domscript.setAttribute('src', url);
			domscript.onloadDone = false;
			domscript.onload = function() {
				domscript.onloadDone = true;
				if (typeof(cbfunc) === 'function') {
					cbfunc(domscript);
				}
			};
			domscript.onreadystatechange = function() {
				if (( "loaded" === domscript.readyState || "complete" === domscript.readyState ) && ! domscript.onloadDone) {
					domscript.onloadDone = true;
					cbfunc(domscript);
				}
			};
			doc.getElementsByTagName('head')[0].appendChild(domscript);
		},

		/**
		 * Add CSS link node to pull in external stylesheet.
		 * @param {String} url Stylesheet source.
		 */
		addStyleNode: function(url) {
			var doc = document;
			var stylenode = doc.createElement('link');
			stylenode.setAttribute('rel', 'stylesheet');
			stylenode.setAttribute('type', 'text/css');
			stylenode.setAttribute('href', url);
			doc.getElementsByTagName('head')[0].appendChild(stylenode);
		},

		/**
		 * Enables the main navigation bar.	 Fired inline on all pages just after
		 * the navbar loads.
		 * @param {String} element The navbar DOM ID.
		 * @param {String} nav_id the ID of the top tab to highlight
		 * @param {String} subnav_str a substring of the subnav link to highlight
		 */
		enable_navbar: function (element, nav_id, subnav_str) {
			if (typeof(nav_id) === "undefined") {
				nav_id = 'nav-news';
			}
			Sacbee.set_nav_subnav(element, nav_id, subnav_str);

			jQuery('#' + element + ' .topnav').mouseover(function () {
				if (jQuery(this).attr('id') != "nav-ad") {
					jQuery('#' + element + ' .topnav').removeClass('active');
					jQuery(this).addClass('active');
					jQuery('#' + element + ' .topnav').find('.subnav').removeClass('active');
					jQuery(this).find('.subnav').addClass('active');
				}
			});

			jQuery('#' + element + ' .subnav li').mouseover(function () {
				jQuery('#' + element + ' .subnav li').removeClass('active');
				jQuery(this).addClass('active');
			});

			jQuery('#' + element).mouseout(function () {
				navbar_reset_highlights(element);
			});
		},

		/**
		 * Highlights the proper tab in the navbar.	 Called after the navbar loads if necessary.
		 * @param {String} element The navbar DOM ID.
		 * @param {String} nav_id the ID of the top tab to highlight
		 * @param {String} subnav_str a substring of the subnav link to highlight
		 */
		set_nav_subnav: function (element, nav_id, subnav_str) {
			if (jQuery('#' + element + ' #' + nav_id).length === 0) {
				nav_id = "nav-news";
			}

			// Clear any existing active tabs
			jQuery(".default_active").removeClass('default_active');

			// Set what we want
			jQuery('#' + element + ' #' + nav_id).addClass('default_active');

			// Set the subnav highlight, if we have one
			if (typeof(subnav_str) !== "undefined" && subnav_str !== "") {
				jQuery('#' + element + ' #' + nav_id + ' .subnav li a:contains("' + subnav_str + '")').parent().addClass('default_active');
			}

			navbar_reset_highlights(element);
		},

		/**
		 * Enables a mini-slideshow.  Always called inline immediatly after the mini-slideshow.
		 * Also called in the ready() function via the old global enable_mini_slideshow().
		 * This use is deprecated.
		 * @param {String} element_id The ID where the slideshow should go.
		 */
		enable_mini_slideshow: function (element_id) {
			if (typeof(element_id) === 'undefined') {
				element_id = 'mini-slideshow';
			}

			jQuery('#' + element_id + ' div.slides ul').cycle(
				{
					fx: 'scrollHorz',
					speed: 200,
					timeout: 0,
					prev: '#' + element_id + ' span.prev a',
					next: '#' + element_id + ' span.next a',
					pager: '#' + element_id + ' span.indicator',
					pagerAnchorBuilder: function (idx, slide) {
						return '<a href="#"><img src="http://media.sacbee.com/static/img/blank.gif" alt=""\/><\/a>';
					},
					after: function () {
						jQuery('#' + element_id + ' div.slides ul').animate(
							{
								height: parseInt(jQuery('img', this).attr('height') + 1) + 'px'
							},
							"fast");
						jQuery('#' + element_id + ' div.captions').hide().html(jQuery('.txt', this).html()).show();
					}
				}
			);

			jQuery('#' + element_id + ' .mini-slideshow-loader').hide();
			jQuery('#' + element_id + ' div.txt').hide();

			// Create a caption block outside of the cycled block and fill it with the first caption.
			// Later we'll put the other captions in here
			jQuery('#' + element_id + ' div.slides').after(jQuery('<div/>').addClass('captions').html(jQuery('#' + element_id + ' ul li:first .txt').html()));

			// Needed for Safari so the first image shows...
			jQuery('#' + element_id + ' div.slides ul li').css('height', parseInt(jQuery('#' + element_id + ' ul li:first img').attr('height') + 1) + 'px');
		},

		/**
		 * Enables a mini-slideshow from a gallery url.
		 * @param {String} element The ID where the gallery should go.
		 * @param {String} url The gallery URL.
		 * @param {String} opts.title A title to use for the gallery.
		 * @param {Number} opts.count A count to limit the headlines to.
		 */
		gallery_mini_slideshow: function (element, url, opts) {
			var element_id = '#' + element;
			var data_url = url.replace(/\.html$/, ".xml");
			var title = (opts.title) ? opts.title : "Gallery Slideshow";

			jQuery(element_id).addClass('mini-slideshow');

			// Make our generic slideshow container...
			var box_header = jQuery('<div/>').addClass('boxheader').appendTo(element_id);
			var header_div = jQuery('<div/>').addClass('header').appendTo(box_header);
			var title_div = jQuery('<div/>').addClass('name').appendTo(header_div);
			var title = jQuery('<a/>').attr('href', url).html(title).appendTo(title_div);
			var loader_span = jQuery('<span/>').addClass('mini-slideshow-loader').appendTo(title_div);
			jQuery('<img/>').attr('src', 'http://media.sacbee.com/static/img/ajax-loader-slideshow.gif').attr('alt', 'Loading').appendTo(loader_span);

			var controls = jQuery('<div/>').addClass('controls').css('margin-top', '7px').appendTo(header_div);
			var prev = jQuery('<span/>').addClass('prev').appendTo(controls);
			var prev_link = jQuery('<a/>').appendTo(prev);
			jQuery('<img/>').attr('src', 'http://media.sacbee.com/static/img/mm-mini-left-transparent.gif').attr('alt','previous').appendTo(prev_link);
			jQuery('<span/>').addClass('indicator').appendTo(controls);
			var next = jQuery('<span/>').addClass('next').appendTo(controls);
			var next_link = jQuery('<a/>').appendTo(next);
			jQuery('<img/>').attr('src', 'http://media.sacbee.com/static/img/mm-mini-right-transparent.gif').attr('alt','next').appendTo(next_link);

			var slides = jQuery('<div/>').addClass('slides').appendTo(box_header);

			var button = jQuery('<div/>').addClass('button').css('margin-left', '5px').appendTo(element_id);
			var button_link = jQuery('<a/>').attr('href', url).appendTo(button);
			jQuery('<button/>').html('See Full Gallery').appendTo(button_link)

			// Use the gallery XML to load it up...
			jQuery.ajax({
				url: data_url,
				success: function (xml_data) {
					var ul = jQuery('<ul/>').appendTo(slides);

					var images = xml_data.getElementsByTagName('img');

					for (var i = 0, il = images.length; i < il; i++) {
						if (opts.count && i >= opts.count)
							break;

						var image = images[i];
						var image_src = image.getAttribute('src');
						var image_height = image.getAttribute('height') * 316/640;
						var image_width = image.getAttribute('width') * 316/640;
						// Try to finagle a photo credit from the caption
						var photoby_pattern = /\s*\((.*?)\)$/;
						var photoby_match = image.getAttribute('caption').match(photoby_pattern);
						var photoby = (photoby_match) ? jQuery('<h4/>').html(photoby_match[1]) : "";
						var caption = image.getAttribute('caption').replace(photoby_pattern, "");

						var li = jQuery('<li/>');
						var image_div = jQuery('<div/>').addClass('image embedded box multi').appendTo(li);
						var link = jQuery('<a/>').attr('href', url + '?image=' + (i + 1)).appendTo(image_div);
						jQuery('<img/>').attr('src', image_src.replace('standalone', 'embedded')).attr('height', image_height).attr('width', image_width).appendTo(link);
						jQuery('<div/>').addClass('txt').css('display', 'none').html(caption).prepend(photoby).appendTo(li);

						li.appendTo(ul);
					};

					Sacbee.enable_mini_slideshow(element);
				}
			});
		},

		/**
		 * Enables a full-sized slideshow from a gallery url.
		 * @param {String} element The ID where the gallery should go.
		 * @param {String} url The gallery URL.
		 * @param {String} opts.title A title to use for the gallery.
		 * @param {Number} opts.count A count to limit the headlines to.
		 */
		gallery_big_slideshow: function (element, url, opts) {
			var element_id = '#' + element;
			var data_url = url.replace(/\.html$/, ".xml");
			var title = (opts.title) ? opts.title : "Gallery Slideshow";

			jQuery(element_id).addClass('big-slideshow');

			// Make our generic slideshow container...
			var title_div = jQuery('<div/>').addClass('name').appendTo(element_id);
			var title = jQuery('<a/>').attr('href', url).html(title).appendTo(title_div);
			var loader_span = jQuery('<span/>').attr('id', 'big-slideshow-loader').appendTo(title_div);
			jQuery('<img/>').attr('src', 'http://media.sacbee.com/static/img/ajax-loader-slideshow.gif').attr('alt', 'Loading').appendTo(loader_span);

			var controls = jQuery('<div/>').addClass('controls').css('margin-top', '7px').appendTo(element_id);
			var prev = jQuery('<span/>').addClass('prev').appendTo(controls);
			var prev_link = jQuery('<a/>').appendTo(prev);
			jQuery('<img/>').attr('src', 'http://media.sacbee.com/static/img/mm-mini-left-transparent.gif').attr('alt','previous').appendTo(prev_link);
			jQuery('<span/>').addClass('indicator').appendTo(controls);
			var next = jQuery('<span/>').addClass('next').appendTo(controls);
			var next_link = jQuery('<a/>').appendTo(next);
			jQuery('<img/>').attr('src', 'http://media.sacbee.com/static/img/mm-mini-right-transparent.gif').attr('alt','next').appendTo(next_link);

			var slides = jQuery('<div/>').addClass('slides').appendTo(element_id);

			//var button = jQuery('<div/>').addClass('button').css('margin-left', '5px').appendTo(element_id);
			//var button_link = jQuery('<a/>').attr('href', url).appendTo(button);
			//jQuery('<button/>').html('See Full Gallery').appendTo(button_link)

			// Use the gallery XML to load it up...
			jQuery.ajax({
				url: data_url,
				success: function (xml_data) {
					var ul = jQuery('<ul/>').appendTo(slides);

					var images = xml_data.getElementsByTagName('img');

					for (var i = 0, il = images.length; i < il; i++) {
						if (opts.count && i >= opts.count)
							break;

						var image = images[i];
						var image_src = image.getAttribute('src');
						var image_height = image.getAttribute('height');
						var image_width = image.getAttribute('width');

						// Try to finagle a photo credit from the caption
						var photoby_pattern = /\s*\((.*?)\)$/;
						var photoby_match = image.getAttribute('caption').match(photoby_pattern);
						var photoby = (photoby_match) ? photoby_match[1] : "";
						var caption = image.getAttribute('caption').replace(photoby_pattern, "");

						var li = jQuery('<li/>');
						var image_div = jQuery('<div/>').addClass('image standalone').appendTo(li);
						var link = jQuery('<a/>').attr('href', url + '?image=' + (i + 1)).appendTo(image_div);
						jQuery('<img/>').attr('src', image_src.replace('standalone', 'embedded')).attr('height', image_height).attr('width', image_width).appendTo(link);
						jQuery('<div/>').addClass('gallerycaption').css('display', 'none').append(
							jQuery('<div/>').addClass('galcaption').html(caption)
						).append(
							jQuery('<div/>').addClass('galbyline').html(photoby)
						).appendTo(image_div);

						li.appendTo(ul);
					};

					Sacbee.enable_big_slideshow();
				}
			});
		},

		/**
		 * Enables the dynamic search box.  Fired inline on all pages (in /shared/searchbox_default.comp and sbNaHeaderSearch).
		 */
		enable_searchbox: function () {
			// Show the options on focus (i.e.: clicking).
			jQuery('div.searchmain input:text').focus(function () {
				jQuery('div.searchmain div.controller span:hidden').css('cursor','pointer').show();
				jQuery('div.searchdropdown:hidden').show();
				jQuery(this).css('background-position','0 -18px')
			});

			// Clicking elsewhere will restore that "keyword search" background
			// if the search field is empty.
			jQuery('div.searchmain input:text').blur(function () {
				if (jQuery('div.searchmain input:text').val() == "") {
					jQuery(this).css('background-position','0 0');
				}
			});

			// Make the close box close things
			jQuery('div.searchmain div.controller span').click(function () {
				jQuery(this).hide();
				jQuery('div.searchdropdown:visible').hide();
				if (jQuery('div.searchmain input:text').val() == "") {
					jQuery(this).css('background-position','0 0');
				}
			});
		},

		/**
		 * Enables the Reader Servives menu(s).  Fired inline on all pages on all pages (in /shared/usertools_default.comp).
		 */
		enable_readerservices_menus: function () {
			jQuery('div.readerservices-menu').parent().hover(
				function () {
					jQuery(this).addClass('active');
				},
				function () {
					jQuery(this).removeClass('active');
				}
			);

			// Disable clicks on the reader services links
			jQuery('div.readerservices-menu a').click(function(){
				return false;
			});
		},

		/**
		 * Returns a pretty "Monday, November 24, 2008".  Called inline on all pages (in generic.comp).
		 * @return {String} a date string
		 */
		display_date_str: function () {
			var sbMiNow = new Date();
			var sbMiDayOfWeek = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
			var sbMiMonth = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

			return sbMiDayOfWeek[sbMiNow.getDay()] + ", " + sbMiMonth[sbMiNow.getMonth()] + " " + sbMiNow.getDate() + ", " + sbMiNow.getFullYear();
		},

		/**
		 * Enables the button that toggles comments on and off.  Called in the main ready loop.
		 * Assumes a button construct on the page along the lines of:
		 *   <pre>&lt;div id="comment_toggle" style="display: none"&gt;
		 *     &lt;img src="http://media.sacbee.com/static/images/hide_comments_btn.gif" alt="hide comments" /&gt;
		 *   &lt;/div&gt;</pre>
		 */
		enable_comment_toggle: function () {
			if (jQuery('#comment_toggle').length) {
				function _hide_comments () {
					jQuery('#comment_toggle img').attr('src', '/static/images/comments/commentsShow.gif').attr('alt', 'show comments');
					jQuery('.comment_guidelines').hide();
					jQuery('#commentingStage').hide();
					jQuery('#disqus_thread').hide();
				}

				function _show_comments () {
					jQuery('#comment_toggle img').attr('src', '/static/images/comments/commentsHide.gif').attr('alt', 'hide comments');
					jQuery('.comment_guidelines').show();
					jQuery('#commentingStage').show();
					jQuery('#disqus_thread').show();
				}

				if (jQuery.cookie('global_comment_pref') == "hide") {
					_hide_comments();
				} else {
					_show_comments();
				}
				jQuery('#comment_toggle').show();

				jQuery('#comment_toggle').click(function () {
					if (jQuery.cookie('global_comment_pref') == "hide") {
						jQuery.cookie('global_comment_pref', 'show', { path: '/', expires: 0, domain: 'sacbee.com' });

						// Delete older cookie too, just in case
						jQuery.cookie('global_comment_pref', 'show', { path: '/', expires: 0, domain: 'www.sacbee.com' });
						jQuery.cookie('global_comment_pref', 'show', { path: '/', expires: 0, domain: 'blogs.sacbee.com' });

						if (typeof(s) != "undefined")
							s.tl(this,'o','Comments-show');	// Omniture click counter

						_show_comments();
					} else {
						jQuery.cookie('global_comment_pref', 'hide', { path: '/', expires: 365, domain: 'sacbee.com' });
						if (typeof(s) != "undefined")
							s.tl(this,'o','Comments-hide');	// Omniture click counter

						_hide_comments();
					}
				});
			}
		},

		/**
		 * Enables the Multimedia Bar.  Called either inline immediatly after the
		 * multimedia bar (in the page element) or from the ready() function below.
		 */
		enable_multimediabar: function () {
			jQuery('div#multimediabar .mm-links li:first').addClass('active');
			jQuery('div#multimediabar div.mm-panelset').each(function(i){
				var thePanelset = i+1;
				jQuery('div.mm-panels',this).cycle({
					fx: 'scrollHorz',
					speed: 500,
					timeout: 0,
					cleartypeNoBg: true,
					next: '#mm-panelset'+thePanelset+' .mm-right a',
					prev: '#mm-panelset'+thePanelset+' .mm-left a',
					pagerAnchorBuilder: function(idx,slide){
						return '<a href="#"><img src="http://media.sacbee.com/static/img/blank.gif" alt=""><\/a>';
					}
				});
			});
			jQuery('#multimediabar .mm-left a, #multimediabar .mm-right a').focus(function(){ this.blur(); });

			// pause all except the first panelset
			jQuery('div#multimediabar div.mm-panelset:not(#mm-panelset1) div.mm-panels').cycle('pause');

			// tabs switch panelsets
			jQuery('div#multimediabar .mm-links a').click(function(){
				jQuery(this).parents('ul').find('.active').removeClass('active');
				jQuery(this).parent('li').addClass('active');
				jQuery('div#multimediabar div.mm-panels').cycle('stop');
				var nextPanelset = '#'+jQuery(this).attr('class');

				jQuery(this).parents('ul').removeClass();
				jQuery(this).parents('ul').removeClass();

				jQuery(this).parents('ul').addClass("mm-links");
				jQuery(this).parents('ul').addClass(jQuery(this).attr('class'));

				jQuery('.mm-panelset:not('+nextPanelset+')').fadeOut('normal', function(){
					jQuery(nextPanelset).fadeIn(
						'normal',
						function(){
						jQuery(nextPanelset+' div.mm-panels').cycle('resume');
					});
				});
				this.blur();
				return false;
			});
		},

		/**
		 * Enable a full-sized slideshow.  Called inline on gallery-detail pages.  Assumes the slideshow is in 'div#big-slideshow'.
		 * Note: this function will look for a GET param called "image" and, if present, use that frame as a starting slide.
		 * @param {Number} [index=0] zero-based index of the first slide to be displayed.  Will override the "image" GET param.
		 */
		enable_big_slideshow: function (index) {
			if (typeof index == 'undefined') {
				// if there is no index, look for an "image" GET param
				if (Sacbee.GET["image"]) {
					index = Sacbee.GET["image"] - 1;
				} else {
					index = 0;
				}
			}

			// Create a caption block outside of the cycled block and fill it with the first caption.
			jQuery('<div/>').addClass('captions').appendTo('#big-slideshow div.slides');

			jQuery('div#big-slideshow div.slides ul').cycle(
				{
					fx: 'scrollHorz',
					speed: 200,
					timeout: 0,
					startingSlide: index,
					cleartypeNoBg: true,
					prev: 'div#big-slideshow span.prev a',
					next: 'div#big-slideshow span.next a',
					pager: 'div#big-slideshow span.indicator',
					pagerAnchorBuilder:function(idx, slide) {
						return '<a href="#"><img src="http://media.sacbee.com/static/img/blank.gif" alt=""><\/a>';
					},
					after: function (currSlideElement, nextSlideElement) {
						// Update the counter
						//jQuery('.bigIndex').html(this.nodeIndex);	// Doesn't work in webkit
						jQuery('.bigIndex').html(jQuery(this).prevAll().length + 1);

						jQuery('#big-slideshow div.slides ul').animate(
							{
								height: parseInt(jQuery('img', this).attr('height') + 1) + 'px'
							},
							"fast");
						jQuery('#big-slideshow div.captions').hide().html(jQuery('div.gallerycaption', this).html()).show();

						// If we can, reload the ads and update the stats
						if (jQuery('#railads').length) {
							// Update Omniture
							if (typeof(s) != "undefined")	// "s" is for "stupid" (needed because s isn't set on preview)
								mistats_resend();

							// Update Google Analytics
							try {
								var pageTracker = _gat._getTracker("UA-2767905-6");
								pageTracker._setDomainName(".sacbee.com");
								pageTracker._trackPageview();
							} catch(err) {}

							jQuery('#railads').attr('src', jQuery('#railads').attr('src'));
						}

						// Enable Meebo sharing on the new image
						//if (typeof(Meebo) != "undefined")
						//	Meebo('makeSharable', {element: jQuery('img', this)[0]});
					}
				}
			);

			jQuery('#big-slideshow-loader').hide();
			jQuery('#big-slideshow div.gallerycaption').hide();

			// Here's a trick: if there's only one image then cycle() will exit and it won't be displayed
			if (jQuery('div#big-slideshow div.slides ul li').length == 1) {
				jQuery('div#big-slideshow div.slides ul li').show();
			}
		},

		/**
		 * Mobile (iDevice and Android) detection.
		 */
		MobileDetect: {
			getBrowser: function () {
				var browserType;
				var browsers = [ 'iPhone', 'iPad', 'iPod', 'Android' ];

				for (x = 0; x < browsers.length; x++) {
					if (navigator.userAgent.indexOf(browsers[x]) !== -1) {
						browserType = browsers[x];
						break;
					}
				}

				return browserType;
			},

			showAppLink: function (ele) {
				var browser = Sacbee.MobileDetect.getBrowser();
				var blurb = 'Click here for the free Sacbee iPhone App!';
				var logoLink = 'http://www.sacbee.com/static/images/scoopy.png';
				var storeLink;

				if (browser && !$.cookie('hide_mobileteaser')) {
					switch(browser)
					{
						case 'iPhone':
							storeLink = 'http://itunes.apple.com/us/app/the-sacramento-bee/id382902278';
							break;
						case 'iPod':
							blurb = 'Click here for the free Sacbee iPod App!';
							storeLink = 'http://itunes.apple.com/us/app/the-sacramento-bee/id382902278';
							break;
						case 'iPad':
							blurb = 'Click here for the Sacbee iPad App!';
							storeLink = 'http://itunes.apple.com/us/app/the-sacramento-bee-for-ipad/id446757012';
							break;
						case 'Android':
							blurb = 'Click here for the free Sacbee Android App!';
							storeLink = 'https://market.android.com/details?id=com.ap.sacramento';
							break;
					}

					$(ele).append(
						$('<img/>').attr('src', 'http://media.sacbee.com/static/img/button-search-close.gif').addClass('closebox').click(function () {
							Sacbee.MobileDetect.trackEvent(this, 'MobileTeaser - Hide');
							Sacbee.MobileDetect.hideAppLink(ele);
						})
					).append(
						$('<div/>').html(blurb).click(function () {
							Sacbee.MobileDetect.trackEvent(this, browser);
							window.location = storeLink;
						})
					).show();
				}
			},

			hideAppLink: function (ele) {
				$.cookie('hide_mobileteaser', 'yes', { expires: 30, path: '/' });
				$(ele).hide();
			},

			trackEvent: function (element, event) {
				if (('s' in window) && ('tl' in window.s)) {
					window.s.tl(element, 'o', 'MobileTeaser-' + event);
				}
			}
		}
	};
}();

