/*!
 * nutrition iQ JavaScript Core
 */

/**
 * nutrition iQ namespace
 */
var NIQ = {
	initialize: function () {
		// Allows for targeting CSS selectors for users with JavaScript enabled
		$('body').addClass('has_script');
		
		// Begin initializing page elements
		NIQ.Utils.BrowserCheck.initialize();
		NIQ.Analytics.initialize();
		NIQ.Contributors.initialize();
		NIQ.Filters.initialize();
		NIQ.StoreFinder.initialize();
		
		// Preload images
		NIQ.Utils.ImagePreloader.add('/content/components/corporate/img/backgrounds/overlay.png');
		NIQ.Utils.ImagePreloader.add('/content/components/corporate/img/bio/amy_campbell.jpg');
		NIQ.Utils.ImagePreloader.load();
	}
};

/**
 * nutrition iQ Analytics namespace
 */
NIQ.Analytics = {
	trackers: {},
	initialize: function () {
		// Build Google Analytics tracker
		this.buildTracker();
		
		// Build external links
		this.buildExternalLinks();
		
		// Build download links
		this.buildDownloadLinks();
		
		// Track single page view
		this.trackPageView();
	},
	buildTracker: function () {
		try {
			if(window.location.toString().match('dev.') || window.location.toString().match('qa.') || window.location.toString().match('local.')) {
				this.trackers.page = _gat._getTracker("UA-6945099-2");
			} else {
				this.trackers.page = _gat._getTracker("UA-6945099-1");
			}
		} catch(err) {}
	},
	buildExternalLinks: function () {
		var that = this;
		$('a.link-external', 'body').each(function () {
			$(this).attr('target', '_blank').click(function (e) {
				that.handleExternalLinks($(this).attr('href'));
			});
		});
	},
	buildDownloadLinks: function () {
		var that = this;
		$('a.link-download', 'body').click(function (e) {
			that.handleDownloadLinks($(this).attr('href'));
		});
	},
	handleExternalLinks: function (href) {
		var index = href.indexOf('://');
		if(index != -1) {
			href = href.substring(index + 3, href.length);
		}
		this.trackPageView('/outgoing/' + href);
	},
	handleDownloadLinks: function (href) {
		var index = href.indexOf('://');
		if(index != -1) {
			href = href.substring(index + 3, href.length);
		}
		this.trackPageView('/download' + href);
	},
	trackEvent: function (category, action) {
		this.trackers.page._trackEvent(category, action);
	},
	trackPageView: function (href) {
		if (href) {
			this.trackers.page._trackPageview(href);
		} else {
			this.trackers.page._trackPageview();
		}
	}
};

/**
 * nutrition iQ Contributors namespace
 */
NIQ.Contributors = {
	currentIndex: null,
	containers: {},
	windows: [],
	initialize: function () {
		// Define containers
		this.containers.main = $('#contributors').get(0);
		this.containers.list = $('#contributor-list').get(0);
		
		// Build modal windows
		this.buildWindows();
	},
	getWindows: function () {
		var that = this;
		var items = [];
		
		$('li .bio', this.containers.list).each(function (index) {
			items.push(new NIQ.Contributors.Bio(this, index));
		});
		
		return items;
	},
	buildWindows: function () {
		
		this.windows = this.getWindows();
		
		$(this.windows).each(function () {
			this.build();
		});
	},
	showWindow: function (index) {
		// Set new currentIndex
		this.currentIndex = index;
		
		var bio = this.windows[index];
		
		// Show window
		$(bio.dom).jqmShow();
		// Set maximum body height & create scrollbar
		var scroller = $('.body .scroller', bio.dom).get(0);
		if ($(scroller).height() > 400) {
			$(scroller).height(400);
			$(scroller).jScrollPane({
				showArrows: true,
				scrollbarWidth: 11
			});
		}
		if (NIQ.Utils.BrowserCheck.isIE === true && NIQ.Utils.BrowserCheck.version < 7) {
			$(bio.dom).css('margin-top', '-50px');
		} else {
			$(bio.dom).css('margin-top', -($(bio.dom).height()/2));
		}
	},
	hideWindow: function () {
		$(this.windows[this.currentIndex].dom).jqmHide();
	},
	nextWindow: function () {
		this.hideWindow();
		if (this.currentIndex + 1 !== this.windows.length) {
			this.showWindow(this.currentIndex + 1);
		} else {
			this.showWindow(0);
		}
	},
	prevWindow: function () {
		this.hideWindow();
		if (this.currentIndex - 1 !== -1) {
			this.showWindow(this.currentIndex - 1);
		} else {
			this.showWindow(this.windows.length - 1);
		}
	}
};

NIQ.Contributors.Bio = function (el, index) {
	if (arguments.length !== 2) {
		throw new Error('Expected an argument of one but recieved ' + arguments.length);
	}
	
	this.dom = el;
	this.index = index;
};

NIQ.Contributors.Bio.prototype = {
	build: function () {
		var that = this;
		
		// Add common HTML to all windows
		$(this.dom).html(
			'<div class="top"></div>' +
			'<div class="body">' +
			'	<h3 class="fir"><span>nutrition iQ Contributors</span></h3>' +
			'	<a href="#" class="close arrow-link">Close Window</a>' +
			'	<div class="hr"><hr /></div>' +
			$(this.dom).html() +
			'	<div class="hr"><hr /></div>' +
			'	<ul class="navigation">' +
			'		<li class="prev"><a href="#">&lt; Previous Bio</a></li>' +
			'		<li class="next"><a href="#">Next Bio &gt;</a></li>' +
			'	</ul>' +
			'</div>' +
			'<div class="bottom"></div>'
		);
		
		// Initialize jqModal window
		$(this.dom).addClass('jqmWindow').jqm({overlay: 35});
		$(this.dom).parent().find('a:first').click(function (e) {
			that.show();
			e.preventDefault();
		});
		$('li.next a', this.dom).click(function (e) {
			NIQ.Contributors.nextWindow();
			e.preventDefault();
		});
		$('li.prev a', this.dom).click(function (e) {
			NIQ.Contributors.prevWindow();
			e.preventDefault();
		});
		$('a.close', this.dom).click(function (e) {
			that.hide();
			e.preventDefault();
		});
	},
	show: function () {
		NIQ.Contributors.showWindow(this.index);
	},
	hide: function () {
		NIQ.Contributors.hideWindow(this.index);
	}
};

/**
 * nutrition iQ Filters namespace
 */
NIQ.Filters = {
	buttons: {},
	containers: {},
	items: {},
	scroller: {},
	initialize: function () {
		// Define containers
		this.containers.filters = $('#filters').get(0);
		this.containers.media = $('#media-items').get(0);
		this.containers.hints = {
			pdf: $('#pdf-hint').get(0),
			link: $('#link-hint').get(0),
			img: $('#img-hint').get(0)
		};
		
		// Define buttons
		this.buttons.all = $('#filters-all').get(0);
		this.buttons.pdf = $('#filters-pdf').get(0);
		this.buttons.link = $('#filters-link').get(0);
		this.buttons.img = $('#filters-img').get(0);
		
		// Define scroller settings
		this.scroller.settings = {
			showArrows: true,
			scrollbarWidth: 11
		};
		
		// Build buttons
		this.buildButtons();
		
		// Build media item scroller
		this.buildScroller();
		
		// Get and categorize items
		this.getAllItems();
		
		// Initially show all items
		$(this.buttons.all).click();
	},
	buildButtons: function () {
		var that = this;
		var fadeSpeed = 250;
		$(this.buttons.all).click(NIQ.Utils.Delegate.create(this, this.handleNavigation));
		$(this.buttons.pdf).click(NIQ.Utils.Delegate.create(this, this.handleNavigation)).hover(function () {
			$(that.containers.hints.pdf).fadeIn(fadeSpeed);
		}, function () {
			$(that.containers.hints.pdf).fadeOut(fadeSpeed);
		});
		$(this.buttons.link).click(NIQ.Utils.Delegate.create(this, this.handleNavigation)).hover(function () {
			$(that.containers.hints.link).fadeIn(fadeSpeed);
		}, function () {
			$(that.containers.hints.link).fadeOut(fadeSpeed);
		});
		$(this.buttons.img).click(NIQ.Utils.Delegate.create(this, this.handleNavigation)).hover(function () {
			$(that.containers.hints.img).fadeIn(fadeSpeed);
		}, function () {
			$(that.containers.hints.img).fadeOut(fadeSpeed);
		});
	},
	buildScroller: function () {
		$(this.containers.media).jScrollPane(this.scroller.settings);
	},
	handleNavigation: function (e) {
		switch (e.currentTarget) {
			case this.buttons.all:
				this.activateButton(this.buttons.all);
				$(this.items.pdf).show();
				$(this.items.link).show();
				$(this.items.img).show();
				NIQ.Analytics.trackEvent('Filter', 'all');
				break;
			case this.buttons.pdf:
				this.activateButton(this.buttons.pdf);
				this.hideAllItems();
				$(this.items.pdf).show();
				NIQ.Analytics.trackEvent('Filter', 'pdf');
				break;
			case this.buttons.link:
				this.activateButton(this.buttons.link);
				this.hideAllItems();
				$(this.items.link).show();
				NIQ.Analytics.trackEvent('Filter', 'link');
				break;
			case this.buttons.img:
				this.activateButton(this.buttons.img);
				this.hideAllItems();
				$(this.items.img).show();
				NIQ.Analytics.trackEvent('Filter', 'img');
				break;
			default: break;
		};
		// Re-build scroller
		this.buildScroller();
		e.preventDefault();
	},
	getAllItems: function () {
		this.items.pdf = $('li > div.pdf', this.containers.media).parent().get();
		this.items.link = $('li > div.link', this.containers.media).parent().get();
		this.items.img = $('li > div.img', this.containers.media).parent().get();
	},
	hideAllItems: function () {
		$(this.items.pdf).hide();
		$(this.items.link).hide();
		$(this.items.img).hide();
	},
	activateButton: function (dom) {
		this.deactivateAllButtons();
		$(dom).addClass('active');
	},
	deactivateAllButtons: function () {
		for (var i in this.buttons) {
			$(this.buttons[i]).removeClass('active');
		}
	}
};

/**
 * nutrition iQ Store Finder namespace
 */
NIQ.StoreFinder = {
	buttons: {},
	containers: {},
	initialize: function () {
		// Define containers
		this.containers.main = $('#find-niq').get(0);
		this.containers.window = $('#find-niq-window').get(0);
		
		// Define buttons
		this.buttons.close = $('a.close', this.containers.window).get(0);
		this.buttons.find = $('#find-niq-button').get(0);
		
		// Build navigation
		this.buildNavigation();
		
		// Build window
		this.buildWindow();
	},
	buildNavigation: function () {
		$(this.buttons.close).click(NIQ.Utils.Delegate.create(this, this.handleNavigation));
		$(this.buttons.find).click(NIQ.Utils.Delegate.create(this, this.handleNavigation));
	},
	buildWindow: function () {
		$(this.containers.window).addClass('jqmWindow').jqm({overlay: 35});
		if (NIQ.Utils.BrowserCheck.isIE === true && NIQ.Utils.BrowserCheck.version < 7) {
			$(this.containers.window).css('margin-top', '-50px');
		} else {
			$(this.containers.window).css('margin-top', -($(this.containers.window).height()/2));
		}
	},
	handleNavigation: function (e) {
		switch (e.currentTarget) {
			case this.buttons.close:
				$(this.containers.window).jqmHide();
				break;
			case this.buttons.find:
				$(this.containers.window).jqmShow();
				break;
			default: break;
		}
		e.preventDefault();
	}
};

/**
 * nutrition iQ Utils namespace
 */
NIQ.Utils = {};

/**
 * nutrition iQ Browser Check namespace
 */
NIQ.Utils.BrowserCheck = {
	isIE: false,
	version: null,
	initialize: function () {
		/**
		 * Detect browser
		 * TODO: Detect more than IE
		 */
		this.detectBrowser();
	},
	detectBrowser: function () {
		if (navigator.appName == 'Microsoft Internet Explorer') {
			// Browser is IE
			this.isIE = true;
			var ua = navigator.userAgent;
			var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
			if (re.exec(ua) !== null) {
				// Set version
				this.version = parseFloat( RegExp.$1 );
			}
		}
	}
};

/**
 * Event delegate
 */
NIQ.Utils.Delegate = {
	create: function (obj, func) {
		return function (e) {
			e = e || {};
			// Forces currentTarget property of the Event object for browsers that don't correctly support it
			e.currentTarget = this;
			// Call function within context of specified object
			func.apply(obj, [e]);
		};
	}
};

/**
 * Image preloader
 */
NIQ.Utils.ImagePreloader = {
	paths: [],
	
	add: function (path) {
		this.paths.push(path);
	},
	
	load: function () {
		// Load images into empty elements
		$(this.paths).each(function () {
			$('<img>').attr('src', this);
		});
		
		// Clear out paths cache
		this.paths = [];
	}
};

/**
 * Initialize NIQ upon page load
 */
$(document).ready(function () {
	// Initialize common methods
	NIQ.initialize();
});