/**
 * @author Taylor Eke
 */

var fw = 1;
var cn = false;

function newWindowSize() 
{
	var h = $(window).height();
	var w = $(window).width();

	//console.log("TEST: "+$('#backstretch img').attr('src'));

	if ( w > 1900 ) 
	{
		if (fw != 1) cn = true;
		fw = 1;
		
		if (cn)
		{
			cn = false;
			var x = $('#backstretch img').attr('src');
			$("#backstretch").remove();
			$('#backstretch img').width("2560px");
			$('#backstretch img').height("1696px");
			$.backstretch(x.replace(/\d\d\d\d\px.jpg/,'2560px.jpg'), {speed: 0});
		}
    }
	else if ( w > 2580 ) 
	{
		if (fw != 2) {cn = true; }
		fw = 2;
		
		if (cn)
		{
			cn = false;
			var x = $('#backstretch img').attr('src');
			$("#backstretch").remove();
			$('#backstretch img').width("2000px");
			$('#backstretch img').height("1325px");
			$.backstretch(x.replace(/\d\d\d\d\px.jpg/,'2000px.jpg'), {speed: 0});
		}
	}
	else if ( w > 1280 ) 
	{
		if (fw != 3) { cn = true; }
		fw = 3;
		
		if (cn)
		{
			cn = false;
			var x = $('#backstretch img').attr('src');
			$("#backstretch").remove();
			$('#backstretch img').width("1680px");
			$('#backstretch img').height("1113px");
			$.backstretch(x.replace(/\d\d\d\d\px.jpg/,'1680px.jpg'), {speed: 0});
		} 
	}
	else
	{
		if (fw != 4) { cn = true; }
		fw = 4;
		
		if (cn)
		{
			cn = false;
			var x = $('#backstretch > img').attr('src');
			$("#backstretch").remove();
			//$('#backstretch > img').width("1280px");
			//$('#backstretch > img').height("848px");
			//$('#backstretch > img').attr('src', $('#backstretch > img').attr('src').replace(/\d\d\d\d\px.jpg/,'1280px.jpg'));
			$.backstretch(x.replace(/\d\d\d\d\px.jpg/,'1280px.jpg'), {speed: 0});
		}
	}
}

$(document).ready(function ()
{
	//newWindowSize();
	
	//
	// Age Gate control
	//
	
	$('#age-gate-yes').live('click', function(e){
	    $.cookie("redhook-age-verification", 1, {expires: 999, path: '/'});
		location.reload();
	    return false;
	});
	
	$('#age-gate-no').live('click', function(e){
	    $.cookie("redhook-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;
	});
	
	$('.portsmouth').load(function(){
		$(this).css('display', 'none');
	});
	
	var address = $('p.address');
	if(address.length) {
		address.click(function(){
			window.open('http://maps.google.com?q='+encodeURIComponent(address.text()),'map');
		});
	}
	
	
	/** Input Box Selections **/
	swap_val = [];  
	$("input:text").each(function(i){ 
		swap_val[i] = $(this).val();  
		$(this).focusin(function(){
		if ($(this).val() == swap_val[i]) {
			$(this).val("");  
		}  
		}).focusout(function(){  
			if ($.trim($(this).val()) == "") {  
			$(this).val(swap_val[i]);  
		}  
		});  
	}); 
	
/** Hompage Overlays **/
	$('#homeList li:not(.twitter) > div').animate({'opacity' : 0}, 0);
	$('#homeList li:not(.twitter)').hover(
		function() {
			$(this).children('div').stop(true,false)
			.animate({'opacity' : 1}, 500);
		},
		function() {
			$(this).children('div').stop(true,false)
			.animate({'opacity' : 0}, 500);
		}
	);	
/** Blog Overlays **/
	$('#blog ul li div').animate({'opacity' : 0}, 0);
	$('#blog ul li').hover(
		function() {
			$(this).children('div').stop(true,false)
			.animate({'opacity' : 1}, 500);
		},
		function() {
			$(this).children('div').stop(true,false)
			.animate({'opacity' : 0}, 500);
		}
	);	
	
/** Image Gallery Display View - Lightbox **/
	var imgCount = $('.imgGallery img').length;
	var currentIndex = -1;
	
	if(imgCount) 
	{
		$('.imgGallery img').click(function ()
		{
			if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) ){
		 		var image = $(this).parent().attr('rel');
		 		window.open(image,'lightimage');
		 	}
		 	else {
				$("#captionPhoto").hide();
				currentIndex = $('.imgGallery img').index(this);
				var image = $(this).parent().attr('rel');
				var imgTitle = $(this).parent().attr('title');
				$('body').append('<div id="lightBoxPhoto"></div>');
				$('body').append('<div id="lightbox"><img class="lightboxImage" src="'+image+'" /><p id="captionPhoto">'+imgTitle+'<br /><br /><small>Right click and choose \'Save Image As...\' to save</small></p><a id="closePhoto" href="#close">X</a><a id="lastPhoto" href="#prev">Prev<div>&nbsp;</div></a><a id="nextPhoto" href="#next">Next<div>&nbsp;</div></a></div>');
				
				$('#lightbox').append("<img src='/wp-content/themes/redhookbrewing/images/redhook-loading-icon.gif' class='loader' style='display: none;' />");
				$(".loader").show();
				
				$('img.lightboxImage').load(function() 
				{
					var w = $('img.lightboxImage').width();
					var h = $('img.lightboxImage').height() + 57;
					if(h > $(window).height()-70) {
						var newImage = '/wp-content/themes/redhookbrewing/timthumb.php?src=';
						newImage += $('img.lightboxImage').attr('src');
						newImage += '&h='+($(window).height()-70);
						$('img.lightboxImage').attr('src', newImage);
						h = $('img.lightboxImage').height() + 57;
					}
					$("#lightbox").animate({height:h+'px', width:w+'px'}, 300, function()
					{
						$(".loader").fadeOut();
						$('img.lightboxImage').fadeIn("slow", function(){$("#captionPhoto").show();});
					});
					
					$('img.lightboxImage').unbind("load");
				});
				
				
				$('#lightBoxPhoto').css({
					'width' : $(document).width(),
					'height' : $(document).height(),
					'margin' : 0,
					'padding' : 0
				}).animate({'opacity': 0}, 0).animate({'opacity':.59},500);
				
				return false;
			}
		});
		
		function next() 
		{
			$("#captionPhoto").hide();
			
			$('img.lightboxImage').fadeOut(400, function() 
			{
				//alert((currentIndex == $('.imgGallery img').length-1));
				
				if(currentIndex == $('.imgGallery img').length-1) currentIndex = -1; 
				currentIndex++;
				
				image = $('.imgGallery img').eq(currentIndex).parent().attr('rel');
				imgTitle = $('.imgGallery img').eq(currentIndex).parent().attr('title');
				$('img.lightboxImage').attr('src', image);
				$('#captionPhoto').html(imgTitle+'<br /><br /><small>Right click and choose \'Save Image As...\' to save</small>');
				
				$(".loader").fadeIn();

				$('img.lightboxImage').load(function() 
				{
					var w = $('img.lightboxImage').width();
					var h = $('img.lightboxImage').height() + 57;
					if(h > $(window).height()-70) {
						var newImage = '/wp-content/themes/redhookbrewing/timthumb.php?src=';
						newImage += $('img.lightboxImage').attr('src');
						newImage += '&h='+($(window).height()-70);
						$('img.lightboxImage').attr('src', newImage);
						h = $('img.lightboxImage').height() + 57;
					}
					$("#lightbox").animate({height:h+'px', width:w+'px'}, 300, function()
					{
						$(".loader").fadeOut();
						$('img.lightboxImage').fadeIn();
						$("#captionPhoto").show();
					});
					
					$('img.lightboxImage').unbind("load");
				});
			});
			
			return false;
		}
		
		function last() 
		{
			$("#captionPhoto").hide();
			
			$('img.lightboxImage').fadeOut(400, function() 
			{
				if(currentIndex == 0) currentIndex = imgCount; 
				currentIndex--;
				
				image = $('.imgGallery img').eq(currentIndex).parent().attr('rel');
				imgTitle = $('.imgGallery img').eq(currentIndex).parent().attr('title');
				$('img.lightboxImage').attr('src', image);
				$('#captionPhoto').html(imgTitle+'<br /><br /><small>Right click and choose \'Save Image As...\' to save</small>');

				$(".loader").fadeIn();
				
				$('img.lightboxImage').load(function() 
				{
					var w = $('img.lightboxImage').width();
					var h = $('img.lightboxImage').height() + 57;
					if(h > $(window).height()-70) {
						var newImage = '/wp-content/themes/redhookbrewing/timthumb.php?src=';
						newImage += $('#lightBoxPhoto > div > img.lightboxImage').attr('src');
						newImage += '&h='+($(window).height()-70);
						$('img.lightboxImage').attr('src', newImage);
						h = $('img.lightboxImage').height() + 57;
					}
					$("#lightbox").animate({height:h+'px', width:w+'px'}, 300, function()
					{
						$(".loader").fadeOut();
						$('img.lightboxImage').fadeIn();
						$("#captionPhoto").show();
					});
					
					$('img.lightboxImage').unbind("load");
				});
			});
			
			return false;
		}
		
		$('#lastPhoto').live('click', last);
		$('#nextPhoto').live('click', next);
		
		$('#closePhoto').live('click',function (){
			$('#lightBoxPhoto').remove();
			$('#lightbox').remove();
			return false;
		});
		$('#lightBoxPhoto').live('click', function(e) {
			if (!$(e.target).closest('#lightbox').length) {
		        $('#lightBoxPhoto').remove();
				$('#lightbox').remove();
		    };
		});
		$('#lightbox').live('click', function(e) {
 			e.stopPropagation();
		});


		$(document).keypress(function (e) {
			e.preventDefault();
			if(e.keyCode == 37){
				last();
			}
			else if(e.keyCode == 39){
				next();
			}
			else if(e.keyCode == 27){
				$('#lightBoxPhoto').remove();
				$('#lightbox').remove();
			}
		});
		$(document).keyup(function (e) {
			e.preventDefault();
			if(e.keyCode == 37){
				last();
			}
			else if(e.keyCode == 39){
				next();
			}
			else if(e.keyCode == 27){
				$('#lightBoxPhoto').remove();
				$('#lightbox').remove();
			}
		});
		$(window).resize(function ()
		{
			$('#lightBoxPhoto').css({
				'width' : $(document).width(),
				'height' : $(document).height()
			});
		});
		
	}
});


/*---------------- age-gate control ---------
if($.cookie("redhook-age-verification") == 1)
{
	$("#age-gate").hide();
}
else
{
	$("#age-gate").css('display', 'block');
}


$('#age-gate-yes').live('click', function(e)
{
   $.cookie("redhook-age-verification", 1, {expires: 999, path: '/'});
});

$('#age-gate-no').live('click', function(e)
{
  e.preventDefault();
  $.cookie("redhook-age-verification", 0, {expires: -1, path: '/'});	
  $("#age-gate-content").html("<p>You must be of legal drinking age to visit this site.</p>")
});
*/

	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 redhook.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.');
			}
		});
	}

/** Scroller Scripts **/
$(function(){
	
	if($('#booking-select').length) {
		$('#booking-select .handle').live('click', function(){
	      $('#booking-select .choices').toggle();
	   });
	   
	   $('#page').hover(function(){
	       $('#booking-select .choices').css('display', 'none');
	   });
	}
	
    if($('#scrollbar1').length) {
	
	   $('#date-select .handle').live('click', function(){
	      $('#date-select .choices').toggle();
	   });
	   
	   $('#page').hover(function(){
	       $('#date-select .choices').css('display', 'none');
	   });
	  
	    // $('#date-select .choices').hover(function(){
	    //     $('#date-select .choices').css('display', 'block');
	    // });
	    // 
	    // $('#date-select .choices').mouseout(function(){
	    //            $('#date-select .choices').css('display', 'none');
	    //        });
	   
	   
	   $('.events li').each(function(){
	      var class_add = 'loc-'+$(this).attr('data-loc-id');
	      $(this).parent().parent().addClass(class_add);
	   });
	   
	   $('.choices li').live('click', function(){
	      var text = $(this).text();
	      var cat_id = $(this).attr('data-id');
	       $('#date-select .choices').css('display', 'none');
	       $('.handle').html(text);
	       var locs = cat_id.split(' ');
	       $('#dates li').each(function() {
	           if($(this).hasClass('loc-'+locs[0]) || cat_id == "all"){
	               $(this).css('display', 'block');
	           }else{
	               $(this).css('display', 'none');      
	           }
	       })
	       $('.events li').css('display', 'none');
           
           (cat_id != "all") ? $('li[data-loc-id ='+cat_id+']').css('display','block') : $('.events li').each(function() {$(this).css('display', 'block')});
	       
           
	   });

	$('#scrollbar1').tinyscrollbar();
	
    
    /*--------Calendar Page filter ----------------*/
    
    
    
    
    }
    
    if($('ul.events li').length) {
    	var modal = $('#eventModal');
		$('#polaroid h4 a').click(function(e) {
			ajaxEvent($(this).attr('rel'), modal, e);
		});
		$('ul.events li').click(function(e) {
			ajaxEvent($(this).attr('rel'), modal, e);
		});
    }
	   
});

// Preloader
/*
$(window).load(function() {

	var cssFiles = $('link[media]'), files = {};
	var files = Array()
	$.each(cssFiles, function(i,item) {
		
		// Find 4 digit pixel reference in filename
	    var digits = 4;
	    var str = item.href;
	    var regex = new RegExp("\\d{"+digits+"}", "g");
	    var match = str.match(regex);
		
		if ( match == null )
			match = 0;
		
		if ( item.media != 'all' )
			files[match] = item.href;
			
	});

	var bodyClass = '.'+$('body').attr('class');
	
	// Preload background images referenced by body class	
	$.each(files, function(k,v) {
		if ( screen.width > k )
		{
			preload(getBgImages(bodyClass+' div#background', v));
		}
	});
	
});
*/

/** Map Selection for Contact Us **/
function showWoodinville() {
	$('.breweryMap').css('display', 'none');
	$('.woodinville').css('display', 'block');
}
function showPortsmouth() {
	$('.breweryMap').css('display', 'none');
	$('.portsmouth').css({'display': 'block', 'left': 0});
}

function ajaxEvent(ID, modal, mouseEvent) {
	
	if(mouseEvent)
	{
		clientX = mouseEvent.clientX;
		clientY = mouseEvent.clientY;
	}
	else
	{
		clientX = 350;
		clientY = 350;
	}
	
	$.ajax({
		type: 'POST',
		url: '/calendar/',
		data: 'eventID='+ID,
		dataType: 'json',
		success: function(data){
			modal.css({
				'display': 'block',
				'top': clientY+'px',
				'left': clientX+'px'
			});
			modal.children('.modalTitle').html(data.post_title+'<a class="closeModal" href="#close">X</a>');
			modal.children('.modalText').html(data.post_content);
			modal.children('.modalDate').html(data.dates);
			modal.children('.modalAddress').html(data.address);
			modal.children('.modalPhone').html(data.phone);
			modal.children('.modalCost').html(data.cost);
			var mapsUrl = 'http://maps.google.com?q='+encodeURIComponent(data.address_search);
			modal.children('.modalMap').attr('href', mapsUrl);
			$(document).keyup(function (e) {
				if(e.keyCode == 27){
					modal.css('display','none');
				}
			});
			$('.closeModal').live('click', function() {
				modal.css('display','none');
				return false;
			});
			var below = parseInt(modal.css('top'))+modal.height();
			if(below > $(window).height()) {
				var diff = below-$(window).height();
				var move = parseInt(modal.css('top'))-diff-10;
				modal.css('top', move);
			}
			var side = parseInt(modal.css('left'))+modal.width();
			if(side > $(window).width()) {
				var diff = side-$(window).width();
				var move = parseInt(modal.css('left'))-diff-10;
				modal.css('left', move);
			}
		}	
	});
}



