/* Author: 
josh ellington
*/

$(function() {
    function checkForYouTubeUrl(){
    
        if ( $('a[href*="youtube.com/watch"]').length ){
            
            if($('#how-to-pour-video').length){
            }else{
                $('body').append('<div id="how-to-pour-video" class="video_modal modal alt-modal small-modal" style="width:860px;height:650px;"></div>');
            }
            $('a[href*="youtube.com/watch"]').die();
            $('a[href*="youtube.com/watch"]').live('click', function() {
               var src = $(this).attr('href');
               var youtubeID = src.replace('http://www.youtube.com/watch?v=', '');
               var title = $(this).attr('title');
               var html = '<a href="#" class="close fxopacity"></a><div class="send-prost-content"><h3>'+title+'</h3><iframe title="YouTube video player" width="800" height="500" src="http://www.youtube.com/embed/'+youtubeID+'?rel=0" frameborder="0" allowfullscreen></iframe>'
                
                log(title);
           
                $('#how-to-pour-video').lightbox_me({
                    onLoad: function() {
                        $('#how-to-pour-video').html(html);
                    },
                    onClose: function() {
                        $('#how-to-pour-video').empty();
                    },
                    centered: true
                });
                return false;
                $console.log(html);
            }); 
    
        }
    }

    checkForYouTubeUrl();

	$('a.button, a.fxopacity').live('hover', function(event) {
		if ( event.type == 'mouseenter' ) {
			$(this).stop(true,false).animate({'opacity': 0.7}, 300);
		} else {
			$(this).stop(true,false).animate({'opacity': 1}, 500);
		}
	});
	
	if ( $('#hero').length ) {
		$('#hero').cycle({
			fx: 'none',
			speed: 1500,
			timeout: 7000,
			pager: '#hero-nav'
		});
	}

	$('#home-beers .col-ten').live('hover', function(event) {
		if ( event.type == 'mouseenter' ) {
			$(this).find('span.hover').stop(true,false).animate({'opacity': 1}, 300);
		} else {
			$(this).find('span.hover').stop(true,false).animate({'opacity': 0}, 500);
		}
	});
	
	var len = $('.item').length;
	if(len) {
		var supadupa = len * 102;
		$('#scrollarea').css('width',supadupa);
		$(".scrollable").scrollable({onSeek:function(){
			var i = this.getIndex();
			if(i >= len-10){
				$('#next_set').addClass('disabled');
			}else{
				$('#next_set').removeClass('disabled');
			}
		}});
	}

	if ( $('#filter-beers-list').length ) {
	
		setupBeers();
		
		$('#filter-tabs a').live('click', function() {
			var id = $(this).attr('id');
			var type = id.replace('-filter-load','');
			var slide = id.replace('-load','');
			var dest = id.replace('-load','-wrap');
			
			$('#filter-tabs a').removeClass('active');
			$(this).addClass('active');
			
			$('#filter-slider').removeClass('abv').removeClass('ibu');
			$('#filter-slider').addClass(type);
			
			$('#filter-slider > div').not('.hidden').hide(0, function() {
				resetBeers();
				
				$('#filter-slider > div').addClass('hidden');
				$('#'+dest).removeClass('hidden').show();
				
				var minMax, buffer;
				
				if ( type == 'color' ) {
					minMax = minMaxColor;
					buffer = 5;
				} else if ( type == 'abv' ) {
					minMax = minMaxAbv;
					buffer = 0.5;
				} else {
					minMax = minMaxIbu;
					buffer = 10;
				}
				
				//log(minMax);
				
				$('#'+slide).slider({
					min: Array.min(minMax),
					max: Array.max(minMax),
					animate: true,
					slide: function(event,ui) {
						//log(ui.value);
						filterBeer(ui.value,type,buffer);
					}
				});
				
			});
			
			return false;
		});
		
		$('#color-filter').slider({
			min: Array.min(minMaxColor),
			max: Array.max(minMaxColor),
			animate: true,
			slide: function(event,ui) {
				//log(ui.value);
				filterBeer(ui.value,'color',5);
			}
		});
	
		$('.col-four a').live('click', function() {
			if ( !$(this).hasClass('selected') ) {
				window.location.hash = $(this).attr('rel');
				
				$('.col-four').removeClass('selected');
				//$(this).parent().parent().addClass('selected');
				$(this).parent().addClass('selected');
				
				var color = $(this).parent().find('.filter-beer-border').css('background-color');
				$('html, body').animate({scrollTop:0}, 'fast');
			}
			return false;
		});
		
		var beerInfo =  $('#beer-info');
		
		$(window).hashchange( function(){
			var href = window.location.hash.substr(1);
			if ( href.length ) {
				$('#loading').show();
				if ( !$('.col-four.selected').length ) {
					$('#filter-beers-list .col-four a[rel="'+href+'"]').parent().parent().addClass('selected');
				}
				$('.col-four').find('span.filter-beer-selected').hide();
				$('.col-four.selected').find('span.filter-beer-selected').show();
				
				$(beerInfo).css('opacity', 0.3);
				$(beerInfo).load(href+' #single-beer-content', function(d) {
					$('.big-beer-text').bigtext();
					$(beerInfo).find('img:first').load(function() {
						$('#loading').hide(0, function() {
							$(beerInfo).animate({'opacity': 1}, 300);
							checkForYouTubeUrl();
						});
					});
				});
			}
			return false;
		});
		
		if ( window.location.hash.length ) {
			$(window).hashchange();
			
		}
	
		var prostHtml = $('#send-prost').html();
	
		$('.send-prost').live('click', function() {
			$('#send-prost').lightbox_me({
				onLoad: function() {
					$('#send-prost').html(prostHtml);
				},
				onClose: function() {
					$('#send-prost').empty();
				},
				centered: true
			});
			return false;
		});
		/*
		var pourHtml = $('#how-to-pour-video').html();
		
		$('.how-to-pour').live('click', function() {
			$('#how-to-pour-video').lightbox_me({
				onLoad: function() {
					$('#how-to-pour-video').html(pourHtml);
				},
				onClose: function() {
					$('#how-to-pour-video').empty();
				},
				centered: true
			});
			return false;
		});
		*/
		$('.share-beer').live('click', function() {
			
			var current = $('.col-four.selected').html();
			
			if ( !current ) {
				current = '<div class="widmer-logo"><img src="'+$('#logo img').attr('src')+'" /></div>';
			}
			
			$('#share-buttons .share-left').html(current);
			$('#share-buttons').lightbox_me({
				centered: true
			});
			
			return false;
		});
		
		$('.fb-share-beer').live('click', function(e) {
			var name = $('.hero-text-big').text();
			var link = location.href;
			var picture = $('#filter-beers-list div.selected span.filter-beer-pour img').attr('src');
						
			var caption = $('.hero-text-small').text();
			var description = $('.beer-info-desc p').text();
			if ( !name ) {
				name = 'Widmer Brothers Brewing - Beer';
				link = location.href;
				picture = $('#logo img').attr('src');
				caption = '';
				description = '';
			}
			fbShare(name,link,picture,caption,description);
			return false;
		});
		
		$('.tw-share-beer').live('click', function() {
			var name = 'Prost! to ' + $('.hero-text-big').text();
			var link = escape(location.href);
			if ( !name ) {
				name = 'Widmer Brothers Brewing - Beer';
			}
			window.open('http://twitter.com/?status='+name+' - '+link);
			return false;
		});
		
		//Validate Prost Form and Send
	    $('#send-my-prost').live('click', function(e){
	        validate_prost();
	        return false;
	    });
	
	}
	
	if ( $('#media-wrapper').length ) {
	
		var months = ['January','February','March','April','May',
'June','July','August','September','October','November','December'];
	
		$.getJSON('/inc/youtube.php', function(d) {
			
			var mediaList = $('#media-list-container');
			
			$.each(d.data.items, function(i,item) {
				//log(item);
				
				var dateString = item.updated.toString();
				var date = new Date(item.updated);
				
				var dateYear = dateString.slice(0,4);
				var dateMonth = parseInt(dateString.slice(5,7),10)-1;
				var dateDay = dateString.slice(8,10); 
					
				   $(mediaList).append('<div class="media-entry"><a href="#" rel="'+item.id+'">\
                    <img src="'+item.thumbnail.hqDefault+'" width="175" /></a><h4>'+item.title+'</h4>\
                    <h5>'+item.viewCount+' views / '+months[dateMonth]+' '+dateDay+', '+dateYear+'</h5>\
                    <span id="desc" style="display:none;">'+item.description+'</span></div>');
			});
			
			var divs = $('#media-list-container div');
			
			for(var i = 0; i < divs.length; i+=2) {
				divs.slice(i, i+2).wrapAll("<div class='new'></div>");
			}
			
			// initialize scrollable with mousewheel support
		    $(".video-scrollable").scrollable({ vertical: true });
			
			$('#media-list-container a:first').trigger('click');
			
		});
	
		$('#media-list-container a').live('click', function() {
			var item = $(this).parent();
			buildMediaPlayer(item);
			return false;
		});
	
	}
	
	if ( $('#page-brewery').length ) {
	
		$('.brewery-list a').live('click', function() {
			log($(this).attr('rel'));
			$('.brewery-list a').removeClass('selected');
			$(this).addClass('selected');
			$('#brewery-page-content .tabbed').not('.hidden').addClass('hidden');
			$('#'+$(this).attr('rel')).removeClass('hidden');
			return false;		
		});
	
		$('.brewery-tab a').live('click', function() {
			window.location.hash = $(this).attr('rel');
			$('.brewery-tab').removeClass('selected');
			$(this).parent().parent().addClass('selected');
			
			return false;
		});
		
		$('.brewery-list a').live('click', function() {
			if ( $(this).attr('href') == '#' ) {
				
			} else {
				$('.brewery-list a').removeClass('selected');
				window.location.hash = 'brewer/'+$(this).attr('rel');
			}
			return false;
		});
	
		var defaultHeader = $('#brewery-header img').attr('src');
	
		$(window).hashchange( function(){
			var hash = window.location.hash.substr(1);
			//log(hash);
			if ( hash != '' ) {
				$('#loading').show();
				
				$('#brewery-ajax-content').load(hash+' #brewery-page-content', function() {
				
					if ( $('#brewery-ajax-content #brewery-header-new').length ) {
						$('#brewery-header img').attr('src', $('#brewery-header-new img').attr('src'));
					} else {
						$('#brewery-header img').attr('src', defaultHeader);
					}
				
					$('#loading').hide();
					
					if ( hash.indexOf('brewer') > -1 || hash.indexOf('brewers') > -1 ) {
						$('.brewery-tab').removeClass('selected');
						$('.brewery-tab a[rel="brewers"]').parent().parent().addClass('selected');
					}
					
					if ( hash.indexOf('/') == -1 ) {
						$('.brewery-tab').removeClass('selected');
						$('.brewery-tab a[rel="'+hash+'"]').parent().parent().addClass('selected');
					} else {
						var selected = hash.replace('brewer/', '');
						$('.brewery-list a[rel="'+selected+'"]').addClass('selected');
						log(selected);
					}
					checkForYouTubeUrl();
					changeBorderCornersLoad();
					
				});
			}
			return false;
		});
		
		if ( window.location.hash.length ) {
			$(window).hashchange();
		}
	
	}
		
	if ( $('#history-wrapper').length ) {
	
		slickSlideInit('slick-slideshow-2', 'slide-show-nav', 'slide-show-start');
	
	}
   if ( $('#process-wrapper').length ) {
    
        slickSlideInit('slick-slideshow', 'slide-show-nav', 'slide-show-start');
    
    }
	
	
	if ( $('#events-calendar').length ) {
		
		if ( location.hash.length ) {
			
			$(window).load(function() {
				var toLoad = $('.event[rel="'+location.hash.substr(1)+'"], .event-latest[rel="'+location.hash.substr(1)+'"]');
				loadEvent(toLoad);
			});
			
		}
		
		$('.event, .event-latest').live('click', function() {
			
			loadEvent($(this));
			return false;
			
		});
		
		function loadEvent(obj) {
			var current = $(obj).find('.event-modal-content').html();
			var hash = $(obj).attr('rel');
			
			$('#event-modal').html(current).prepend('<a href="#" class="close fxopacity"></a>');
			
			$('#event-modal').lightbox_me({
				centered: true,
				onLoad: function() {
					location.hash = hash;
					
					$('.fb-share-event').live('click', function() {
						var name = $('#event-modal .event-modal-top h3').text();
						var link = location.href;
						var picture = $('#event-modal .event-modal-desc img').attr('src');
						var caption = $('#event-modal .event-modal-top h4').text()+' / '+$('#event-modal .event-modal-top h5').text();
						var description = $('#event-modal .event-modal-desc p').text();
						fbShare(name,link,picture,caption,description);
						return false;
					});
					
					$('.tw-share-event').live('click', function() {
						var name = $('#event-modal .event-modal-top h3').text();
						var link = escape(location.href);
						var caption = $('#event-modal .event-modal-top h4').text()+' / '+$('#event-modal .event-modal-top h5').text();
						window.open('http://twitter.com/?status='+name+' - '+link);
						return false;
					});
					
					return false;
				}
			});
		}
		
	}
	
	
	//
	// Age Gate control
	//
	
	$('#age-gate-yes').live('click', function(e){
	    $.cookie("widmer-age-verification", 1, {expires: 999, path: '/'});
		location.reload();
	    return false;
	});
	
	$('#age-gate-no').live('click', function(e){
	    $.cookie("widmer-age-verification", 0, {expires: -1, path: '/'});
	    $("#age-gate-content").html("<p>You must be of legal drinking age to visit this site.</p>")
	    return false;
	});
	
	//Beer Filter Explanation Tooltips
	var tabs = $('#filter-tabs a');
	if(tabs.length) {
		tabs.each(function() {
			var tip = '';
			if($(this).is('#color-filter-load'))
				tip = '<span>COLOR</span>Color intensity measures the attenuation of light as it passes through beer.'; //Explain Beer Color
			else if($(this).is('#ibu-filter-load'))
				tip = '<span>BITTERNESS</span>Hops used during brewing provide the bitterness in beer.'; //Explain Beer Bitterness IBU
			else if($(this).is('#abv-filter-load'))
				tip = '<span>ALCOHOL BY VOLUME</span>The standard measure of the quantity of ethanol, expressed as a percentage of the total volume.';   //Explain Beer ABV
			$(this).qtip({
			   content: tip,
			   show: 'mouseover',
			   hide: 'mouseout',
			   position: {
			      corner: {
			         target: 'topRight',
			         tooltip: 'bottomLeft'
			      }
			   },
			   style : {
			   	   padding: 5,
				      background: '#101010',
				      color: '#FFF',
				      textAlign: 'left',
				      border: {
				         width: 1,
				         radius: 10,
				         color: '#101010'
				    },
				    tip: 'bottomLeft'
			   }
			});
		});
	}
	
});

$(window).load(function() {
	
	if ( !$('html.ie7, html.ie8').length ) {
		$('.hero-text, .event-hero, .big-beer-text, #blog-headline').bigtext().animate({'opacity': 1}, 500);
	}
	
});


function buildMediaPlayer(item) {

	var id = $(item).find('a').attr('rel');
	var title = $(item).find('h4').text();
	var desc = $(item).find('span#desc').text();
	var meta = $(item).find('h5').text();

	if ( $('#media-player iframe').length ) {
		$('#media-player iframe').attr('src', 'http://www.youtube.com/embed/'+id+'?wmode=transparent&autoplay=1&showinfo=0');
	} else {
		$('#media-player').html('<iframe title="YouTube video player" width="765" height="460" src="http://www.youtube.com/embed/'+id+'?wmode=transparent&showinfo=0" frameborder="0" allowfullscreen></iframe>');
	}
	
	// $('#media-meta h2').text(title);
	$('#media-video-title h2').text(title);
	if(title.length > 60){$('#media-video-title h2').css('line-height', '30px')}else{$('#media-video-title h2').css('line-height', '60px')};
	$('#media-meta p').text(desc);
	$('#media-meta .media-view-date').text(meta);

	var mcHeight = $('#media-content').outerHeight();
	$('#media-list, .video-scrollable').height(mcHeight);

}


// Store initial beer values to reduce dom lookup on change
var minMaxColor = [];
var minMaxAbv = [];
var minMaxIbu = [];

var beers = {};

function setupBeers() {

	$('#filter-beers .col-four').each(function() {
	
		var color = $(this).attr('data-color');
		var abv = $(this).attr('data-abv');
		var ibu = $(this).attr('data-ibu');
		
		var name = $(this).find('a').attr('rel');
	
		beers[$(this).index()] = {name: name, color: color, abv: abv, ibu: ibu};
		
		if ( color ) { minMaxColor.push(parseFloat(color)); }
		if ( abv ) { minMaxAbv.push(parseFloat(abv)); }
		if ( ibu ) { minMaxIbu.push(parseFloat(ibu)); }
		
	});
	
	//log(beers);
	//log(minMaxColor);

}

// Show accepted beers on slider change
function filterBeer(sliderValue,type,buffer) {
    
    if($('#filter-tabs a').eq(1).hasClass('active')){
        $('#filter-beers #current-value').css({'display':'block','right':'325px'}).html(sliderValue+' IBU');
    }else if($('#filter-tabs a').eq(2).hasClass('active')){
        $('#filter-beers #current-value').css({'display':'block','right':'270px'}).html(sliderValue+'%');
    }else if($('#filter-tabs a').eq(0).hasClass('active')){
        $('#filter-beers #current-value').css({'display':'block','right':'430px'}).html(sliderValue+' SRM');
    };
    
    //log('sliderValue: '+sliderValue);
    
	var high = sliderValue + buffer;
	var low = sliderValue - buffer;

	//log(high+', '+low);

	$.each(beers, function(i,v) {
		
		i = i - 1;
		
		var div = $('#filter-beers-list div.col-four').eq(i);
		
		//log(div.attr('class'));
		
		if ( v[type] < high && v[type] > low ) {
			
			$(div).stop(true,false).animate({'opacity': 1}, 300);
		
		} else {
		
			$(div).stop(true,false).animate({'opacity': 0.5}, 300);
		
		}
		
	});

}

function resetBeers() {

	$('#filter-beers-list div.col-four').stop(true,false).animate({'opacity': 1}, 300);
	$('#color-filter, #ibu-filter, #abv-filter').slider('destroy');
	$('#filter-beers #current-value').css('display', 'none');

}

// Array functions
Array.max = function( array ){
    return Math.max.apply( Math, array );
};
Array.min = function( array ){
    return Math.min.apply( Math, array );
};



function validate_prost(){
    $('#prost-errors').html('');
    var errors = ''
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var name = $('input#firstname').val();
    var email = $('input#email').val();
    var prost = escape($('input#prost').val());
    var friends = $('input#friends').val();
    var beer = window.location.hash.substr(1);
    
    if(prost == ''){
        $('#prost-errors').append('<p>Please Enter a Prost</p>')
    }
    if(name == ''){
        $('#prost-errors').append('<p>Please Enter your Name</p>')
    }
    if(reg.test(email) == false) {
          $('#prost-errors').append('<p>Please Enter a valid Email</p>')
       }
    if($('#prost-errors').html() == ''){
        var dataString = 'prost='+ prost +'&firstname='+ name + '&email=' + email + '&beer=' + beer + '&friends=' + friends;
        
        log(dataString);
        
        $.ajax({  
          type: "POST",  
          url: "/inc/prostMail.php",  
          data: dataString,  
          success: function(d) {  
            $('#prost-form').html('<h2>Thanks for your Prost!</h2>') 
            log(d);
          }  
        });  
    }
}


function fbShare(name,link,picture,caption,description) {
	FB.ui(
   {
     method: 'feed',
     name: name,
     link: link,
     picture: picture,
     caption: caption,
     description: description,
     actions: {name: 'View on widmer.com', link: link}
     //message: 'Facebook Dialogs are easy!'
   },
   function(response) {
     if (response && response.post_id) {
       alert('Thanks for sharing!');
     } else {
       //alert('Post was not published.');
     }
   }
 );
}
