﻿var BTFC = {};
var _gaq = _gaq || [];

$(function () {
	BTFC.search.init();
	BTFC.categories.init();
	BTFC.newsEvents.init();
	BTFC.GoogleAnalytics({ enabled: BTFC.isProduction, accountId: 'UA-20267695-1' });
});

BTFC.search = {
	init: function () {
		$("#search-q").focus(this.onSearchFocus).blur(this.onSearchBlur);
	},
	onSearchFocus: function () {
		if (this.value === this.defaultValue) {
			this.value = '';
		}
	},
	onSearchBlur: function () {
		if (this.value === '') {
			this.value = this.defaultValue;
		}
	}
};

BTFC.newsEvents = {
	init: function () {
		$("#news-events-toggle li").click(this.onNewsEventsToggleClick);
		this.arrangeEvents();
	},
	arrangeEvents: function () {
		var $container = $("#calendar-items");
		if ($container.length) {

			// hide all items after the first, add a 'more' link
			// $container.find(">ul>li").each(function () {
			//     if ($(this).find("li").length > 1) {
			//         $(this).find("div").addClass("more").end().find("li:gt(0)").addClass("hide");
			//     }
			// });

			// split into two lists (expecting 6 >li). Ignore splash page
			if (!$("#splash-content").length) {
				$("<ul/>").append($container.find(">ul>li:gt(2)")).appendTo($container);
			}

			// listen for expand
			$(".more", $container).click(this.onMoreEventsClick);

		}
	},
	onMoreEventsClick: function () {
		$(this).removeClass("more").next("ul").find("li").removeClass("hide");
	},
	onNewsEventsToggleClick: function () {
		if (!$(this).hasClass("selected")) {
			// toggle buttons
			$(this).addClass("selected").siblings().removeClass("selected");
			// toggle divs
			$("#news-events .news-events-section.hide").removeClass("hide").siblings(".news-events-section").addClass("hide");
		}
	}
};

BTFC.categories = {
	$categoriesContainer: null,
	init: function () {
		this.$categoriesContainer = $(".categories");
		if (this.$categoriesContainer.length) {

			// wrap all category content in divs
			$("h2", this.$categoriesContainer).each(function () {
				$(this).nextUntil("h2", BTFC.categories.$categoriesContainer).wrapAll("<div class='category-section'></div>");
			});

			// wrap h2 content in a span, add a category content container after, and listen for h2 click events
			$("h2", this.$categoriesContainer).wrapInner("<span />").click(this.showCategoryContent);

			// expand 1st category content ** removed at btfc request
			// $("h2:eq(0)", this.$categoriesContainer).click();
		}
	},
	hideCategoryContent: function () {
		$(".category-section", this.$categoriesContainer).hide("fast");
	},
	showCategoryContent: function () {
		BTFC.categories.hideCategoryContent();
		$(this).addClass("selected").siblings().removeClass("selected").end().next(".category-section").show("fast");
	}
};

BTFC.isProduction = (function () {
	return (/braintumour\.ca$/i).test(window.location.hostname);
}());


BTFC.GoogleAnalytics = function (options) {
	var settings = $.extend({
		enabled: true,

		// Google account ID e.g. UA-0000000-00
		accountId: null,

		// clickable elements to attach events to
		elements: ['a', 'area'],

		// collection of link types, each of which may be 
		// identified and click-handled using custom logic
		linkTypes: {
			outbound: {
				cssClass: 'outbound',
				identify: function (obj) {
					return !obj.href.match(/^mailto\:/) && (obj.hostname !== location.hostname);
				},
				onClick: function () {
					_gaq.push(['_trackEvent', 'OutboundLink', 'Click', $(this).attr('href')]);
				}
			},
			download: {
				cssClass: 'download',
				identify: function (obj) {
					var // download filetypes may be extended
							ext = ['pdf', 'doc'],
							pattern = (function () {
								var p = '';
								$.each(ext, function (index, value) {
									p += '\\.' + value + '|';
								});
								p = p.substring(0, p.length - 1);
								return '(' + p + ')$';
							}()),
							m = obj.href.match(new RegExp(pattern, 'i'));

					return (m && m.length >= 1);
				},
				onClick: function () {
					var url = $(this).attr("href"),
							ext = url.split('.').pop().toUpperCase();
					_gaq.push(['_trackEvent', 'Downloads', ext, url]);
				}
			}
		}
	}, options || {}),
		identifyElements = function () {
			$.each(settings.linkTypes, function (key, obj) {
				$.expr[':'][key] = obj.identify;
				markElements(obj.cssClass);
			});
		},
		markElements = function (className) {
			$.each(settings.elements, function (index, value) {
				$(value + ':' + className).addClass(className);
			});
		},
		attachHandlers = function () {
			$.each(settings.linkTypes, function (key, obj) {
				$.each(settings.elements, function (index, value) {
					$(value + ':' + key).click(obj.onClick);
				});
			});
		};

	identifyElements();

	if (settings.enabled === true) {
		if (!settings.accountId) {
			throw 'You must provide an account ID';
			return false;
		}
		attachHandlers();

		_gaq.push(['_setAccount', settings.accountId]);
		_gaq.push(['_trackPageview']);
		(function () {
			var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		} ());
	}
};


/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

/* Modified to support Opera */
function bookmarksite(title, url) {
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if (window.opera && window.print) { // opera
		var elem = document.createElement('a');
		elem.setAttribute('href', url);
		elem.setAttribute('title', title);
		elem.setAttribute('rel', 'sidebar');
		elem.click();
	}
	else if (document.all) { // ie
		window.external.AddFavorite(url, title);
	} 
}
