// --------------------------------------------------
// NWS Namespace
// --------------------------------------------------

if(!window.NWS){
	window.NWS = {};
}

// --------------------------------------------------
// Initialize NWS Application
// --------------------------------------------------

NWS.init = function(){
	
	//fire metrix for the page
	NWS.pageTrack();
	
	
	new NWS.smoothScroll($('nav#nav-main ul li').not('.page'), {
		wrapper: $('header#site-header'),
		replacementElement: 'button',
		callback: function(target){
			metrix._trackPage(target);
		}
	});
	
	//new NWS.omniturePage($('nav#nav-main ul li.page'));

	var circleField1 = new NWS.backgroundScroll($('div#circle-field-1'), {
		ammount: 50,
		itemClass: 'circle',
		itemHeight: 65,
		itemWidth: 65,
		inertia: 1.2
	});

	var circleField2 = new NWS.backgroundScroll($('div#circle-field-2'), {
		ammount: 40,
		itemClass: 'circle',
		itemHeight: 170,
		itemWidth: 170,
		inertia: 2
	});

	var circleField3 = new NWS.backgroundScroll($('div#circle-field-3'), {
		ammount: 7,
		itemClass: 'circle',
		itemHeight: 667,
		itemWidth: 667,
		inertia: 3
	});
};

// --------------------------------------------------
// Anchor Smooth Scroll
// --------------------------------------------------

NWS.pageTrack = function(){
	var curLocation = document.location.href;
	var backslashPos = curLocation.lastIndexOf("/") + 1;
	var pageStr = curLocation.substr(backslashPos);
	var hashInt, aNameStr;
	if(backslashPos>7 && pageStr.length>1) {
		hashInt = pageStr.indexOf("#");
		if(hashInt!=-1){
			//strip out everything before the hash
			aNameStr = pageStr.substr(hashInt+1);
			metrix._trackPage(aNameStr);
		}else{
			metrix._trackPage(pageStr); 
		}	
	}else{
		metrix._trackPage("home");	
	}
}


NWS.smoothScroll = function(target, options){
	var base = this;

	base.options = $.extend({
		wrapper: null,
		replacementElement: null,
		scrollDuration: 1000,
		callback: function(target){}
	}, options || {});

	base.elTarget = target;

	base.init();
};

NWS.smoothScroll.prototype = {
	init:function(){
		var base = this,
			i, ii, elCopy, elHref, el, elCollection = [],
			elType = base.options.replacementElement;

		if(elType){		
			for(i = 0, ii = base.elTarget.length; i < ii; i++){
				elCopy = $(base.elTarget[i]).find('a').text();
				elHref = $(base.elTarget[i]).find('a').attr('href');
				el = $('<' + elType + ' />').text(elCopy).data('destination', elHref);
				
				$(base.elTarget[i]).find('a').replaceWith(el);
			}
		}
		
		
		base.elTarget = elType ? base.elTarget.find(elType) : base.elTarget.find('a');

		base.bindEvents();
	},
	bindEvents:function(){
		var base = this;

		base.elTarget.click(function(e){
			e.preventDefault();

			if(base.options.wrapper){
				/*base.hideWrapper();*/
			}

			base.jump(this);
		});
	},
	jump:function(el){
		var base = this,
			targetID = base.options.replacementElement ? $(el).data('destination') : el.hash,
			targetName = targetID.replace('#', ''), targetOffset;

		if(targetID.length){
			targetOffset = $(targetID).offset().top;

			$('html,body').animate({
				scrollTop: targetOffset
			}, base.options.scrollDuration, 'easeOutExpo', function(){
				if(targetName !== base.currentSection){
					base.options.callback(targetName);

					base.currentSection = targetName;
				}
			});
		}
	},
	hideWrapper:function(){
		var base = this,
			duration = base.options.scrollDuration / 3;

		base.options.wrapper.animate({
			opacity: 0,
			top: '-' + base.options.wrapper.height()
		}, duration, 'easeOutExpo', function(){ base.showWrapper(); });
	},
	showWrapper:function(duration){
		var base = this,
			duration = base.options.scrollDuration;

		base.options.wrapper.animate({
			opacity: 1,
			top: 0
		}, duration, 'easeInOutBack');
	}
};

// --------------------------------------------------
// Background Scroll
// --------------------------------------------------

NWS.backgroundScroll = function(target, options){
	var base = this;

	base.options = $.extend({
		ammount: 50,
		itemClass: 'item-class',
		itemHeight: 65,
		itemWidth: 65,
		adjuster: 900,
		inertia: 0.3
	}, options || {});

	base.elTarget = target;

	base.init();
};

NWS.backgroundScroll.prototype = {
	init:function(){
		var base = this;

		base.generate();

		base.bindEvents();
	},
	generate:function(){
		var base = this,
			i, ii, el;

		base.elTarget.css({
			height: $('body').height() * base.options.inertia,
			top: base.scrollPosition(base.options.adjuster, base.options.inertia)
		});

		for(i = 0, ii = base.options.ammount; i < ii; i++){
			el = $('<div class="' + base.options.itemClass + ' item-' + i + '" />');

			$(el).css({
				left: base.randomCoordinates(0, base.elTarget.width() - base.options.itemWidth),
				top: base.randomCoordinates(0, base.elTarget.height())
			});

			base.elTarget.append(el);
		}
	},
	bindEvents:function(){
		var base = this;

		$(window).scroll(function(e){
			base.elTarget.css({
				'top' : base.scrollPosition(base.options.adjuster, base.options.inertia)
			});
		});
	},
	randomCoordinates:function(from, to){
		var base = this;

	    return Math.floor(Math.random() * (to - from + 1) + from);
	},
	scrollPosition:function(adjuster, inertia){
		var base = this;

	    return (-(($(window).height() + $(window).scrollTop()) - adjuster) * inertia)  + "px";
	}
	
};

//--------------------------------------------------
// Calendar Detail
// --------------------------------------------------

NWS.calendarDetail = function(target, content, options){
	var base = this;

	base.options = $.extend({
		fadeInDuration: 300,
		fadeOutDuration: 100
	}, options || {});

	base.elTarget = target;
	base.elContent = content;

	base.init();
};

NWS.calendarDetail.prototype = {
	init:function(){
		var base = this;

		base.buildContent();
		base.bindEvents();
	},
	bindEvents:function(){
		var base = this;

		base.elContentWrapper.click(function(e){
			base.elContentWrapper.fadeOut(base.options.fadeOutDuration, function(){
				$(this).remove();
			});
		});
	},
	buildContent:function(){
		var base = this,
			elHeader = $('<h1 />').text(base.elContent.title),
			elCopy = $('<div />').html(base.elContent.copy);
		
		base.elBtnClose = $('<button id="btn-detail-close">Close</button>');

		base.elContentWrapper = $('<div id="calendar-detail" />').append(elHeader, elCopy, base.elBtnClose).hide();

		base.elTarget.append(base.elContentWrapper.fadeIn(base.options.fadeInDuration));
	}
};

// --------------------------------------------------
//
// Content Switcher
//
// USAGE: homeCarousel = new NWS.contentSwitcher(target, options);
//
// AUTHOR: MC
//
// DEPENDENCIES:
// jQuery 1.6 or later
//
// --------------------------------------------------

NWS.contentSwitcher = function(target, options){
	var base = this;

	base.options = $.extend({
		elWrapper: null,			// wrapper element
		drawerSelector: null,		// hide/show drawer content
		panelTitleSelector: null,	// button/tab text
		contentSelector: null,		// content element for fancy load in
		btnElement: null,           // override default button element
		currentIndex: 0,			// index for first content loaded
		maxItems: 5,				// max items in switcher
		cycleSpeed: 6000,			// speed through auto cycle
		panelFadeDuration: 1000,	// duration for switching panels
		autoCycle: false,			// boolean for auto cycling
		pagination: false,			// boolean for pagination buttons
		arrows: false,				// boolean for arrow buttons
		showNext: false,			// boolean for displaying next panel title
		showNextText: 'Next: ',     // next text indicator
		itemCount: false,			// boolean for item count display
		itemCountSeparator: ' of ',	// set separator for item count
		callback: function(){}
	}, options || {});

	base.elPanel = target;
	
	base.animating = false;
	base.elWrapper = !!base.options.elWrapper ? base.options.elWrapper : base.elPanel.parent();

	base.init();
	base.options.callback();
};

NWS.contentSwitcher.prototype = {
	init:function(){
		var base = this, i, ii, contentNodeLeftPosition,
			elContentNodes = $(base.elWrapper).find(base.options.contentSelector).children();

		// cache current panel
		base.elCurrentPanel = $(base.elPanel[base.options.currentIndex]);

		// cache original left position for all content elements
		for(i = 0, ii = elContentNodes.length; i < ii; i++){
			contentNodeLeftPosition = $(elContentNodes[i]).position().left;

			$(elContentNodes[i]).data('leftPosition', contentNodeLeftPosition);
		}

		// hide all panels except the default panel
		base.elPanel.hide();
		base.elCurrentPanel.show().addClass('on');

		// build out navigation
		base.buildNav();

		// animate default panels conent
		if(base.options.contentSelector){
			base.animateContent();
		}

		// cycle through panels
		if(base.options.autoCycle){
			base.cycle = setTimeout(function(){
				base.autoCycle();
			}, base.options.cycleSpeed);
		}
	},
	buildNav:function(){
		var base = this, i, ii,
			elNavLink, itemCount,
			elBtnBack, elBtnNext,
			elBtnDrawer, btnText,
			btnElement, elNextPanel,
			nextPanelText;

		itemCount = base.elPanel.length > base.options.maxItems ? base.options.maxItems : base.elPanel.length;
		btnElement = base.options.btnElement ? base.options.btnElement : 'button';

		if(itemCount > 1){
			base.elControlsWrapper = $('<div class="panel-controls"></div>');

			// build out pagination/tabs
			if(base.options.pagination){
				base.elNavPagiWrapper = $('<ul class="nav-panels-pagi" />');

				for(i = 0, ii = itemCount; i < ii; i++){
					btnText = base.options.panelTitleSelector ? $(base.elPanel[i]).find(base.options.panelTitleSelector).text() : 'Panel ' + (i + 1);
					elNavLink = $('<li><div>' + btnText + '</div></li>').addClass('btn-' + i);
	
					if(i === base.options.currentIndex){
						elNavLink.addClass('on');
					}
	
					base.elNavPagiWrapper.append(elNavLink);
				}
	
				base.elControlsWrapper.append(base.elNavPagiWrapper);
			}

			// build arrow buttons
			if(base.options.arrows){
				base.elNavArrowsWrapper = $('<ul class="nav-panels-arrows" />');
				
				elBtnBack = $('<li class="btn-back"><' + btnElement + '>Back</' + btnElement + '></li>');
				elBtnNext = $('<li class="btn-next"><' + btnElement + '>Next</' + btnElement + '></li>');

				base.elNavArrowsWrapper.append(elBtnBack, elBtnNext);
				base.elControlsWrapper.append(base.elNavArrowsWrapper);

				if(base.options.currentIndex === 0){
					base.elNavArrowsWrapper.children('li.btn-back').addClass('disabled');
				}else if(base.options.currentIndex === base.elPanel.length - 1){
					base.elNavArrowsWrapper.children('li.btn-next').addClass('disabled');
				}
			}

			// add drawer navigation
			if(base.options.drawerSelector){
				for(i = 0, ii = itemCount; i < ii; i++){
					elBtnDrawer = $('<button class="btn-drawer">See Details</button>');

					$(base.elPanel[i]).append(elBtnDrawer);
				}
			}

			// display item count
			if(base.options.itemCount){
				base.elCountWrapper = $('<p class="panel-count"></p>');

				base.elCountWrapper.text((base.elCurrentPanel.index() + 1) + base.options.itemCountSeparator + (base.elPanel.length));
				base.elControlsWrapper.append(base.elCountWrapper);
			}

			// display next panal title
			if(base.options.showNext){
				base.elShowNextWrapper = $('<p class="panel-next"></p>');

				elNextPanel = base.elCurrentPanel[0] !== base.elPanel.last()[0] ? base.elPanel[base.elCurrentPanel.index() + 1] : base.elPanel[0];
				nextPanelText = base.options.showNextText + $(elNextPanel).find(base.options.panelTitleSelector).text();

				base.elShowNextWrapper.text(nextPanelText);
				base.elControlsWrapper.append(base.elShowNextWrapper);
			}

			base.elWrapper.prepend(base.elControlsWrapper)
		}

		base.bindEvents();
	},
	bindEvents:function(){
		var base = this,
			direction;

		// bind click to all pagination/tab buttons
		if(base.elNavPagiWrapper){
			base.elNavPagiWrapper.children('li').click(function(e){
				if(!base.animating){
					base.switchPanel($(this).index());
	
					clearTimeout(base.cycle);
					clearTimeout(base.progressInterval);
				}
			});
		}

		// bind click to arrow buttons
		if(base.elNavArrowsWrapper){
			base.elNavArrowsWrapper.children('li').click(function(e){
				if(!base.animating){
					direction = $(this).hasClass('btn-back') ? 'back' : 'next';
	
					if(direction === 'back' && base.elCurrentPanel.index() > 0){
						base.switchPanel(base.elCurrentPanel.index() - 1);
					}else if(direction === 'next' && base.elCurrentPanel.index() < base.elPanel.length - 1){
						base.switchPanel(base.elCurrentPanel.index() + 1);
					}

					clearTimeout(base.cycle);
					clearTimeout(base.progressInterval);
				}
			});
		}

		// bind click to drawer button
		if(base.options.drawerSelector){
			$(base.elPanel).children('.btn-drawer').click(function(e){
				if(!base.animating){
					action = $(this).hasClass('btn-close') ? 'close' : 'open';

					if(action === 'open'){
						base.openDrawer(this);
					}else if(action === 'close'){
						base.closeDrawer(this);
					}

					clearTimeout(base.cycle);
					clearTimeout(base.progressInterval);
				}
			});
		}
	},
	switchPanel:function(index){
		var base = this,
			elTargetPanel;

		if(index !== undefined){
			elTargetPanel = base.elPanel[index];
		}else{
			if(base.elCurrentPanel.next('li').length && base.elCurrentPanel.next('li').index() + 1 <= base.options.maxItems){
				elTargetPanel = base.elCurrentPanel.next('li');
			}else{
				elTargetPanel = $(base.elPanel[0]);
			}
		}

		if(base.elCurrentPanel[0] !== elTargetPanel && !base.animating){
			base.animating = true;

			base.elCurrentPanel.removeClass('on').fadeOut(base.options.panelFadeDuration / 2);

			$(elTargetPanel).addClass('on').fadeIn(base.options.panelFadeDuration, function(){
				if(!base.options.contentSelector){
					base.animating = false;
				}
			});

			base.elPreviousPanel = base.elCurrentPanel;
			base.elCurrentPanel = $(elTargetPanel);

			if(base.options.contentSelector){
				base.animateContent();
			}

			base.updateUI();

			// switching panel event
			$('body').trigger('POP:switchPanel');
		}
	},
	updateUI:function(){
		var base = this,
			elNextPanel,
			nextPanelText;

		// update current panel indicator
		if(base.options.pagination){
			base.elNavPagiWrapper.children('li').removeClass('on');

			$($('ul.nav-panels-pagi li')[base.elCurrentPanel.prevAll().not('.panel-controls').length]).addClass('on');
		}

		// enable/disable arrows
		if(base.options.arrows){
			base.elNavArrowsWrapper.children('li').removeClass('disabled');

			if(base.elCurrentPanel.index() === 0){
				base.elNavArrowsWrapper.children('li.btn-back').addClass('disabled');
			}else if(base.elCurrentPanel.index() === base.elPanel.length - 1){
				base.elNavArrowsWrapper.children('li.btn-next').addClass('disabled');
			}
		}

		// keep track of current panel
		if(base.options.itemCount){
			base.elCountWrapper.text((base.elCurrentPanel.index() + 1) + base.options.itemCountSeparator + (base.elPanel.length));
		}

		// show upcoming panel
		if(base.options.showNext){
			elNextPanel = base.elCurrentPanel[0] !== base.elPanel.last()[0] ? base.elPanel[base.elCurrentPanel.index() + 1] : base.elPanel[0];
			nextPanelText = base.options.showNextText + $(elNextPanel).find(base.options.panelTitleSelector).text();

			base.elShowNextWrapper.text(nextPanelText);
		}
	},
	animateContent:function(){
		var base = this, loadInterval, currentIndex = 0,
			elContent = base.elCurrentPanel.children(base.options.contentSelector).children();

			base.animating = true;

		loadInterval = setInterval(function(){
			if(currentIndex <= elContent.length - 1){
				$(elContent[currentIndex]).animate({
					left : 0,
					opacity : 1
				}, 1000, 'easeOutExpo');

				currentIndex += 1;	
			}else{
				if(base.elPreviousPanel){
					base.resetContent();
				}

				currentIndex = 0;
				base.animating = false;

				clearInterval(loadInterval);
			}
		}, 500);
	},
	resetContent:function(){
		var base = this, i, ii,
			elContent = base.elPreviousPanel.children(base.options.contentSelector).children();

		for(i = 0, ii = elContent.length; i < ii; i++){
			$(elContent[i]).css({
				left : $(elContent[i]).data('leftPosition'),
				opacity : 0
			});
		}
	},
	openDrawer:function(el){
		var base = this;

		base.animating = true;

		$(el).addClass('btn-close');

		$(el).siblings(base.options.drawerSelector).animate({
			opacity: 1,
			top: 0
		}, 500, 'easeOutExpo', function(){
			base.animating = false;
		});
	},
	closeDrawer:function(el){
		var base = this;

		base.animating = true;

		$(el).removeClass('btn-close');

		$(el).siblings(base.options.drawerSelector).animate({
			opacity: 0,
			top: '100%'
		}, 300, 'easeOutExpo', function(){
			base.animating = false;
		});
	},
	autoCycle:function(){
		var base = this,
			i = base.elCurrentPanel.index() + 1;

		(function cycleNode(){
			base.switchPanel();
			base.progressInterval = setTimeout(cycleNode, base.options.cycleSpeed);
		})();
	}
};

// --------------------------------------------------
// Load On DOM Ready
// --------------------------------------------------

$(function(){
	NWS.init();
});
