//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');
		}
	}
}
//twittermodule
$.fn.tweetModule = function(theUrl){
	
	//username parser for the twitter strings
	String.prototype.parseUsername = function() {
		return this.replace(/[@]+[A-Za-z0-9-_]+/, function(u) {
			var username = u.replace("@","")
			return u.link("http://twitter.com/"+username);
		});
	};
	
	var tweets = [];
	var tModule = this;
	var lText = $('<h3 class="loadingText subHead">Loading Tweets...</h3>');
	var ul = $('<ul class="module" />');
	var sm;	
	
	var parse_date = function(date_str) {
      return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
    }
	
	//get relative time from twitter time
	var relativeTime = function(time_value) {
      var parsed_date = parse_date(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      var pluralize = function (singular, n) {
        return '' + n + ' ' + singular + (n == 1 ? '' : 's');
      };
      if(delta < 60) {
      return '1 minute ago';
      } else if(delta < (60*60)) {
      return pluralize("minute", parseInt(delta / 60)) + ' ago';
      } else if(delta < (24*60*60)) {
      return pluralize("hour", parseInt(delta / 3600)) + ' ago';
      } else {
      return pluralize("day", parseInt(delta / 86400)) + ' ago';
      }
    }
	
	var init = function(){
		tModule.append(lText);
		getTweets();
	}
	
	//retrieve tweets!!!
	var getTweets = function(){
		$.ajax({
			url: theUrl,
			type: 'GET',
			dataType: 'json',
			success: function(data, textStatus, xhr) {
				tweets = data;
				buildList();
			}
		});
	}
	
	//put those tweets in a ul and add that ul, if it's not there already
	var buildList = function(){
		for(var i=0; i<tweets.length;i++){
			var tweet = tweets[i];
			var text = '<p>' + tweet.text.parseURL().parseUsername() + '</p>';
			//var byLine = '<p class="byLine"><a href="http://www.twitter.com/'+tweet.from_user+'">@'+tweet.from_user.substring(0,10)+'</a> '+relativeTime(tweet.created_at)+'</p>';
			var byLine = '<p class="byLine">'+relativeTime(tweet.created_at)+'</p>'
			var li = $('<li>'+text+byLine+'</li>');
			$(li.find('a')).attr('target', '_blank');
			ul.append(li);
		}
		ul.hide();
		lText.fadeOut(200, function(){
			tModule.append(ul);
			ul.fadeTo(300,1);
			ul.sliderModule();
			lText.remove();
		});		
	}
	
	init();
}
//loader
$.fn.loaderGif = function(){
	var lg = $('<div class="ajaxLoader"></div>')
	lg.height(this.height());
	lg.width(this.width());
	lg.css({top:this.offset().top, left:this.offset().left});
	lg.insertAfter(this);
	
	var destroy = function(){
			lg.remove();
	}
	
	return{
		destroy:destroy
	}
}
//form validation
$.fn.validateForm = function(){
	var isValid = false;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; //regex
	var inputs = $(this.find('input, textarea'));
	var alertClass = '.formError';
	var requiredText = 'This field is required';
	var emailText = 'Please enter a valid email address';
	
	var validate = function(){
		for(var i = 0;i<inputs.length;i++){
			var inp = $(inputs[i]);
			if(inp.hasClass('required') && (inp.val() == '' || inp.val() == null)){//required field
				showAlert(inp, requiredText);
			}else if(inp.hasClass('email') && !emailReg.test(inp.val())){//email validation
				showAlert(inp, emailText);
			}else{
				clearAlert(inp);
			}
		}
		
		//if there are no invalid fields, submit that form!
		if(!inputs.hasClass('invalid')){
			this.submit();
		}
	}
	
	var showAlert = function(inp, txt){
		inp.addClass('invalid').next(alertClass).text(txt);
	}
	
	var clearAlert = function(inp){
		inp.removeClass('invalid').next(alertClass).text('');
	}
	
	//bind the click to the submit
	$(this.find('#submit')).bind('click', function(){validate(); return false;})
}

/*------------------------------------------------------------------
modules
------------------------------------------------------------------*/
var rumDropDown = 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 = 400;
	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 recipeFilter = function(type){
	//variables	
	var recipeGrid = $('#recipes ul.grid');
	var items = $(recipeGrid.find('li'));
	var filterList = $('#recipes ul.filters');
	var featuredModule = $(recipeGrid.find('.featured'));
	var listBox = $('#filterList');
	var marquee = $('#recipes').find('.marquee');
	var currentProfile = 'all';
	var currentRum = '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.
		recipeGrid.height(recipeGrid.height());
		
		items.each(function(){
			var j = $(this);
			var offsets = j.position();
			j.css({'top':offsets.top, 'left':offsets.left});
		}).each(function(){
			//i had to break it out into chained functions so that i could get the absolute positioning correct
			$(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 != currentRum){
				//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 = $('#recipes 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{
			currentRum = linkName;
		}
		
		//filter the data into the filteredData array	
		if(currentProfile != 'all' && currentRum != 'all'){
			items.each(function(){
				if($(this).hasClass(currentProfile) && $(this).hasClass(currentRum)){
					filteredData.push(this);
				}
			});
		}else if(currentProfile == 'all' && currentRum == 'all'){
			items.each(function(){
				filteredData.push(this);
			});
		}else if(currentProfile != 'all'){
			items.each(function(){
				if($(this).hasClass(currentProfile)){
					filteredData.push(this);
				}
			});
		}else if(currentRum != 'all'){
			items.each(function(){
				if($(this).hasClass(currentRum)){
					filteredData.push(this);
				}
			});
		}
				
		if(filteredData.length > 0 ){
			if($('#recipes').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();
			recipeGrid.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;
			recipeGrid.animate({'height':gridHeight});
		}
	}
	
	function stickyScroll(args){
		if(!args){ args = {} }
		var winScroll = $(window).scrollTop();
		var scrollTarg = winScroll - $('#recipes').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);
		// 		}
			
		//event handlers
		filterList.bind('click', function(e){ 
			filterClick(e, this);
			var targ = $(e.target);
			targ.parent().siblings().find('a').not(e.target).removeClass('selected');
			targ.addClass('selected');
			
			return false;
		});
		
		//this is a hack to fire the 'halloween' or 'holiday' click event for deep linking
		//we will need to find a more robust solution at some point in the very near future
		var onLoadSelected = $('.profile').find('.selected');
		if(!onLoadSelected.hasClass('all')){
		 	onLoadSelected.click();
		}

		$(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 ageGate = function(){
	// private vars
	var dom = $('#ageGate');
	var agi = $('#ageGateInner');
	var openBg = $('#agBgOpen');
	var qButton = $('#ageQuestion');
	var yesBtn = $(dom.find('a[href="#yes"]'));
	var noBtn = $(dom.find('a[href="#no"]'));
	var marquee = $('#marquee');
	var startHeight = dom.height();
	var hoverHeight = '172px';
	var endHeight = '487px';
	var dur = 500;
	
	var cookieCheck = function(){
		if(isOfAge == 'true'){
			dom.height(endHeight);
			getMarquee();
			agi.hide();
		}else{
			init();
		}
	}

	//private functions
	var init = function(){
		qButton.bind('mouseover', function(){ 
			openGate();
		});
		
		yesBtn.click(function(){
			//set the age gate cookie here
			$.cookie("donq_agegate", true, {path:'/'});
			getMarquee();
			return false;
		});
		
		noBtn.click(function(){
			closeGate();
			//unset the age gate
			$.cookie("donq_agegate", false, {path:'/'});
			return false;
		});
	};
	//get the marquee
	var getMarquee = function(){
		var dlg = dom.loaderGif();
		$.ajax({
			url: 'xhr/marquee/',
			datatype: 'HTML',
			success: function(data) {
				dom.unbind().css({background:'#121211'}).animate({height:endHeight}, {duration:700, easing:easingMethod, complete:function(){
					openBg.remove();
					var mq = new homeMarquee(data);
					
					window.setTimeout(function(){
						dlg.destroy();
						mq.init();
						},700);
					}
				});
				dom.find('.ageGateBtns').find('a').hide();				
			}
		});
	}
	
	var openGate = function(){
		dom.stop().animate({height:hoverHeight }, {duration:dur, easing:easingMethod});
		agi.stop().animate({height:'133px' }, {duration:dur, easing:easingMethod} );
		openBg.stop().fadeTo(dur, 1);
		qButton.stop().fadeTo(200, 0);
	}
	var closeGate = function(){
		dom.stop().animate({height:startHeight }, {duration:dur, easing:easingMethod});
		agi.stop().animate({height:'71px'}, {duration:dur, easing:easingMethod});
		openBg.stop().fadeOut(300, 0);
		qButton.stop().fadeTo(200, 1);
	}
	cookieCheck();
}

var flavorSwitcher = function(){
	var fs = $('#flavorSlider');
	var as = $('#awardsSlider');
	var fNav = $('#flavorNav');
	var imgs = $('#bottleHero').find('ul').children();
	var subHead = $('.awardsList').find('.subHead');
	var activeAwards = as.find('.active');
	var activeContent = fs.find('.active');
	var activeImages = fs.find('.active');
	var animDur = 600;
	var btn;
	var asHid = false;
	var currFlavor;
	
	var flavorClick = function(flavor){
		var content = $('#'+flavor+'Content');
		var awards = $('#'+flavor+'Awards').length > 0  ? $('#'+flavor+'Awards') : null;
		var image = $('#img_'+ flavor);
		activeAwards = as.find('.active');
		activeContent = fs.find('.active');
		activeImage = imgs.filter('.active');
		var otherContent = fs.find('.flavorContent').not(content);
		subHead.text('DonQ '+ flavor.capitalizeFirstLetter());

		var contentTo = fs.height() +50;
		var awardsTo = as.height() +50;
		
		//out with the old...
		activeContent.fadeOut(200.00, function(){content.fadeIn(animDur).addClass('active') }).removeClass('active');
		if(awards != null){
			activeAwards.fadeOut(200.00).removeClass('active');
			awards.delay(200).fadeIn(animDur).addClass('active');
			if(asHid){
				$('.awardsList, #allRums').delay(200).fadeTo(animDur, 1);
				asHid = false;
			}
			as.animate({height:awards.height()}, {duration:animDur});
		}else{
			$('.awardsList, #allRums').fadeTo(300, 0);
			asHid = true;
		}
		activeImage.css({'z-index':0}).fadeOut(200, function(){}).removeClass('active');
		image.css({'z-index':1}).delay().fadeIn(animDur).addClass('active');
		
		fs.animate({height:content.height()}, {duration:animDur});
	}
	
	var setStartFlavor =  function(){
		fs.find('.flavorContent').removeClass('active');
		as.find('.flavorAwards').removeClass('active');
		fNav.children('li').removeClass('selected');
		imgs.removeClass('active');
		
		$('#'+currFlavor+'Content').addClass('active');
		if($('#'+currFlavor+'Awards').position() != null){
			$('#'+currFlavor+'Awards').addClass('active');
		}else{
			$('.awardsList, #allRums').fadeTo(0,0);
			asHid = true;
		}
		$('#img_'+currFlavor).addClass('active');
		$('a[href="#'+currFlavor+'"]').parent().addClass('selected');
		subHead.text('DonQ '+ currFlavor.capitalizeFirstLetter());
	}
		
	var init = function(){
		if(window.location.hash){
			currFlavor = window.location.hash.substring('1');
			setStartFlavor();
		}else{
			currFlavor = fNav.find('.selected a').attr('href').substring(1);
		}
		fNav.bind('click', function(e){
			btn = $(e.target);
			btn.parent().addClass('selected');
			fNav.find('li').not(btn.parent()).removeClass('selected');
			var clickedFlav = btn.attr('href').substring(1);
			if(clickedFlav != currFlavor){
				flavorClick(clickedFlav);
				currFlavor = clickedFlav;
				window.location.hash = currFlavor
			}
			return false;
		});
		fs.find('.flavorContent').not('.active').hide();
		as.find('.flavorAwards').not('.active').hide();
		imgs.not('.active').hide();
		
		activeAwards = as.find('.active');
		activeContent = fs.find('.active');
		if(activeAwards.position() != null){
			console.log(activeAwards.attr('id'));
			as.height(191);	
		}
		fs.height(activeContent.height() + activeContent.position().top + 20);	
	}
	//initialize!!
	init();
}

function reportObj(theObj,willAlert) {
	var objProps = [];
	var propReport = "";
	var looper = 0;
	var position = 0;
	
	// loop through obj props, build array
	for(objItem in theObj[position]) {
		for(objItemProp in objItem) {
			objProps[looper] = objItemProp + ": " + objItem[objItemProp] + "\n";
			looper++;
		}   
		pos++;
	}   

	propReport = objProps.join(''); // join array
	
	if (willAlert){
		alert("[Debug]\n" + propReport);
	}else{
		return propReport;	
	}

}

var regionSwitcher = function(){
	var rs = $('.regionSwitcher');
	var lis = rs.find('a');
	
	var init = function(){
		var ck = currRegion;
		var theOne = $('.'+ck+'_link');
		if($('#wrapper').hasClass('events')){
			showEvents(ck);
		}
		$(theOne).addClass('selected');
		lis.bind('click', function(e){ rsClick(e.target); return false;}).not('.selected').fadeTo(0,.4);
		lis.hover(function(e){
			$(e.target).not('.selected').fadeTo(100, .65);
		},function(e){
			$(e.target).not('.selected').fadeTo(100, .4);
		});
	}
	
	var showEvents = function(reg){
		var noEvents = $('<h3 class="subHead" id="noEvents">Come back soon to check out events in your area!</h3>');
		var events = $('.'+reg+'_event');
		var otherEvents = $('.eventsList dl, #marquee').not(events);
		if(events.length <= 0){
			if(!document.getElementById('noEvents')){
				$(otherEvents).fadeOut(100);
				noEvents.insertBefore('.eventsList').delay(100).fadeIn(100);
			}
		}else{
			if(!document.getElementById('noEvents')){
				$(otherEvents).fadeOut(100, function(){$(events).fadeIn(200); $('#noEvents').remove();});
			}else{
				$('#noEvents').fadeOut(100, function(){$(events).fadeIn(200); $('#noEvents').remove();});	
			}
		}
	}
	
	var rsClick = function(targ){
		var t = $(targ);
		var reg = t.attr('href').substring(1);
		
		t.parent().siblings('li').find('a').fadeTo(50,.4).removeClass('selected');
		t.fadeTo(50,1).addClass('selected');
		
		//redirect to the home page
		//unless we're clicking on the events switcher
		//then just refresh the events content
		if($(t.closest('div')).hasClass('eventSwitcher')){
			showEvents(reg);
		}else{
			//set the region cookie
			$.cookie('donq_region', reg, {path:'/'});

			//unset the age gate
			$.cookie("donq_agegate", false, {path:'/'});
			
			var url = window.location.href;
			url = url.substring(url.indexOf('//')+2);
			rUrl = url.substring(0, url.indexOf('/'));
			rUrl = 'http://'+ rUrl;
			window.location.href = rUrl;
		}
	}
	init();
}

var videoOverlay = function(){
	var vidLink = $('#videoLink');
	var vidHref = vidLink.attr('href');
	var vidId = vidHref.substring(vidHref.lastIndexOf('/') + 1);
	var vidHolder = $('<div id="vidHolder"/>');
	
	var showVideo = function(id){
		ol.showOl();
		ol.body.addClass('full').bind('click', function(){destroyVideo();});
		vidId = id;
		var embedCode = '<object width="640" height="363"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+vidId+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id='+vidId+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="640" height="363"></embed></object>';	
		vidHolder.append(embedCode).insertAfter('#footer');
	}
	
	var getImage = function(){
		var hoverBtn = $('<span class="vidButton">+</span>')
		$.ajax({
			url:'http://vimeo.com/api/v2/video/'+vidId+'.json?callback=?',
			type: 'GET',
			dataType: 'jsonp',
			success:function(data){
				$(vidLink.find('img')).attr('src', data[0].thumbnail_medium).after(hoverBtn);
				//hoverBtn.insertAfter(vidLink);
			},
			error:function(){
				console.log('no go');
			}
		});
	}
	
	var destroyVideo = function(){
		ol.hideOl();
		ol.body.removeClass('full');
		vidHolder.empty().remove();
	}
	
	var init = function(){
		var links = $('#videoModule').find('a');
		getImage();
		
		links.bind('click',function(){
			showVideo(vidId);
			return false;
		}).hover(function(){
			vidLink.addClass('on');
		},function(){
			vidLink.removeClass('on');
		});
	}
	
	init();
}

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 textBgStyle = "url('images/home_marquee_text_bg.jpg') top left repeat-x #0D0D0C ";
	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('images/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('images/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 = [605, 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 = [603, 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();
}

var fbFans = function(){
	//TODO: replace this with the correct URL once the necessary facebook changes have been made
	var url = 'https://graph.facebook.com/cocacola&callback=?';
	$.ajax({
		url: url,
		dataType: 'json',	
		success: function(data) {
			$('#facebookModule .visitors strong').text(addCommas(data.fan_count));
		},
		error: function() {
			//$('#facebookModule .visitors strong').text('20,000');
		}
	});
	
}

/*------------------------------------------------------------------
initialize!!
------------------------------------------------------------------*/
$(document).ready(function() {
	ol = new overlay();
	var rdd = new rumDropDown($('#rumsNav'));
	var add = new rumDropDown($('#aboutTopNav'));
	var fm;
	
	if(document.getElementById('flavorSlider')){ var fs = new flavorSwitcher();}
	if(document.getElementById('ageGate')){ var ag = new ageGate(); }
	if(document.getElementById('recipes')){ var rf = new recipeFilter(); }	
	if(document.getElementById('videoModule')){ var vo = new videoOverlay();}
	if(document.getElementById('aboutMarqueeNav')){ var vo = new aboutIndexNav();}
	//if(document.getElementById('facebookModule')){var fbf = new fbFans();}
	var rs = new regionSwitcher();
	//if(document.getElementById('marquee')){var hm = new homeMarquee();}
	
	$('.module').sliderModule();
	if(document.getElementById('twitterModule')){
		$('#twitterModule').tweetModule('http://twitter.com/statuses/user_timeline/77068748.json?callback=?');
	}
	$('#bottlesHero li').highlightHover();
	$('#recipes ul.grid li').highlightHover();
	$('#relatedRecipesModule ul li').highlightHover();
	
	//attach form validation plugin
	$('#eventForm, #contactForm').validateForm();
	
	
	//check the region cookie and set the body class, for styling and hiding
	$('body').addClass(currRegion);
	
	//hide the facebook like buttons on load
	//to avoid that nasty white flash
	$('.fb_like').fadeTo(0,0).delay(1500).fadeTo(300, 1);
	
	//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'
		})
	});
});





