$(function(){
	// ## SHADOWBOX
	//
	$('ul.js-sellmore li').each(function(){
		var url = $(this)
			.find('a')
			.eq(0)
			.attr('rel','shadowbox;width=800;height=600')
			.attr('href');
		$(this)
			.find('p')
			.append('<span><a href=\"'+url+'\" rel=\"shadowbox;width=800;height=600\">View more &raquo;</a></span>');
	})
	Shadowbox.init();
	
	// ## Product LHN
	//
	var currentURL = window.location.pathname,
		anch = window.location.hash;
		products = {};
		prodControls = {																
			nav     : {
				level : {}
			},
			content : {
				level : {}
			}
		};

	// ## mainNav active link state management
	//
	$('#mainNav > li > a').add('li.hasDrop > div > a').each(function(){ 
	    if($(this).attr('href') == currentURL){
	        $(this)
				.addClass('mainNavOn')
				.parent()
				.addClass('mainNavOn');
	    }
	});
	
	// ## Subnav active link state management
	//
	$('.subNav a').each(function() {
		if($(this).attr('href') == window.location.pathname){
	        $(this)
				.addClass('subNavOn')			// mark subnav <a> on
				.parents('ul#mainNav > li')		// find mainNav <li> above
				.addClass('mainNavOn')			// mark on
				.find('> a, div > a')			// find mainNav anchor
				.addClass('mainNavOn');			// mark on
	    }
	});
	
	// ## Product Showcase generation and animation
	//
	var showContainers = $('div[id^="showPath-"]'); 
	if ($(showContainers).size() != 0) {
		var totalShows = 3,
		logoPathsReference = {
			'wl' : 'wine-logos',
				'wb' 	: 'bubbles',
				'wc' 	: 'california',
				'wd' 	: 'dessert',
				'we' 	: 'european',
				'wi'	: 'imports',
				'wo' 	: 'oregon',
				'wod' 	: 'other-domestic',
				'ws' 	: 'sake',
				'wsh' 	: 'southern-hemisphere',
				'ww' 	: 'washington',
			'bl' : 'beer-logos',
				'bd' 	: 'domestic',
				'bi'	: 'import',
				'bci'	: 'cider',
				'bcr'	: 'craft',
				'bp'	: 'pab',
			'nal' : 'na-logos',
				'ne'		: 'energy',
				'ns'		: 'soda',
				'ntj'		: 'tea-juice',
				'nwa'		: 'water',
				'nwe'		: 'wellness'
		};
		
		// GET PATH TO DIRECTORY FOR ALL IMAGES IN THIS DIV
		function parsePath(pathInfo) {
			var path = "/images";
			pathInfo = pathInfo.split('-'); 								// split path into array
			pathInfo.splice(0,1); 											// remove 'showPath'
			for (pathSeg in pathInfo) {										// build path string from lpr obj
				if (pathSeg == 'indexOf') {continue;}						// Fix for IE's poor handling of .slice() method
				path += '/' + logoPathsReference[pathInfo[pathSeg]];
			}
			return path;
		}

		$(showContainers).each(function(){ 										// ## Iterate each div with shows
			 var imagePath = parsePath( $(this).attr('id') ),					// grab categories from ID
				listEls = [],													// init array to hold + randomize li's
				siz = 0,														// init size var
				insertStr = '',													// generated html
				totalShowCount = 0;												// showcases generator loop #
				
			$(this).find('li[class^=show-]').each(function(){					// iterate show li
				var fileName = $(this).attr('class').substring(5);				// find the filename linked to in the class name
				var linkObj = $(this).find('a');							// find the link 'a' object
				var linkHREF = linkObj.attr('href');							// extract the hyperlink
				var bulletImgLinkTxt;										// the rendering HTML
				if (linkHREF==undefined) {
					bulletImgLinkTxt = '<li><img src="'+ imagePath + '/' +  fileName +'.aspx" border="0" alt="" />'+$(this).html()+'</li>';
				} else {
					bulletImgLinkTxt = '<li><a href="' + linkHREF + '" target="_null"><img src="'+ imagePath + '/' +  fileName +'.aspx" border="0" alt="" /></a>'+$(this).html()+'</li>';
				}
				listEls.push(bulletImgLinkTxt);	// build array of new li's
				siz++;
			});

			while(siz != 0 && totalShowCount <= totalShows){					// Random showcases built here
				totalShowCount++;
				// build outer ul
				insertStr += '<ul class="clearfix grid-width-4 showcase">';
				// loop four times
				for(showLength = 1; showLength <= 4 && siz !=0; showLength++, siz--) {		
					var randomLi = 	Math.floor(Math.random()*siz);
					insertStr += listEls.splice(randomLi,1); // random list el
				}
				insertStr += '</ul>';
			}
			//## Insert generated showcase
			$(this)
				.find('.extended-content')										// find div.extended-content
				.eq(0)
				.before(insertStr);												// prepend insert showcase
			$(this)
				.find('ul.showcase')
				.eq(0)
				.addClass('showcase-active');
		});

	}
	
	function animateStack(stackContainer){
		var stackAnimTime = 300,
			stacks = $(">ul.showcase",stackContainer),
			activeStack = 0,
			stackTotal = $(stacks).size()-1;
			
		if (stackTotal <= 0) {return false;}

		$(stacks).each(function(i){	
			if ( $(this).is(':visible') ) {
				activeStack = i;
			}
		});

		function _anim() {
			$(stacks)
				.eq(activeStack)
				.animate({opacity:0},stackAnimTime,function(){
					$(this).css('display','none');
				});
				
			if (activeStack == stackTotal) { activeStack = -1;}
			
			$(stacks)
				.eq(activeStack+1)
				.css('display','block')
				.animate({opacity:1.0},stackAnimTime);
				
			activeStack++;
		}

		waveQStackSwitcher = setInterval(_anim, 4500);
	}
	
	// ## INIT - Collect product specialties into object
	//
	function categorize(args) { // possible args passed in here are link element (el), anchor name (name), nesting level (level) 
		var 
			anchor   = $(args.el),				// grab link item
			listItem = $(anchor).parent(),		// grab parent <li>
			name     = $(anchor).attr('href');	// grab anchor targets name
		
		if ( prodControls[name] != undefined ) {  return prodControls[name]; }				// return object if already categorized	
		else { prodControls[name] = {}; }													// init object if non-existent
		
		prodControls[name].linkObject = anchor;												// Add element
		
		// Nav Target
		if ( $(listItem).find('ul').size() != 0 ) {											// Look for a child list
			prodControls[name].navTarget = $(listItem).find('ul').eq(0);					// Add child as navTarget
			prodControls[name].level = args['level'] == undefined ? 0 : args['level'];		// Mark its level (default to 0 if no level passed)	
			$(prodControls[name].navTarget).find('a').each(function(){						// Pass the child throught categorize()
				categorize({																// Call self, pass target
					el    : $(this), 
					level : prodControls[name].level + 1
				});	
			});
		} 
		
		// Content Target
		prodControls[name].contentTarget = $('div.col_right a[name='+name.substr(1)+']')	// Add contentTarget (a > h2 > container div)
			//.parent()
			.parent();	
		prodControls[name].extended_content = $(prodControls[name].contentTarget).find('div.extended-content');
		prodControls[name].level = args['level'] == undefined ? 0 : args['level'];			// Add level
		
		return prodControls[name];
	}	
	
	if ( $('.product-lhc-subnav').size() != 0 ) {
		var lhcLinks = [];																		// Working var for clickable headers
	
		$('.product-lhc-subnav a').each( function(i) {										
			lhcLinks.push([
				($(this))
				,$(this).text().replace(/ »/,"")
			]);
			prodObj = categorize({ el : $(this) });												// Collect links into object
			$(prodObj.linkObject).get(0).prodObj = prodObj;										// Attach object to its dom element
		});
		
		// ## Product headers - make into active links
		// Automatically wrap headers in an anchor and bind to showsubsection function passing the adjacent anchor name as an arg
		// Cannot wrap
		$('.col_right :header').not('h1').each(function () {
			// get named anchor
			var anchText = $(this).text();
			for(i=0, len=lhcLinks.length; i <= len; i++) {
				if (anchText == lhcLinks[i][1]) {
					$(this).get(0).lhnTarget = lhcLinks[i][0];
					$(this)
						.css('cursor','pointer')
						.click(function(){
							$( $(this).get(0).lhnTarget ).click();
						})
					break;
				}
			}
			// find the matching link
			// attach that link obj to the header as an obj
			// attach on onclick anon func that calls hpc func while passing the obj
		});
	}
	
	
	for (o in prodControls) {																// Iterate all collected objects
		var obj = prodControls[o];
		if (obj.contentTarget != undefined){ 												// Avoid nav and content objects
			if (obj.navTarget != undefined) {												// Process nav controllers
				if (prodControls.nav.level[obj.level] == undefined) {
					prodControls.nav.level[obj.level] = $();								// Init as an empty jQuery set
				}	
				prodControls.nav.level[obj.level] = $(prodControls.nav.level[obj.level]).add(obj.navTarget);		// Add nav object to set
			}

			if (prodControls.content.level[obj.level] == undefined) {
				prodControls.content.level[obj.level] = $();								// Init as an empty jQuery set
			}	
			prodControls.content.level[obj.level] = $(prodControls.content.level[obj.level]).add(obj.contentTarget);// Add content object to set			
		}
	}
	
	// ## Flyout - Prepend the off-page pointing anchors with 'js-' to defeat onload page jump
	$('#dropdown a').each(function(){
		var flyUrl = $(this).attr('href');
		if ( flyUrl.indexOf('#') != -1 && $.url.setUrl(flyUrl).attr('path') != currentURL ) {
			$(this).attr(
				'href',
				$(this).attr('href').replace("#","#js-")
			)
		}
	});
	
	// ## New page navigation - User comes on site landing on a product page with anchor
	if (anch != '') { 
		anch = anch.replace("#js-","#");
		showSubsection(anch.substr(1));
	}
	
	// ## Same page navigation
	$('#dropdown').add('.product-lhc-subnav').bind('click', function(event){
		// Ignore clicks on list if they are not on an anchor
		if($(event.target)[0].tagName != 'A') {
			event.preventDefault();
			return false;
		} else {
			handleProductClick(event);
		}
	}); 
	
	
	// ## UTIL
	// 
	// Product click filter 
	// If this is a click to a same page link with an anchor pass the anchor name to showSubsection()
	function handleProductClick(event) {
		if ($(event.target).hasClass('active')) { 
			event.preventDefault();
			return false; 
		}
		var toUrl = ($(event.target).attr('href')), 																// Get full url
			toPath = $.url.setUrl(toUrl).attr('path'); 																// Get url without hash
		if ( toUrl.indexOf('#') != -1 && ( toPath == currentURL  || toPath == null) ) {								// Verify valid link
			showSubsection($.url.setUrl(toUrl).attr('anchor'));	
			event.preventDefault();																					// Call showSubSection()
		} 
	}
	// Update Address Bar hash
	//
	function updateHashAddress(newHash) {
		window.location.hash = 'js-'+newHash;
	}
	// Update active link style
	//
	function updateLHNProductLink(anchorTag) {
		var choice = $('.product-lhc-subnav a[href=#'+anchorTag+']');												// Find new anchor
		$('.product-lhc-subnav a.active').removeClass('active');													// Remove old link active
		$(choice).addClass('active');																				// Update new
	}
	// Clean up dropdowns on new selection
	//
	function cleanUpLHN(newAnchor) {
		var curParentWork  = {},																					// Work var
			newParents 	   = $('.product-lhc-subnav a[href=#'+newAnchor+']').parents('ul'),							// New selections parents
			currentSelection = $('.product-lhc-subnav a.active'),
			activeULs = $('.product-lhc-subnav ul:visible');
		
		$(activeULs).each(function(i) {																				// Bring currentParents into work var
			curParentWork[i] = {parentUl : $(this).get(0), shouldBeClosed : true};									// with bool indicating close or no close
		});
		
		$(newParents).each(function() {																				// Iterate newParents comparing to current
			for(i in curParentWork) {																				// parents. If parents are the same, mark
				if ( curParentWork[i+''].parentUl == $(this).get(0)) {												// for no close
					curParentWork[i+''].shouldBeClosed = false;
				}
			}
		});
		
		for (i in curParentWork) {
			if (curParentWork[i+''].shouldBeClosed) { 																// Iterate and take care of business
				$(curParentWork[i+''].parentUl).hide(); 
			}									
		}
	}
	// Product section reveal
	//
	function showSubsection(choice) {	
		cleanUpLHN(choice);																							// Zip up prev. shown menus
		updateHashAddress(choice);																					// Update address bar with new hash
		updateLHNProductLink(choice);																				// Update active menu link style
		
		choice = $('.product-lhc-subnav a[href=#'+choice.replace('js-','')+']');
		choice = $(choice).get(0).prodObj;																			// Grab linkObject data
		if (choice.navTarget != undefined) {
			$(choice.navTarget).toggle();
		}
		var lvl 	   = choice.level,
			workTarget = choice.contentTarget,
			choiceShowContainer = choice.contentTarget; 														 
		if(lvl == 0) {																								// Clicking a top level(0) parent is the only time we need to stop/start animation	
			try {
				clearInterval(waveQStackSwitcher);															
			} catch(err) {
				null;
			}
			animateStack(choiceShowContainer);
		}
		$(prodControls.content.level[lvl]).hide();																	// Hide all lists on level
		$(workTarget).add(choice.extended_content).show();															// Show extended content
		$(workTarget).find('div.product-list').show();																// Show container
		//$(workTarget).find('> .showcase').show();																	// Show showcase 
		
		while ( lvl !== 0 ) {																						// Climb and manipulate parent chain
			lvl--;																									
			workTarget = $(workTarget).parents('div.product-list').eq(0); 											// Move up one parent
			$(prodControls.content.level[lvl]).hide(); 																// Hide parent sibs
			$(workTarget).show(); 																					// Show parent
			$(workTarget).find('div.extended-content').eq(0).show(); 												// Show parent extended content
			//$(workTarget).find('> .showcase').hide(); 															// Hide parents showcase 
		}
	}
	
	//	## CONTENT ZIPPING
	//
	$('div.article-container')
		.addClass('zipped hasZip')
		.append('<span class="zip-control"><span>Continue Reading »<br />Finished Reading &laquo;</span></span>')
	$('.zip-control').bind('click',function(){
		$(this).parent().toggleClass('zipped');
	});
	
	
	// ## SLIDERS
	//
	carouselLists = $('div.carousel');
	$(carouselLists)
		.children('ul')
		.addClass('clearfix');
		
	// create sliders array
	carouselSliders = new Array;
	
	// create and push sliders
	$(carouselLists).each(function(i){
		// create obj
		var o = {},requiredWidth=0;
		o.container = $(this);
		o.viewport = $(o.container).children('div.viewport');
		o.viewportWidth = $(o.viewport).width();
		o.slider = $(o.viewport).children('ul');
		o.slides = $(o.slider).children('li');
		o.slideCount = $(o.slides).size();
		o.slideWidth = o.slides.eq(0).outerWidth(true);
		o.slideImgHeight = $(o.slides).eq(0).find('img').eq(0).css('height');
		
		// verify content exceeds viewport; if not, abort
		$(o.slides).each(function(i){ 
			requiredWidth += $(this).outerWidth(true); 
			if ( i == 0 || (o.slideCount - 1) ) {
				if ( i == 0 ) {requiredWidth -= parseInt( $(this).css('margin-left') );}
				if ( i == (o.slideCount - 1) ) {requiredWidth -= parseInt( $(this).css('margin-right') );}
			}
		});
		if(requiredWidth <= o.viewportWidth ) {return false;}
		
		// build controls sized to height slide image
		var controls = $(document.createElement('div'))
			.addClass('slider-arrow prev')
			.add(
				$(document.createElement('div'))
				.addClass('slider-arrow next')
			);
			if (o.slideImgHeight != undefined) { $(controls).css('height',o.slideImgHeight); } // fall back to css which uses height: 100%
		$(this).prepend(controls);
		o.controls = $(o.container).children('.slider-arrow');
		
		// add to slider array
		carouselSliders.push(o);
		
		// extend width of ul to accomodate single row
		$(o.slider)
			.css('width',(o.slideWidth * (o.slideCount + 2)) + 500 + "px");
		
		$(o.controls).each(function(ci){
			$(this).bind('click', function(){
				try{
					var s = carouselSliders[i].slider;
						targetSlide = !ci ?  $(s).children('li:last-child') : firstSlide = $(s).children('li:first-child');
						cloneWidth = $(targetSlide).outerWidth(true) * -1 + 'px';
					if(!ci){ // left control
						$(targetSlide)
							.detach()
							.css('margin-left',cloneWidth)
							.prependTo(s); 																		// attach to left
						$(s).children('li:first-child').animate({'margin-left':'5px'},150,'swing');				// slide list
					}else{ // right control
						$(targetSlide).animate({'margin-left':cloneWidth},150,'swing', function(){
							$(targetSlide)
								.detach()
								.css('margin-left','5px')
								.appendTo(s); 											
						});		
					}
				} catch (e){
					return false;
				}
			})
		});
	});
	
	// ## DYNAMIC DROPDOWNS
	//
	// Product page dynamic master dropdown list generation
	//
	//- Detect product page
	if (currentURL == '/Products/Beer.aspx' || currentURL == '/Products/Wine.aspx' || currentURL == '/Products/Non-alcoholic.aspx') {
		var 
			selectText = currentURL != '/Products/Non-alcoholic.aspx' ? 'All ' + $.trim( $('h1').text() + " Products" ) : 'All NA Products',
			workArray = [],
			alphaList = "",
			clonedListItems = $('ul.product-list li').clone(false); // Clone all LI into a var
		
		// Create drop element
		dropCode = $(document.createElement('div')) // Build the dropdown container
			.addClass('dropSelector')
			.append('<span class="defaultMsg">'+selectText+'</span><ul></ul><div class="control"></div>');
			
		// Extract data into array
		$(clonedListItems).each(function(i) {
		    workArray.push([
		        $(this).text().trim(),
		        $(this).find('a').attr('href') || ''
		    ]);
		});
		// Alpha sort array
		workArray.sort();
		
		// Rebuild list items
		for (var i = 0, len = workArray.length; i < len; i++) {
			if (workArray[i][1] != "") {
				alphaList += '<li><a href="'+workArray[i][1]+'" target="_blank">'+workArray[i][0]+'</a></li>';
			} else {
				alphaList += '<li>'+workArray[i][0]+'</li>';
			}
		}
		
		// Create new list
		$(dropCode).find('ul').append(alphaList);
		
		// Insert drop list
		$('div.col_right').prepend(dropCode);
			
		// Bind events
		$('div.dropSelector').bind('mouseleave',function(){
			$(this)
				.removeClass('dropSelectorActive')
				.children('ul').get(0).scrollTop = '0px';
		});
		$('div.dropSelector').bind('mouseover',function(){
			$(this).addClass('dropSelectorActive');
		});
		
		// ## PRODUCT LIST ALPHABETICAL REFLOW
		//
		// Automatically create vertical orientation of product lists
		//		
		var prodCollection = $('ul.product-list'),
	    	columnCount = 4;

		$(prodCollection).each(function() {
		    var curItems = $(this).find('li'),
		        itemCount = $(curItems).size(),
		        itemsPerCol = Math.ceil(itemCount / columnCount),
		        breakAt = itemsPerCol-1, // .each is zero based
		        workStr = '<div style="width: 155px; float: left; display: inline; margin-right: 5px;">';

		    $(curItems).each(function(i) {
		        if (i == breakAt + 1) {
		            workStr += '<div class="" style="width: 155px; float: left; display: inline; margin-right: 5px;">';
		            breakAt += itemsPerCol;
		        }
		        workStr += '<li>'+ $(this).html() + '</li>';
		        if (i == breakAt) {
		            workStr += '</div>';
		        }
		    });
		    workStr += "</div>";
		    $(this).html(workStr);
		});
	} 
	
	// ## RSS GENERATORS
	//
	if ($('.rssJobs').size() != 0) {
		rssEl = $('.rssJobs');
		$.ajax({
			type: "GET",
			url: "http://query.yahooapis.com/v1/public/yql",
			data: "q=SELECT * FROM feed WHERE url='http://client.hrservicesinc.com/downloads/rss/portals/228.xml'&format=json&diagnostics=true&callback=cbfunc",
			dataType: "jsonp",
			success: function (msg) {
				res = msg.query.results.item;
				pageResult = '<ul class="feed">';
				for (i in res) {
					pageResult += "<li><span>"+ res[i]['pubDate'] +"</span><a href='"+ res[i]['link'] +"'>"+res[i]['title']+"</a><span>"+"</span></li>";
					if(i==2){break;}
				}
				pageResult += "</ul>";
				$(rssEl).html(pageResult);
			}
		});

	};
	if ($('.rssNews').size() != 0) {
		rssEl = $('.rssNews');
		$.ajax({
			type: "GET",
			url: "http://query.yahooapis.com/v1/public/yql",
			data: "q=SELECT%20*%20FROM%20feed%20WHERE%20url%3D'http%3A%2F%2Fnbwa.org%2Fthe-daily-brew%2Ffeed.xml'&format=json&diagnostics=true&callback=cbfunc",
			dataType: "jsonp",
			success: function (msg) {
				res = msg.query.results.item;
				pageResult = '<ul class="feed">';
				for (i in res) {
					pageResult += "<li><span>"+ res[i]['pubDate'].substr(0,17) +"</span><a href='"+ res[i]['link'] +"' target=\"_blank\">"+res[i]['title']+"</a><span>"+"</span></li>";
					if(i==7){break;}
				}
				pageResult += "</ul>";
				$(rssEl).html(pageResult);
			}
		});
	};
	


	
	
});




