$(document).ready(function() {

	var galleryLoadOnce = true;
	var gallery_total;
	var loaded = 3;

	
	$('body').removeClass('ns_home');
	$('#home').css('left', '8000px');
	
	$.scrollTo( '#home');
	// New Navigation Code - Needs BBQ Implementation
	$('.sidenav li.scroll a').each(function(){
		$(this).attr('href','#'+$(this).attr('href'));
	});
	
	$(window).bind('hashchange', function(event){

	       var hash_str = event.fragment,
	       param_obj = event.getState(),
	       param_val = event.getState( 'param_name' ),
	       param_val_coerced = event.getState( 'param_name', true );
		
			pageTracker._trackPageview(hash_str);

			var gotoID = hash_str.replace(new RegExp(/\//g),"");
			if(gotoID == ""){ gotoID = "home"; }
			
			$('.sidenav li.scroll a').each(function(){
				$(this).parent().removeClass('current');
			});
			
			var navItem = ".go_"+gotoID;
			$(navItem).parent().addClass('current');
			
	        $.scrollTo('#'+gotoID, 4000, { axis:'xy', queue:true, onAfter:function(){
		
	       if(gotoID == "gallery"){
	           $.ajax({
					type: "POST",
					dataType: "json",
					url: "/gallery",
					data: "ajax=1",
					success: function(msg){
					if(galleryLoadOnce){
						$('#gallery_slider').width((1134*loaded)+1134);
				    	galleryLoadOnce = false;
						$('#gallery_slider').append(msg.html);
						$('.gallery_controls a.next').fadeIn('fast');
						gallery_total = msg.total;
				   }
				}
				});
			}

			} });
		});
	
	$(window).trigger( 'hashchange' );
	
	// Backup scroll for food sub pages
	 $('.sidenav li.scroll a.go_food-drink').click(function(e) {
	
	  	$.scrollTo("#food-drink", 4000, { axis:'xy', queue:true});
	 });
	 
	 
	
	
	//////////////////////////////////////////
	// Event listings - moves in 3's = 600px
	var events_max = parseInt($('#max_events').html());
	$('#max_events').remove();
	
	var set=2; var calledTo = 1;
	
	//SHOW NEXT IF MORE THAN 3 EVENTS
	if(events_max > 1){
		$('#events .menu_controls .next').click(function(e) {
			e.preventDefault();	
			next_event();
		});
	}else{
			$('#events .menu_controls .next').hide();	
	}
	
	function next_event (){
		$('#events .menu_controls .previous, #events .menu_controls .next').unbind('click').click(function(e) {
			e.preventDefault();
			});
			
		if (events_max ==set){$('#events .menu_controls .next').fadeOut('slow'); 
		}else {$('#events .menu_controls .next').fadeIn('slow')	.click(function(e) {
				e.preventDefault();	
				next_event();
			});
		}
		if (1==set){$('#events .menu_controls .previous').fadeOut('slow')
		} 
		else {$('#events .menu_controls .previous').fadeIn('slow').click(function(e) {
			e.preventDefault();	
			previous_event();
		});
		}
		
		//ONLY CALL IF THIS PAGE HASN'T BEEN REQUEST BY AJAX YET!
		if(set > calledTo){
			$.ajax({
			   type: "POST",
			   url: "events/page/"+set,
			   data: "ajax=true",
			   success: function(msg){
				$('#events_slider ul').append(msg);
				$('#events_slider').scrollTo('+=600px', 1200, { axis:'x' });
				calledTo = set;
				set++;
			   }
			});
		}else{
			$('#events_slider').scrollTo('+=600px', 1200, { axis:'x' });
			set++;
		}
	}
	
	$('#events .menu_controls .previous').click(function(e) {
		e.preventDefault();
		previous_event();
	});
	
	function previous_event (){
		$('#events .menu_controls .previous, #events .menu_controls .next').unbind('click').click(function(e) {
			e.preventDefault();
			});
			
		set--;
		if (set<=2){$('#events .menu_controls .previous').fadeOut('slow');
		} 
		else {$('#events .menu_controls .previous').fadeIn('slow').click(function(e) {
			e.preventDefault();	
			previous_event();
		});
		}
		if (events_max<set){$('#events .menu_controls .next').fadeOut('slow');
		} 
		else {$('#events .menu_controls .next').fadeIn('slow').click(function(e) {
			e.preventDefault();	
			next_event();
		});
		}
		$('#events_slider').scrollTo('-=600px', 1200, { axis:'x' });
	}
	
	////////////////////////////////////////////////////////
	// Menu Slider 
	
	$('#food_menu_cats .next, .menu_cat').click(function(e){
		e.preventDefault();
		duration = 1500;
		
		//GET THE CLICKED ITEM
		var section = $(this).attr('title');
		//FOOR OR DRINK?
		var getID;
		var insertInto;
		if($(this).parent().attr('id') == "drinks_menu_cats"){ 
			getID = "#ajax_drink_items" 
			insertInto = "#drinks_ajax_container";
		}else if($(this).parent().attr('id') == "food_menu_cats"){
			getID = "#ajax_food_items" 
			insertInto = "#food_ajax_container";
		}
		
		$(insertInto).load("food-drink?ajax=true "+getID, function(response, status, xhr) {
			var scrollToElement;
			
				if (section =="Food Plaque"){
					scrollToElement ="#mains"
				
				}else if (section == "Drinks Plaque"){
					scrollToElement ="#sparkling"
				}else {
					scrollToElement = '#'+section.toLowerCase().replace(" ", "_");
				}
				
				var pos = $(scrollToElement).position();
				var distance;
				if($(scrollToElement).parent().attr('id') == "ajax_food_items"){
					distance = pos['left'] - 8000;
				}else if($(scrollToElement).parent().attr('id') == "ajax_drink_items"){
					distance = pos['left'] - 8000;
					distance = distance * -1;
				}	
				var speed = 0.5;
				var duration = distance * speed;
				
  			 	$.scrollTo(scrollToElement, { axis:'x', duration:duration });
  			}
		);								
	});
		$('#food_ajax_container .menu_controls a, #drinks_ajax_container .menu_controls a').live('click', function(e){
		e.preventDefault();
		var section = $(this).attr('title');
		var scrollToElement = '#'+section.toLowerCase().replace(" ", "_");
		$.scrollTo(scrollToElement, { axis:'x', duration:duration });
	});
	
	////////////////////////////////////////////////////////
	///GALLERY FRAME SCROLLING
	
	var itemWidth = 1134;
	var duration = 500;
	var count = 0;
	var page = 1;
	
	$('.gallery_controls .previous').click(function(e){
		e.preventDefault();
		galleryScrollPrev();
		});
	
	$('.gallery_controls .next').click(function(e){
		e.preventDefault();	
		galleryScrollNext();
		});
	
	function galleryScrollNext(e){
		
			$('.gallery_controls a.next, .gallery_controls a.previous').unbind().click(function(e){ e.preventDefault()});
			
			$('#gallery_slider').animate({
			left: '-='+itemWidth
		 	 }, duration, function() {
				// Animation complete.
				
			  });
				count++;
				if(count == gallery_total){
					
					$('.gallery_controls a.next').fadeOut('slow');
				}else{
					$('.gallery_controls a.next').fadeIn('slow').click(function(e){
						e.preventDefault();	
						galleryScrollNext();
						});
				}
				
				//LOAD 3 MORE IMAGES
				if(count + 2 > loaded){
				
					page++;	
					
				
					if(page * 3 > loaded && loaded < gallery_total){
					  $.ajax({
								type: "POST",
								dataType: "json",
								url: "/gallery",
								data: "ajax=1&page="+page,
								success: function(msg){
									$('#gallery_slider').width((1134*loaded)+1134);									
									$('#gallery_slider').append(msg.html);
								}
						});
					}
				loaded = loaded+3;
					
				}
				
				$('.gallery_controls a.previous').fadeIn('slow').click(function(e){
					e.preventDefault();
					galleryScrollPrev();
					
					});
	}
	
	function galleryScrollPrev(e){
		$('.gallery_controls a.next, .gallery_controls a.previous').unbind().click(function(e){ e.preventDefault()});
			
			$('#gallery_slider').animate({
			left: '+='+itemWidth
		 	 }, duration, function() {
				// Animation complete.
				
			  });
				count--;
				if(count == 0){
					$('.gallery_controls a.previous').fadeOut('slow');
				}else{
					$('.gallery_controls a.previous').fadeIn('slow').click(function(e){
						e.preventDefault();
						galleryScrollPrev();
						});
				}
				$('.gallery_controls a.next').fadeIn('slow').click(function(e){
					e.preventDefault();	
					galleryScrollNext();
					});
	}
	
	
	////////////////////////////////////////////////////////
	//CONTACT FORM
	
	$('#form_contact').submit(function(e){
		e.preventDefault();
		var validate = true;
		var message;
		var $inputs = $('#form_contact :input');
		
		//BUILD VALUE ARRAY & VALIDATE
		var values = {};
		$inputs.each(function() {
			values[this.name] = $(this).val();
			
			if(this.name == 'email'){
				if(!isValidEmailAddress($(this).val())){
					validate = false;
					
					message = "Please supply a valid email address";
				}
			}
			
			if(this.name in {'name':'', 'email':''}){
				if($(this).val() == "" || $(this).val() == " "){
					validate = false;
					
					if(this.name == "name"){
						$(".name-label").css('background-position','-70px top');
					}else if(this.name == "email"){
						$(".email-label").css('background-position','-70px -25px');
					}
					message = "The marked fields are mandatory";
				}
			}
			
			
			
		});
		
		
		if(validate){
			//DO AJAX SUBMISSION
			$.ajax({
			   type: "POST",
			   url: "/wp-content/themes/slaughteredlamb/form_submit.php",
			   data: "form=contact&ajax=1&email="+values['email']+"&name="+values['name']+"&phone="+values['phone']+"&enquiry="+values['enquiry'],
			   cache: false,
			   dataType: 'html',
			   success: function (html) {
				if (html==1) {
					$(".boxes").fadeOut("slow");
					$(".enquiries").append("<div class='message'>Thanks for contacting us.<br />We'll be in touch soon.</div>");
					$(".enquiries .message").fadeIn("slow");

				
				} else { 
					$("#form_contact .message").html('There was an error submitting the form, <br />Please try again');
					
				};}
			 });
			
			
			
		}else{
			//DOES NOT VALIDATE. PROVIDE ERROR
				
			$("#form_contact .message").html(message).fadeIn("slow");
		}				   
			
	});
	
	
	
	////////////////////////////////////////////////////////
	////EMAIL SUBSCRIBE FORM
	
	$('#form_mailing').submit(function(e){
		if ($('#krydhk-krydhk').val() == '' || !isValidEmailAddress($('#krydhk-krydhk').val())) {
			alert('Please enter a valid email address');
			
			$('#krydhk-krydhk').focus();
				return false;
		}
		else {
			//SAVE VIA PHP PROXY
			$.ajax({
			   type: "POST",
			   url: "/wp-content/themes/slaughteredlamb/form_submit.php",
			   data: "form=email&ajax=1&email="+$('#krydhk-krydhk').val(),
			   cache: false,
			   dataType: 'html',
			   success: function (html) {
				if (html==1) {
					$(".mailing_list_wrap").fadeOut('slow');
					$(".mailing_list").append("<div class='message'>Thank you. Your email has been added</div>");
					$(".mailing_list .message").fadeIn('slow');
					$('#dudkhj_dudkhj').val('Email Address');
					setTimeout(successHide, 2000);
				} else { 
					$('#success').html('Sorry that didn\'t work please try again');
					$('#success').fadeIn('slow');
					setTimeout(successHide, 2000);
				};}
			 });
			
	return false;
			
		}
	
	});
	
	
	
	
	
	
});

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}