/**
 * @fileOverview Sacramento Connect Toolbar v 1.0
 * @author <a href="mailto:kgill@sacbee.com">Kamal Gill</a>
 * @author <a href="mailto:mamatteo@sacbee.com">Marc Matteo</a>
 * @author Tyler Stobbe
 */


/** @namespace Namespace for the Sac Connect code. */
if (typeof SCTOOLBAR === 'undefined') {
	var SCTOOLBAR = { };
}


(function() {
	SCTOOLBAR.DEV_MODE = /\/test\/toolbar\-test\.html$/.test(window.location.pathname);
	/* Echo SC toolbar version number to console */
	var toolbar_version = '20110705';
	if (typeof console !== 'undefined') { console.log('SC Toolbar Version: ' + toolbar_version); }

	/* Convenience variable */
	var doc = document,
		loc = doc.location;

	/** Toolbar enabled? (KILL SWITCH) */
	var TOOLBAR_ENABLED = true;

	/* Are we on third-party site? */
	var host = loc.host,
		THIRD_PARTY_SITE = (host.match('sacbee') || host.match('sacwineregion') || host.match('sacramentoconnect') || host.match('scoopytube')) ? false : true;

	/* Get page title */
	var title_tag = doc.getElementsByTagName('title')[0],
		PAGE_TITLE = title_tag.innerText || title_tag.textContent;

	/* Set the affiliate ID */
	var AFFILIATE_ID = 'sacbee:';
	AFFILIATE_ID += (SCTOOLBAR.DEV_MODE) ? 'sacbee' : host.replace('www.','').split('.').slice(0,-1).join('.').replace(/\W/gi,'_');
	if (typeof console !== 'undefined') { console.log('Affiliate ID: ' + AFFILIATE_ID); }

	/* Reference to YUI3 seed and loader file */
	var yui3_loader = 'http://yui.yahooapis.com/combo?3.3.0/build/yui/yui-min.js&3.3.0/build/loader/loader-min.js';


	/**
	 * Template substitution (source: Douglas Crockford)
	 *
	 * */
	if (typeof String.prototype.supplant !== 'function') {
		String.prototype.supplant = function (o) {
			return this.replace(/{([^{}]*)}/g, function (a, b) {
				var r = o[b];
				return typeof r === 'string' ? r : a;
			});
		};
	}


	/**
	 *
	 * @param {String} url URL String to parse
	 * @param {Boolean} strictMode If true, use strict mode
	 * @returns {Object} Object of key/value pairs (see [key] array for keys)
	 * @see http://blog.stevenlevithan.com/archives/parseuri
	 *
	 */
	var parseURL = function (url, strictMode) {
		var options = {
			strictMode: strictMode,
			key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
			q: {
				name:   "queryKey",
				parser: /(?:^|&)([^&=]*)=?([^&]*)/g
			},
			parser: {
				strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
				loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
			}
		};
		var o   = options,
			m   = o.parser[o.strictMode ? "strict" : "loose"].exec(url),
			uri = {},
			i   = 14;

		while (i--) uri[o.key[i]] = m[i] || "";

		uri[o.q.name] = {};
		uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
			if ($1) uri[o.q.name][$1] = $2;
		});

		return uri;
	};


	/**
	 * 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
	 *
	 * */
	var addScriptNode = function(url, cbfunc) {
		var domscript = doc.createElement('script');
		domscript.setAttribute('src', url);
		domscript.setAttribute('type', 'text/javascript');
		domscript.onloadDone = false;
		domscript.onload = function() {
			domscript.onloadDone = true;
			cbfunc();
		};
		domscript.onreadystatechange = function() {
			if (( "loaded" === domscript.readyState || "complete" === domscript.readyState ) && ! domscript.onloadDone) {
				domscript.onloadDone = true;
				cbfunc();
			}
		};
		doc.getElementsByTagName('body')[0].appendChild(domscript);
	};


	/*
	 * Use iframed-JS approach to load JS code in an async, non-blocking fashion
	 * First presented by Meebo at Velocity 2010
	 * See http://www.youtube.com/watch?v=b7SUFLFu3HI (minute 9:00 - 10:00)
	 * @param {string} cbfunc reference to JS function, provided as a string
	 * @param {string} frameId id attribute value of iframe element
	 *
	 * */
	var addEyeFramedJSNode = function(cbfunc, frameId) {
		// Add iframe node
		var iframe = doc.createElement('iframe');
		iframe.setAttribute('id', frameId);
		iframe.setAttribute('name', frameId);
		var styleText = 'width: 0; height: 0; position: absolute; left: -999em;';
		iframe.setAttribute('style', styleText);
		iframe.style.cssText = styleText; /* IE */
		doc.body.appendChild(iframe);

		// Add body tag to iframe
		var d = iframe.contentWindow.document;
		d.open().write('<body onload="window.parent.' + cbfunc + '"></body>');
		d.close();
	};


	/*
	 *  iFrame markup convenience function
	 *
	 * */
	var insertEyeFrame = function(parentId, frameId, bodyContent) {
		var parentNode = doc.getElementById(parentId);
		var inode = doc.createElement('iframe');
		inode.setAttribute('id', frameId);
		inode.style.width = '100%';
		inode.style.height = '97%';
		inode.setAttribute('frameBorder', '0');
		parentNode.appendChild(inode);
		var d = inode.contentWindow.document;
		d.open().write('<body style="font-size: 78%; margin: 0; padding: 0;">' + bodyContent + '</body>');
		d.close();
	};


	/**
	 * Meebo init code
	 *
	 * */
	var initMeebo = function() {
		/* Initialize Meebo toolbar */
		window.Meebo||function(b){function p(){return["<",i,' onload="var d=',g,";d.getElementsByTagName('head')[0].",
		j,"(d.",h,"('script')).",k,"='//",b.stage?"stage-":"","cim.meebo.com/cim?iv=",a.v,"&",q,"=",b[q],b[l]?
		"&"+l+"="+b[l]:"",b[e]?"&"+e+"="+b[e]:"","'\"></",i,">"].join("")}var f=window,a=f.Meebo=f.Meebo||function(){(a._=
		a._||[]).push(arguments)},d=document,i="body",m=d[i],r;if(!m){r=arguments.callee;return setTimeout(function(){r(b)},
		100)}a.$={0:+new Date};a.T=function(u){a.$[u]=new Date-a.$[0]};a.v=4;var j="appendChild",h="createElement",
		k="src",l="lang",q="network",e="domain",n=d[h]("div"),v=n[j](d[h]("m")),c=d[h]("iframe"),g="document",
		o,s=function(){a.T("load");a("load")};f.addEventListener?f.addEventListener("load",s,false):f.attachEvent("onload",
		s);n.style.display="none";m.insertBefore(n,m.firstChild).id="meebo";c.frameBorder="0";c.id="meebo-iframe";
		c.allowTransparency="true";v[j](c);try{c.contentWindow[g].open()}catch(w){b[e]=d[e];o="javascript:var d="+
		g+".open();d.domain='"+d.domain+"';";c[k]=o+"void(0);"}try{var t=c.contentWindow[g];t.write(p());t.close()}catch(x){c[k]=
		o+'d.write("'+p().replace(/"/g,'\\"')+'");d.close();'}a.T(1)}
		({network:AFFILIATE_ID,stage:false});
		Meebo('domReady');
	};


	/**
	 * Get site category and mixer id from categories JSON file
	 */
	var getSiteCategory = function() {
		var key = null;
		SCTOOLBAR.partner_site = null;
		SCTOOLBAR.site_category = null;
		SCTOOLBAR.mixer_id = null;
		if (typeof SacConnect !== 'undefined' && typeof SacConnect.SITE_CATEGORIES !== 'undefined') {
			// Set category based on host name for third-party sites
			if (SacConnect.SITE_CATEGORIES[AFFILIATE_ID]) {
				key = SacConnect.SITE_CATEGORIES[AFFILIATE_ID];
				SCTOOLBAR.partner_site =  key;
				SCTOOLBAR.site_category = key.category;
				SCTOOLBAR.mixer_id = key.mixer_id;
			}
			// Set category based on section name for sacbee.com sites
			if (!THIRD_PARTY_SITE) {
				if (typeof Sacbee !== 'undefined' && Sacbee.section_name) {
					if (SacConnect.SITE_CATEGORIES[Sacbee.section_name.replace(/\s+/g, '')]) {
						key = SacConnect.SITE_CATEGORIES[Sacbee.section_name.replace(/\s+/g, '')];
						// Use section_name instead of affiliate id to get category
						// Remove spaces in section_name to get appropriate key
						SCTOOLBAR.site_category = key.category;
						SCTOOLBAR.mixer_id = key.mixer_id;
					}
				}
			}
		}
	};


	/**
	 * Targeted Ad code (partnerTakeover Value)
	 *
	 * */
	var setTargetedAds = function() {
		var section = null;
		/* Site-specific (and section-specific for sacbee.com) Ad targeting (Partner Takeover) code */
		section = loc.pathname.split('/')[1] || "home";
		/* Target by section only on sacbee.com */
		if (!THIRD_PARTY_SITE) {  // sacbee sites
			/* Use Yahoo APT taxonomy when available */
			if (typeof miyahoo !== 'undefined' && miyahoo.tax) {
				section = miyahoo.tax;
			}
		} else { // third-party site
			/* Get site category from sites/categories object */
			if (SCTOOLBAR.site_category) {
				section = SCTOOLBAR.site_category;
			} else {
				section = 'affiliate'; // fallback
			}
		}
		// Log values to console
		if (typeof console !== 'undefined') {
			console.log("partnerTakeover value: " + section);
			console.log("Site Category: " + SCTOOLBAR.site_category);
			console.log("Site Mixer ID: " + SCTOOLBAR.mixer_id);
		}
		// Set partnerTakeover value
		Meebo.partnerTakeover = {section: section};
	};


	/**
	 * Custom Share Page button
	 *
	 * */
	var addSharePageButton = function() {
		/* Add our custom button */
		Meebo('addButton', {
			id: "SharePage",
			type: "action",
			icon: "http://media.sacbee.com/static/sacconnect/images/share-icon.png",
			label: "Share",
			onClick: function(){ Meebo('share', { url: doc.location.href, title: PAGE_TITLE}); }
		});
	};


	/**
	 * Lingospot Related Articles ("Explore") button.
	 * @param {Object} Y YUI instance passed in from YUI().use(...) callback
	 *
	 * */
	var addRelatedArticles = function(Y) {
		/* Set API variables for Lingospot */
		var site_mixer = '';
		if (SCTOOLBAR.mixer_id) {
			site_mixer = SCTOOLBAR.mixer_id;
		}

		var lingo_page_url, lingo_relitems_api_url, lingo_link_hash_tag, lingo_url_params, lingo_json_url;
		lingo_page_url = encodeURIComponent(doc.URL.replace(loc.search, '').replace(loc.hash, ''));
		lingo_relitems_api_url = "http://partner.lingospot.com/data/json/1/";
		lingo_link_hash_tag = THIRD_PARTY_SITE ? "#storylink=sctoolbarext" : "#storylink=sctoolbarint";
		lingo_url_params = "?api_key=OSOPGRQX&content_key=" + site_mixer + "&url=" + lingo_page_url + "&format=json&callback={callback}!";
		lingo_json_url = lingo_relitems_api_url + lingo_url_params;

		/* Issue JSONP request for related articles */
		if (site_mixer && site_mixer !== 'NULL') {
			Y.jsonp(lingo_json_url, function(oData) {
				if (typeof oData !== 'undefined') {
					var content = null, rssresults = null;
					var related_elem_id = 'sc-relarticles';
					if (typeof oData.content !== 'undefined') {
						content = oData.content;
					}
					if (content) {
						if (typeof content.page !== 'undefined' && content.page.rssresult) {
							rssresults = content.page.rssresult;
						} else if (typeof content.content !== 'undefined' && (typeof content.content.page != 'undefined') && content.content.page.rssresult) {
							rssresults = content.content.page.rssresult;
						}
					}
					/* Add "Stories" button if related items */
					if (rssresults && rssresults.length > 0) {
						var url, url_map, host_name, markup, template, img_template, results, results_node;
						var description = '';
						results = rssresults.slice(0, 6); // Limit to 6 items
						results_node = doc.createElement('ul');
						results_node.setAttribute('id', related_elem_id);
						results_node.className = 'sc-relitems';
						results_node.setAttribute('style', 'display: none;');
						results_node.style.cssText = 'display: none;'; // IE
						/* IE */
						markup = "";
						template = '<li><a href="{url}{hashtag}" class="noimg" title="{description}">{title}<span>- &nbsp;<em>{reltime}</em></span> <span>{description}...</span> <span class="discreet">[{hostname}]</span></a></li>';
						Y.Array.each(results, function(result) {
							url = result['url'].replace(/#[^#]*/, '');
							url_map = parseURL(url);
							host_name = url_map['host'];
							if (result.sum) {
								description = result.sum.split(' ').slice(0, 12).join(' ');
							}
							var data = {'url': url, 'hashtag': lingo_link_hash_tag, 'title': result.title, 'hostname': host_name, 'description': description};
							if (result.ts) {
								data['reltime'] = Y.toRelativeTime(new Date(result.ts));
							}
							if (result.img) {
								img_template = '<li><a href="{url}{hashtag}" title="{description}"><img src="{img}" />{title}<span>- &nbsp;<em>{reltime}</em></span> <span>{description}...</span> <span>[{hostname}]</span></a></li>';
								data['img'] = result.img;
								markup += img_template.supplant(data);
							} else {
								markup += template.supplant(data);
							}
						});
						markup += '<p class="scblurb">More stories of similar interest</p>';
						markup += '<p class="screlpby">Powered by <a href="http://www.lingospot.com/">Lingospot</a></p>';
						results_node.innerHTML = markup;
						doc.getElementsByTagName('body')[0].appendChild(results_node);

						/* Add Stories button */
						Meebo('addButton', {
							id: "relarticles",
							type: "widget",
							icon: "http://media.sacbee.com/static/sacconnect/images/related_stories_icon.png",
							label: "Explore",
							width: 320, height: 320,
							element: related_elem_id
						});
					}
				}
			});
		}
	};


	/**
	 * Make all elements with the given classname sharable via Meebo.
	 * @param {String} class_name Class name of elements to be made sharable.
	 * @param {Object} Y YUI instance passed in from YUI().use(...) callback
	 *
	 * Note: requires Meebo to be initialized.
	 *
	 * */
	var makeSharable = function (class_name, Y) {
		var sharable_tags = Y.all('.' + class_name)._nodes;
		for (var x=0, count=sharable_tags.length; x < count; x++) {
			var sharable_tag = sharable_tags[x];
			if (sharable_tag.nodeName == "IMG") {
				Meebo('makeSharable', {
					element: sharable_tag,
					title: 'A photo shared from ' + doc.domain
				});
			} else if (sharable_tag.nodeName == "A" || sharable_tag.nodeName == "H1") {
				Meebo('makeSharable', {
					tooltipPosition: 'top',
					element: sharable_tag,
					title: sharable_tag.innerHTML + ' - from ' + doc.domain,
					shadow: 'none'
				});
			} else {
				// fake it with anything that falls through...
				Meebo('makeSharable', {
					element: sharable_tag,
					title: 'Shared from ' + doc.domain
				});
			}
		}
	};


	/**
	 * Toolbar search button
	 */
//	var addSearchBox = function() {
//		/* Build search form and results wrapper */
//		var scsearchwrapper = doc.createElement('div');
//		var scsearchwrapper_id = "scsearchwrapper";
//		scsearchwrapper.setAttribute('id', scsearchwrapper_id);
//		scsearchwrapper.setAttribute('style', 'display: none;');
//		scsearchwrapper.style.cssText = 'display: none;'; /* IE */
//
//		/* Build search form */
//		var form_html = '<form id="scsearchform" action="http://sacramentoconnect.sacbee.com/">';
//		form_html += '<label for="scsearchterm">Sacramento Connect Search</label>';
//		form_html += '<input type="text" name="s" id="scsearchterm"/>';
//		form_html += '<input type="submit" id="scsearchgo" value="Go" /></form>';
//		scsearchwrapper.innerHTML = form_html;
//
//		/* Echo search message */
//		var message_node = doc.createElement('div');
//		message_node.id = "scsearchmsg";
//		var results_msg = '<p>Search the Sacramento Connect network,</p><p>including regional ';
//		results_msg += '<a href="http://sacramentoconnect.sacbee.com/partners-alphabetical/" target="_blank">network partners</a>.</p>';
//		message_node.innerHTML = results_msg;
//		scsearchwrapper.appendChild(message_node);
//		/* Insert wrapper into DOM */
//		doc.getElementsByTagName('body')[0].appendChild(scsearchwrapper);
//
//		/* Add Search button to toolbar */
//		Meebo('addButton', {
//			id: "scsearchbutton",
//			type: "widget",
//			icon: "http://media.sacbee.com/static/sacconnect/images/scsearch.png",
//			label: "Search",
//			width: 280,
//			height: 120,
//			element: scsearchwrapper_id,
//			onShow: function(widget, element){
//				doc.getElementById('scsearchterm').focus();
//			}
//		});
//	};


	/**
	 * Weather button
	 * API provider: Google (JSONP-enabled via YQL)
	 * See: http://blog.programmableweb.com/2010/02/08/googles-secret-weather-api/
	 */
	var addWeatherButton = function(Y) {
		// Create placeholder for weather forecast
		var weatherbox, weatherbox_id;
		weatherbox = doc.createElement('div');
		weatherbox_id = 'scweather';
		weatherbox.setAttribute('id', weatherbox_id);
		weatherbox.setAttribute('style', 'display: none;');
		weatherbox.style.cssText = 'display: none;'; /* IE */

		// Get weather data via YQL
		var cache, cache_key, items, yql_query, results, weather, forecast, conditions, curtemp, icon, buttonicon, label, show_weather_info, updated;

		// Weather info convenience function
		show_weather_info = function(results) {
			weather = results.current_observation;
			curtemp = weather.temp_f;
			icon = weather.icons.icon_set[2].icon_url;
			buttonicon = weather.icons.icon_set[9].icon_url;

			// Current conditions
			var curcond_template, curcond_markup, forecast_markup;
			curcond_template = [
				'<div class="wloc"><a href="http://www.sacbee.com/weather" title="View weather news and complete forecast">Sacramento Weather</a></div>',
				'<table class="wcondition"><tr>',
				'<td><img src="{curicon}" align="left" title="{condition}"/><span class="curtemp">{curtemp}&deg;</span>F</td>',
				'<td class="conditions"><b>{condition}</b><br />Wind: {wind}<br />Humidity: {humidity}</td>',
				'</tr></table>'
			].join('');
			curcond_markup = Y.Lang.sub(curcond_template, {
				'curicon': icon,
				'curtemp': curtemp,
				'condition': weather.weather,
				'wind': '{speed} mph {dir}'.supplant({'speed': weather.wind_mph, 'dir': weather.wind_dir}),
				'humidity': weather.relative_humidity
			});
			forecast_markup = '<iframe src="http://www.wunderground.com/auto/sacbee/CA/Sacramento.html?threeday=1&width=316" width="316" height="116" frameborder="0" scrolling="no" style="background-color: #f6f6f6;"></iframe>';
			forecast_markup += '<div class="wupdated">{updated}</div>'.supplant({
				'updated': weather.observation_time
			});

			// Inject HTML into weather box container
			weatherbox.innerHTML = curcond_markup + forecast_markup;

			// Generate button with current temp
			label = '{temp} F Weather'.supplant({'temp': curtemp});

			// Insert wrapper into DOM
			doc.getElementsByTagName('body')[0].appendChild(weatherbox);

			// Add Weather button to toolbar
			Meebo('addButton', {
				id: 'scweatherbutton',
				type: 'widget',
				icon: buttonicon,
				label: label,
				width: 330,
				height: 280,
				element: weatherbox_id
			});
		};

		// Use HTML5 localStorage cache via YUI3 'cache' utility, with expiration of 300 seconds
		cache = new Y.CacheOffline({'expires': 300 * 1000});
		cache_key = 'scweather_cache';
		items = cache.retrieve(cache_key); // Get items from localStorage cache

		// Get weather from Weather Underground API (captured every 15 min to static file) via YQL if localStorage cache is empty
		if (!items) {
			yql_query = 'select observation_time, weather, temp_f, relative_humidity, wind_mph, wind_dir, icons from xml where url="http://www.wunderground.com/auto/sacbeeXML/geo/WXCurrentObXML/index.xml?query=Sacramento,%20CA"';
			Y.YQL(yql_query, function(oData) {
				if (oData) {
					results = oData.query.results || null;
					if (results) {
						cache.add(cache_key, results);
						show_weather_info(results);
					}
				}
			}, {'env': 'foo'});
		} else {
			// YUI3 stores cached data in cached item's .response object
			show_weather_info(items.response);
		}
	};


	/**
	 * Latest posts button
	 * Repurposes code from the multi-tab RSS widget
	 * See https://github.com/sacbee/Sacbee-misc/blob/master/SacbeeWidgets/yui3/yui3-rsswidget.js
	 */
	var addLatestPostsButton = function(Y) {
		// Create placeholder for latest posts
		var latestposts, latestposts_id, category='', categoryfeed='', rsswidget, siteprefix, defaultfeeds;
		latestposts = doc.createElement('div');
		latestposts_id = 'sclatestposts';
		latestposts.setAttribute('id', latestposts_id);
		latestposts.setAttribute('style', 'display: none;');
		latestposts.style.cssText = 'display: none;'; /* IE */

		// Get category from external site
		if (SCTOOLBAR.site_category) {
			category = SCTOOLBAR.site_category;
		}

		// Add category feed when category is available
		if (category) {
			categoryfeed = '{category}::http://sacramentoconnect.sacbee.com/%3Ffeed%3Dsc%26category_name%3D{category}||'.supplant({'category': category});
		}

		// Set default feed URLs
		defaultfeeds = [
				'just in::http://sacramentoconnect.sacbee.com/feed/sc/',
				'editor picks::http://sacramentoconnect.sacbee.com/category/featured/feed/sc/',
				'sacbee::http://www.sacbee.com/topstories/index.rss'
		].join('||');

		// Build RSS widget script tag
		siteprefix = (SCTOOLBAR.DEV_MODE) ? '../src/yui3-rsswidget.js' : 'http://media.sacbee.com/static/sacconnect/widgets/yui3-rsswidget-min.js';
		rsswidget = '<script type="text/javascript" src="{siteprefix}?feeds={categoryfeed}{defaultfeeds}&titlelink={titlelink}"></script>'.supplant({
			'siteprefix': siteprefix,
			'categoryfeed': categoryfeed,
			'defaultfeeds': defaultfeeds,
			'titlelink': 'http://sacramentoconnect.sacbee.com'
		});

		// Insert wrapper into DOM
		doc.getElementsByTagName('body')[0].appendChild(latestposts);

		// Insert RSS widget into wrapper
		insertEyeFrame(latestposts_id, 'sclatestposts-frame', rsswidget);

		// Add Latest posts button to toolbar
		Meebo('addButton', {
			id: "sclatestpostsbutton",
			type: "widget",
			icon: 'http://media.sacbee.com/sacconnect/images/latestposts.png',
			label: 'Latest Posts',
			width: 340,
			height: 620,
			element: latestposts_id
		});
	};


	/**
	 * Custom Menu button
	 */
	var addCustomMenuButton = function() {
		var scicon, scprefix, items, category;
		scicon = 'http://media.sacbee.com/static/sacconnect/images/sclogo16px.png';
		scprefix = 'http://sacramentoconnect.sacbee.com/';
		items= [
			{value: scprefix, text: "sacramento connect", icon: scicon},
			{value: scprefix + "category/california-local/", text: "local california"},
			{value: scprefix + "category/interests/", text: "interests"},
			{value: scprefix + "category/news/", text: "community news"},
			{value: scprefix + "category/opinion/", text: "opinion"},
			{value: scprefix + "partners-alphabetical/", text: "partners"},
			{value: scprefix + "about/", text: "about"},
			{value: "http://www.sacbee.com", text: "The Sacramento Bee", icon: "http://media.sacbee.com/static/images/scoopy23trans.png"}
		];

		if (SCTOOLBAR.site_category) {
			category = SCTOOLBAR.site_category;
			items.splice(1, 0, {'value': scprefix + '?category_name=' + category, 'text': category});
		}

		Meebo('addButton', {
			id: "scmenu",
			type: "menu",
			icon: scicon,
			items: items,
			label: "SacConnect",
			onSelect: function(value){
				window.open(value);
			}
		});
	};


	/**
	 * Add multi-domain version of Google Analytics
	 * @param {Object} Y YUI instance passed in from YUI().use(...) callback
	 */
	/*
	var setGoogleAnalyticsMultiDomain = function(Y) {
		Y.Get.script("http://www.google-analytics.com/ga.js", {
			onSuccess: function () {
				var script_str = [
					'<script type="text/javascript">',
					'  try {',
					'	var sc_pageTracker = _gat._getTracker("UA-2767905-7");',
					'	sc_pageTracker._setDomainName("none");',
					'	sc_pageTracker._setAllowLinker(true);',
					'	sc_pageTracker._trackPageview();',
					'  } catch(e) { }',
					'</script>'
				].join('\n');
				Y.one(doc.body).append(script_str);
			}
		});
	};
	*/

	/**
	 * Set up the Dart tag.
	 */
	var setDartAdCall = function(Y) {
		var dart_script_url = "";

		if (THIRD_PARTY_SITE) {
			var partner = "partner";

			//if (SCTOOLBAR.site_category) {
			//  partner = SCTOOLBAR.site_category;
			//}

			dart_script_url = 'http://ad.doubleclick.net/pfadx/mi.sac00/Online/Events;dcove=d;partner=' + partner + ';pl=vendor;!c=vendor;atf=n;pos=1;sz=100x60;tile=1;dcmt=text/html;ord=0123456789?';
		} else {
			var tax = "_HomePage||||";
			var lvl6 = "SacConnect";
			var pl = "sectfront";

			if (typeof mistats !== 'undefined') {
				if (mistats.taxonomy && mistats.taxonomy !== "BadTaxonomy||||") {
					tax = mistats.taxonomy;
				} else if (typeof miblogs_taxonomy !== 'undefined') {
					tax = miblogs_taxonomy;
				}
				if (mistats.pagename) {
					lvl6 = mistats.pagename.replace(/^(Homepage|Section): /, "");
					if (mistats.pagename.indexOf('Homepage') === 0) {
						pl = "homepage";
					}
				}
			}

			dart_script_url = 'http://ad.doubleclick.net/pfadx/mi.sac00/' + tax.replace(/\|/g,"/").replace(/\/+$/,"") + ';dcove=d;lvl6=' + lvl6 + ';pl=' + pl + ';!c=meebo;atf=n;pos=1;sz=100x60;tile=1;dcmt=text/html;ord=0123456789?';
		}

		Y.Get.script(dart_script_url);
	};

	/* Load YUI3 seed/loader file and SC toolbar if enabled */
	if (TOOLBAR_ENABLED) {
		addScriptNode(yui3_loader, function() {
			/* Get YUI3 modules */
			YUI({gallery: 'gallery-2011.01.03-18-30'}).use('node', 'get', 'jsonp', 'yql', 'cache', 'datatype-date', 'gallery-torelativetime', function(Y) {

				/* JS URL of sites/categories mapping (Script src contains JS Object Literal)*/
				var site_categories_url = "http://media.sacbee.com/static/sacconnect/site_categories.js";
				var errors = [ ];

				/* Shows the toolbar. */
				SCTOOLBAR.showToolbar = function(categories_loaded) {
					/* Get category from categories JSON file */
					try {
						getSiteCategory();
					} catch(e) {
						errors.push('Error getting site category');
					}

					/* Append CSS into document head node */
					try {
						Y.Get.css("http://media.sacbee.com/static/sacconnect/toolbar-min.css");
					} catch(e) {
						errors.push('Error loading SC toolbar CSS.');
					}

					/* Add Google Analytics code for click tracking */
					/*
					try {
						setGoogleAnalyticsMultiDomain(Y);
					} catch(e) {
						errors.push('Error setting Google Analytics for SC toolbar.');
					}
					*/

					/* Initialize Meebo toolbar */
					try {
						initMeebo();
					} catch(e) {
						errors.push('Error initializing Meebo.');
						return false; // Halt execution if Meebo object isn't initialized
					}

					/* Add the DART call */
					if (host.match('sactraffic') || host.match('healthycal')) {
						Meebo.disableAds = true;
					} else {
						try {
							setDartAdCall(Y);
						} catch(e) {
							errors.push('Error setting the Dart call for SC toolbar.');
						}
					}

					/* Disable existing share page button */
					try {
						Meebo.disableSharePageButton=true;
					} catch(e) {
						errors.push('Error disabling default share button.');
					}

					/* Set default thumbnail */
					try {
						Meebo('setDefaultThumbnail', {thumbnail: 'http://media.sacbee.com/static/sacconnect/images/shared_icon.png', width: 50, height: 50});
					} catch(e) {
						errors.push('Error setting default share thumbnail.');
					}


					/* Add custom buttons after toolbar code is initialized */
					Meebo(function() {
						/* Add custom share page button */
						try {
							addSharePageButton();
						} catch(e) {
							errors.push('Error adding custom share page button.');
						}

						/* Add custom menu button */
						try {
							addCustomMenuButton();
						} catch(e) {
							errors.push('Error adding custom menu button.');
						}

						/* Add Latest Posts button */
						try {
							addLatestPostsButton(Y);
						} catch(e) {
							errors.push('Error adding Latests Posts button.');
						}

						/* Add "Search" button */
/*
						try {
							addSearchBox();
						} catch(e) {
							errors.push('Error adding Search button.');
						}
*/

						/* Add Sac Weather button */
						try {
							addWeatherButton(Y);
						} catch(e) {
							errors.push('Error adding Weather button.');
						}

						/* Set targeted ads (partnerTakeover value) only when categories are loaded */
						try {
							if (categories_loaded) { setTargetedAds();}
						} catch(e) {
							errors.push('Error setting targeted ad values.');
						}

						/* Make elements with the "sc_sharable" class sharable */
						try {
							makeSharable("sc_sharable", Y);
						} catch(e) {
							errors.push('Error making photos/headlines shareable.');
						}

						/* Add related articles "Explore" button */
						try {
							addRelatedArticles(Y);
						} catch(e) {
							errors.push('Error adding related stories.');
						}
					});

					/* Log errors */
					if (errors.length > 0) {
						if (typeof console !== 'undefined') {
							for (var i=0, count = errors.length; i < count; i++) {
								console.log("SC Toolbar Log: " + errors[i]);
							}
						}
					}
				};

				/**
				 * Initialize toolbar components after fetching site categories JS file.
				 */
				Y.Get.script(site_categories_url, {
					timeout: 6 * 1000, // Set timeout to 6 seconds
					onSuccess: function () {
						addEyeFramedJSNode('SCTOOLBAR.showToolbar(true)', 'sciframe-sctoolbar');
					},
					onFailure: function () {
						addEyeFramedJSNode('SCTOOLBAR.showToolbar(false)', 'sciframe-sctoolbar');
					},
					onTimeout: function () {
						addEyeFramedJSNode('SCTOOLBAR.showToolbar(false)', 'sciframe-sctoolbar');
					}
				})
			});
		});
	}
})();

