//global vars
var easingMethod = 'easeInOutCubic';
var ol;

/*------------------------------------------------------------------
custom plugins
------------------------------------------------------------------*/
//highlight hover
$.fn.highlightHover = function(){
	var highLight = $('<div class="highLight"/>');
	var beginOpacity = .15;
	var isNotIE = $.support.opacity;
	
	if(isNotIE){
		beginOpacity = .25;
	}
	
	highLight.fadeTo(0, beginOpacity);
	
	this.append(highLight);
	
	this.hover(function(){
		//over
		if(isNotIE){
			$(this).addClass('over').find('.highLight').stop().fadeTo(500, .6);
		}else{
			$(this).addClass('over').find('.highLight').stop().fadeTo(500, .45);
		}
	},function(){
		//out
		$(this).removeClass('over').find('.highLight').stop().fadeTo(500, beginOpacity);
	});
}
//slider module
$.fn.sliderModule = function(){
	var mod = this;
	var modHolder = $('<div class="modHolder"/>');
	var modInner = $('<div class="modInner"/>');
	var lis = mod.children('li');
	var liLength = lis.length;
	var itemWidth = lis.outerWidth();	
	var mId = mod.parent().attr('id');
	var lb;
	var rb;
	
	//this is because webkit in't returning the width css correctly
	var defModHolderWidth = 802;
	
	if(mId == 'timeLineModule'){
		itemWidth = 236;
	}
	var modWidth = itemWidth * liLength + 5;
	var target = 0;
	var index = 0;
	mod.width(modWidth);
	
	//if the content of the module is wider than the module, put it in a slider
	if(defModHolderWidth < modWidth){
		var numShown = 3;
		var buttonHeight = 32;
		if(mId == 'timeLineModule'){
			buttonHeight = 50;		
		}

		lb = $('<a class="leftButton">left</a>');
		rb = $('<a class="rightButton">right</a>');

		lb.css({height:buttonHeight}).addClass('off').bind('click', function(){slideIt('right'); return false;});
		rb.css({height:buttonHeight}).bind('click', function(){slideIt('left'); return false;});
		mod.wrap(modHolder).after(lb).after(rb).wrap(modInner).addClass('wrapped');
		numShown = Math.floor($('.modHolder').width()/itemWidth);
	}	
	var slideIt = function(dir){
		switch(dir){
			case 'left':
			if(index < liLength - numShown){
				target -= itemWidth ;
				index++;
			}
			break;
			
			case 'right':
			if(index > 0){
				target += itemWidth;
				index--;
			}
			break;
		}
		mod.stop().animate({marginLeft:target}, {easing:easingMethod, duration:700});
		if(index == 0){
			lb.addClass('off');
		}else{
			lb.removeClass('off');
		}
		
		if(index >= liLength - numShown){
			rb.addClass('off');
		}else{
			rb.removeClass('off');
		}
	}
}

/*------------------------------------------------------------------
modules
------------------------------------------------------------------*/
var DropDown = function(li){
	var dd = $(li.find('.dd'));
	var ddId = $(li).attr('id');
	var ul = dd.find('ul');
	var downX = '0px';
	var topY = '-320px';
	var dur = 300;
	var isDown = false;
	if(ddId == 'aboutTopNav'){
		downX = '-36px';
		topY = '-250px';
	}
		
	var hoverConfig = {
		interval:100,
		timeout:100,
		over:function(){show()},
		out:function(){hide()}
	}
	
	var init = function(){
		li.hoverIntent(hoverConfig);
	}
	
	var show = function(){
		ul.stop().animate({marginTop:downX}, {duration:dur, easing:easingMethod});
		dd.css({borderWidth:'1px'});
		ol.showOl();
	}
	
	var hide = function(){
		ul.stop().animate({marginTop:'-320px'}, {duration:dur, easing:easingMethod});
		dd.css({borderWidth:'0'});
		ol.hideOl();
	}
	
	init();
}

var ShopFilter = function(type){
	//variables	
	var ShopGrid = $('#Shop ul.grid');
	var items = $(ShopGrid.find('li'));
	var filterList = $('#Shop ul.filters');
	var featuredModule = $(ShopGrid.find('.featured'));
	var listBox = $('#filterList');
	var marquee = $('#Shop').find('.marquee');
	var currentProfile = 'all';
	var current = 'all';
	var currentData = items;
	var isFirstFilter = true;
	var minGridHeight = 800;
	
	if($.support.opacity){
		type='final'
	}else{
		type = 'ie';
	}

	
	function absolutize(){		
		//sets the grid height so that it doesn't collapse when the elements are positioned.
		ShopGrid.height(ShopGrid.height());
		
		items.each(function(){
			var j = $(this);
			var offsets = j.position();
			j.css({'top':offsets.top, 'left':offsets.left});
		}).each(function(){

$(this).css({position : 'absolute'});
		});
	}
	
	function filterClick(e, list){
		var href = $(e.target).attr('href');
		var linkName = href.substring(1);
		if(href){
			href = href.substring(1);
			//window.location.hash = href;
			if(isFirstFilter){
				var feat = $('li.featured');
				filterEm(linkName, list);
				marquee.fadeTo(300,0, function(){marquee.hide(); isFirstFilter = false;});
				feat.fadeTo(300, 0, function(){feat.remove() });
			}else if(href == 'all' || href != currentProfile && href != current){
				//marquee.slideUp(500, function(){filterEm(e, list)});
				//$('li.featured').fadeTo(500, 0, function(){$('li.featured').remove()});
				filterEm(linkName, list);
			};
		}
		return false;
	}
	
	function filterEm(linkName, list){
		
		//redefine the items list to NOT include the featured item
		items = $('#Shop ul.grid li');
		var rowLength = 4;
		var currentRow = -1;
		var item1 = $(items[0])
		var xOff = item1.width() + parseInt(item1.css('margin-right')) + parseInt(item1.css('margin-left'));
		var yOff = item1.height() + parseInt(item1.css('margin-bottom')) + parseInt(item1.css('margin-top'));
		var filteredData = [];
		var scrollPos = $(window).scrollTop();
		
		if(scrollPos != 0){
			$.scrollTo(0, {duration:500});
		}		
		
		//update the currently selected profile
		if($(list).hasClass('profile')){
			currentProfile = linkName;
		}else{
			current = linkName;
		}
		
		//filter the data into the filteredData array	
		if(currentProfile != 'all' && current != 'all'){
			items.each(function(){
				if($(this).hasClass(currentProfile) && $(this).hasClass(current)){
					filteredData.push(this);
				}
			});
		}else if(currentProfile == 'all' && current == 'all'){
			items.each(function(){
				filteredData.push(this);
			});
		}else if(currentProfile != 'all'){
			items.each(function(){
				if($(this).hasClass(currentProfile)){
					filteredData.push(this);
				}
			});
		}else if(current != 'all'){
			items.each(function(){
				if($(this).hasClass(current)){
					filteredData.push(this);
				}
			});
		}
				
		if(filteredData.length > 0 ){
			if($('#Shop').find('h3.noContentAlert')){
				$('h3.noContentAlert').fadeTo(400, 0, function(){$('h3.noContentAlert').remove()});
			}
			
			/*------------------------------------------------------------------
			this is where the animagic happens!!!
			------------------------------------------------------------------*/
			switch(type){
				case 'final':
				$(currentData).each(function(){
					var ranNum1 = Math.round(Math.random()*(300-600))+300;
					$(this).fadeTo(ranNum1, 0);
				});
				setTimeout(function() {
					$(filteredData).each(function(){
						var ranNum2 = Math.round(Math.random()*(400-600))+400;
						var ranNum3 = Math.round(Math.random()*(700-900))+700;
						
						var j = $(this);
						var ind = filteredData.indexOf(this);
						if(ind%rowLength == 0){currentRow+=1}
						var x = xOff * (ind%rowLength);
						var y = yOff * currentRow;
						ranNum3 -= (currentRow*100);
						
						j.stop().css({top: y, left:x-178}).animate({'left' : x}, {queue:false, duration:ranNum3, easing:easingMethod}).delay(ranNum3-300).fadeTo(200, 1);
					});
					//resize the grid					
					resizeGrid();
				}, 300);
				break;
				
				case 'ie':
				var goneX = 180;
				$(currentData).each(function(){
					var ranNum1 = Math.round(Math.random()*(500-700))+500;
					$(this).children().stop().animate({marginLeft:goneX}, {duration:ranNum1, easing:easingMethod}).find('img').animate({left:goneX + 250 }, {duration:ranNum1, easing:easingMethod});
				});
				setTimeout(function() {
					$(filteredData).each(function(){
						var ranNum2 = Math.round(Math.random()*(400-600))+400;
						var ranNum3 = Math.round(Math.random()*(700-900))+700;
						
						var j = $(this);
						var ind = filteredData.indexOf(this);
						if(ind%rowLength == 0){currentRow+=1}
						var x = xOff * (ind%rowLength);
						var y = yOff * currentRow;
						ranNum3 -= (currentRow*100);
						
						j.stop().css({top: y, left:x}).children().css({marginLeft : -200}).stop().animate({marginLeft : 10}, {queue:false, duration:ranNum3, easing:easingMethod}).find('img').stop().css({left : -275}).animate({left:25}, {duration:ranNum3, easing:easingMethod});
					});
					//resize the grid					
					resizeGrid();
				}, 300);
				break;
			}
			
	
		}else{
			items.not($(filteredData)).fadeTo(200, 0);
			
			var noContent = $('<h3 class="noContentAlert subHead"/>');
			noContent.text('This filter returned no results').hide();
			ShopGrid.before(noContent);
			noContent.fadeIn(200);
		}
	
		
		//set the currentData
		currentData = filteredData;
		
		//dynamically resize the grid
		var resizeGrid = function(){
			var gridHeight = (currentRow + 1) * $(items[0]).height() + 60;
			gridHeight = gridHeight >= minGridHeight ? gridHeight : minGridHeight;
			ShopGrid.animate({'height':gridHeight});
		}
	}
	
	function stickyScroll(args){
		if(!args){ args = {} }
		var winScroll = $(window).scrollTop();
		var scrollTarg = winScroll - $('#Shop').offset().top;
		var header = $('#header');

		if(scrollTarg >= -177 && scrollTarg < 0){
			scrollTarg = 10;
		}else if(scrollTarg > $('#content').height()-listBox.height()){
			//if (currentData.length > 9){
			// limit sticky scroll down only for items over 9
				scrollTarg = $('#content').height()-listBox.height() - 40;
		//	}	
		}
		if(args.animate == 'true'){
			listBox.stop().animate({'top':scrollTarg + 'px'}, {duration:500, easing:easingMethod});
		}else{
			listBox.css({'top':scrollTarg + 'px'});
		}

	}

	function init(){
		//absolutizing the grid
		absolutize();
		//check for hash to filter the data
		var hsh = window.location.hash
		// if(hsh != '' && hsh != 'all'){
		// 			var theLink = $('a[href='+hsh+']');
		// 			theLink.addClass('selected').parent().siblings().find('a').removeClass('selected');
		// 			filterEm(hsh.substring(1), filterList);
		// 		}
			



		$(window).bind('scrollstop', function(){
			stickyScroll({'animate':'true'});
		})
		
		featuredModule.bind('click', function(){window.location = $(featuredModule.find('.get')).attr('href');})
		
	}
	
	//initialize!!!!!
	init();
}

var overlay = function(){
	//private vars
	var ov;
	var isDown= false;
	
	//private functions
	var init = function(){
		if(!document.getElementById('overlay_black')){
			ov = $('<div id="overlay_black"/>');
			$('#footer').append(ov);
		}else{
			ov = $('#overlay_black');
		}
	}
	init();
		
	//public methods
	return {
		showOl:function(){
			ov.stop().height($(document).height() - 150).fadeTo(500,.9);
		},
		hideOl:function(){
			ov.stop().fadeTo(500,0, function(){ov.height('1px');});
		},
		body : ov,
		isDown : isDown
	}
};


var homeMarquee = function(list){
	var dots = document.getElementById('dots');
	var cw = 70;
	var ch = 15;
	var paper = Raphael(dots, cw, ch);
	var dotsArray = [];
	var blue;
	var controls = $('#marqueeControls');
	var links = controls.find('a');
	var marqs = $(list).find('li');
	var mImages = $('#marqImages');
	var marqDom = $('#marquee');
	var mText = $('#marqueeTextInner');
	var numDots = marqs.length;
	var prevInd = 0;
	var currInd = 0;
	var dur = 500;
	var iTime = 5000;
	var interval;
		var isFirst = true;
	
	var init = function(){
		showMarq(0);
		marqDom.fadeTo(700, 1).hover(
			function(){window.clearInterval(interval);},
			function(){
				marqueeGo();
			}
		);
		
		for(var i = 0; i<numDots;i++){
			var rad = 3;
			var xPos = cw/numDots * i + rad + 2;
			var	c = paper.circle(xPos, ch/2, rad);
			c.attr({
				'stroke':'#464543'
			});
			dotsArray.push(c);
		}
		
		blue = paper.circle(cw/numDots * 0 + rad + 1, ch/2, rad +1);
		blue.attr({
			'fill':'#189acb',
			'stroke':'none',
			'opacity':1
		});
		
		marqueeGo();		
	}
	
	var marqueeGo = function(){
		window.clearInterval(interval);
		interval = window.setInterval(function(){
			if(currInd < marqs.length -1){
				currInd++;
			}else{
				currInd = 0;
			}
			changeMarquee();
		}, iTime);
	}
	
	var showMarq = function(ind){
		var selected = $(marqs[ind]).clone();
		var text = $(selected.find('.text')[0]);
		var images = $(selected.find('.images')[0]);
				
		var margLeft;
		if(prevInd > currInd){
			margLeft = '-420px';
		}else{
			margLeft = '-20px';
		}
		if(selected.hasClass('slim')){
			$(images.find('img')[0]).css({left:'120px'});
			mText.css({background:'none'});
		}else{
			mText.css({background:"url('img/marquee_home_bg.png')"});
		}		
		//images.hide();

		//images.fadeIn(dur);
		if(!isFirst){
			// text.hide().css({marginLeft:margLeft});
			// text.insertBefore(controls);
			// text.stop().animate({marginLeft:'-228px'}, {queue:false, duration:dur, easing:easingMethod}).delay(400).fadeIn(200);
			text.insertBefore(controls);
			text.hide().delay(dur).fadeIn(dur);
			mImages.find('.slider').append(images);
			mImages.find('.slider').find('.images').animate({left:'-=1200px'}, {duration:dur, easing:easingMethod, complete:function(){
				$(mImages.find('.slider').find('.images')[-1]).remove();
			}});
			
		}else{
			mImages.find('.slider').append(images);
			text.insertBefore(controls);
		}
		isFirst = false;
	}
	
	var changeMarquee = function(){
		
		var currImgs = $(mImages.find('.images'));
		var currText = $(mText.find('.text'));
		
		var selected = $(marqs[currInd]).clone();
		var newText = $(selected.find('.text')[0]);
		var newImgs = $(selected.find('.images')[0]);
		
		var slider = mImages.find('.slider');
		var isSlim = selected.hasClass('slim');
		
		//set the positions for the new images
		var newPos;
		var oldPos;
		if(prevInd > currInd){
			newPos = '-1200px';
			oldPos = '1200px';
		}else{
			newPos = '1200px';
			oldPos = '-1200px';
		}
		
		//out with the old...
		currImgs.filter('.old').remove();
		currText.fadeOut(dur/2, function(){currText.remove();});
		currImgs.addClass('old').animate({left:oldPos}, {queue:false, duration:500, easing:'easeInOutCubic'}).fadeOut(dur);
		
		//in with the new!
		newText.hide().insertBefore(controls).delay(dur/2).fadeIn(dur/2);
		newImgs.css({left:newPos}).hide().appendTo(slider).animate({left:0}, {queue:false, duration:500, easing:'easeInOutCubic', complete:function(){
				//hide the text background if the marquee is the slim type
				if(isSlim){
					mText.css({background:'none'});
				}else{
				}
			}
		}).delay(dur/2).fadeIn(dur/2);
				
		if(isSlim){
			$(newImgs.find('img')[0]).css({left:'120px'});
		}else{
			//show the text background if the marquee is the slim type
			mText.css({background:"url('imag/marquee_home_bg.png')"});
		}
		
		//move blue dot
		var targX = dotsArray[currInd].attrs.cx;
		blue.attr({cx:targX});
	}
	
	links.bind('click', function(e){
		var dir = this.href.substring(this.href.lastIndexOf('#')+1);
		prevInd = currInd;
		switch(dir){
			case 'next':
			if(currInd < marqs.length - 1){
				currInd += 1;
			}else if(currInd == marqs.length -1){
				currInd = 0;
			}
			break;
			
			case 'prev':
			if(currInd > 0 ){
				currInd -= 1;
			}else if(currInd == 0){
				currInd	= marqs.length -1;
			}
			break;
		}
		if(prevInd != currInd){
			changeMarquee();
		}
		window.clearInterval(interval);		
		return false;
	});
	
	return{
		init:init
	}
}

var aboutIndexNav = function(){
	var an = $('#aboutMarqueeNav');
	var lis = an.find('li');
	var animVals = [];
	//the order of the values is liWidth, imgMarg, cpWidth
	var vals1 = [];
	var vals2 = [];
	var vals3 = [];
	var dur = 500;
	
	var init = function(){
		lis.bind('mouseenter', function(){ hoverOn($(this)); });
		an.bind('mouseleave', function(){hoverOff();});
	}
	
	var hoverOn = function(t){
		var cl = t.attr('class');
		var ind = cl.charAt(cl.length - 1);
		switch(ind){
			case '1':     
			vals1 = [600, 0, null];
			vals2 = [233, 0, null];
			vals3 = [363, -110, 205];
			break;
			
			case '2':
			vals1 = [362, -170, null];
			vals2 = [473, 0, null];
			vals3 = [363, -110, 205];
			break;
			
			case '3':
			vals1 = [362, -170, null];
			vals2 = [233, 0, null];
			vals3 = [590, 0, 440];
			break;
			
		}
		animVals = [vals1, vals2, vals3];
		moveEm(ind);
	}
	
	var hoverOff = function(){
		vals1 = [441, -90, null];
		vals2 = [316, 0, null];
		vals3 = [441, -110, 277];
		
		animVals = [vals1, vals2, vals3];
		moveEm();
	}
	
	var moveEm = function(ind){
		var curr = ind != null ? ind : 0;
		
		for(var i = 0;i<lis.length;i++){
			var l = $(lis[i]);
			var img = $(l.find('img'));
			var cp = $(l.find('.copy'));
			if(animVals[i][0] != null){
				l.stop().animate({width:animVals[i][0]}, {duration:dur+12, easing:easingMethod, queue:false});
			}
			if(animVals[i][1] != null){
				img.stop().animate({marginLeft:animVals[i][1]}, {duration:dur, easing:easingMethod, queue:false});
			}
			if(animVals[i][2] != null){
				cp.stop().animate({width:animVals[i][2]}, {duration:dur, easing:easingMethod, queue:false});
			}
			
			if(i != curr-1 && curr != 0 ){
				l.fadeTo(dur, .4);
			}else{
				l.fadeTo(dur, 1);
			}
		}
	}
	init();
}



/*------------------------------------------------------------------
initialize!!
------------------------------------------------------------------*/
$(document).ready(function() {
	ol = new overlay();
	var rdd = new DropDown($('#Nav_2'));
	var add = new DropDown($('#aboutTopNav'));
	var fm;
	
	
	if(document.getElementById('Shop')){ var rf = new ShopFilter(); }	
	if(document.getElementById('aboutMarqueeNav')){ var vo = new aboutIndexNav();}
	//if(document.getElementById('marquee')){var hm = new homeMarquee();}
	
	$('.module').sliderModule();
	
	$('#Shop ul.grid li').highlightHover();
	$('#relatedRecipesModule ul li').highlightHover();
	

	
	
		
	//svg for the hover highlights
	$('.highLight').each(function(){
		var t = $(this);
		var tw = t.width();
		var th = t.height();
		var paper = Raphael(this, tw, th);
		var c = paper.circle((tw-18)/2, th+18, tw/1.8);
		var opac = 1;
		var end;
		var theFill = 'r(0.5, .5)#CCC-#121211';
		var location = $(t.parent().parent());
		
		if($.support.opacity){
			// if not IE
			opac = 0;
			theFill = 'r(0.5, .5)#C5C5C4-#121211';
		}else{
			//if IE
			if(location.hasClass('grid')){
				theFill = 'r(.5, .5)#CCC-#5B5A58-#504F4C-#3F3F3C-#2A2927-#121211-#111110';
			}else if(location.hasClass('module')){
				theFill = 'r(.5, .5)#AAA-#666-#454545-#333-#282827-#1B1A19';
			}else{
				theFill = 'r(.5, .5)#999-#454545-#0F0F0E';
			}
			opac = 1;
		}
		c.attr({
			'fill':theFill,
			'fill-opacity':opac,
			'stroke':'none'
		})
	});
});





