// Prevents site going off top
function topBlocker(){
	var h = $(window).height();
	(h <= 550 ? $wrapper.addClass('halt') : $wrapper.removeClass('halt'));
};

// Remove title and alt attributes
function removeAttributes($node) {
	$wrapper.find('a').attr('title','');
	$wrapper.find('img').attr('alt','').attr('title','');
}

// Open external links in new window
function externalLinks(){
	$wrapper.find('a[rel=external]').click(function(e){
		e.preventDefault();
		window.open(this.href);			
	});
};

function brochureForm(){
	if($('#page_contact_us_request_brochure').length > 0){
		var $form = $('#request_brochure');

		$form.submit(function(e){
			var errors = false;
			// Reset
			$(this).find('div').attr('class','');
			$(this).find('#error_notice').remove();
			
			$(this).prepend('<p id="error_notice">Please fill in the highlighted fields</p>');
			var $fields = $(this).find(':input');
			for (var i=0; i < $fields.length; i++) {
				$field = $($fields[i]);
				if($field.hasClass('required')){
					if($field.val() == ''){
						errors = true;						
						$field.parent().attr('class','error');
						$(this).attr('class','errors');
						console.log($field.attr('name'));
					}					
				}
			};
			
			if(errors == true){
				return false;	
			}			
		});
	}
};

function initSlideshow(){
	$slideshow = $('#slideshow');
	$playpause = $('#play_pause');

	if($slideshow.length > 0){
			$slideshow.cycle({
				timeout: 3000
			});
			
			if($playpause.length > 0){
				$playpause.bind('click', function(e){
					e.preventDefault();
					var txt = $(this).text();
					if(txt == 'PAUSE'){
						$slideshow.cycle('pause');
						$(this).text('PLAY');
					} else {
						$slideshow.cycle('resume');
						$(this).text('PAUSE');						
					}
				})
			}
	}
};

function initSlidingText(){
	var $text = $('#page_home #text');
	var $about = $('#about_bespoke');
	var $sussex = $('#sussex');

	if($text.length > 0){
		$about.hide(0);
		
		$text.prepend('<a href="#" id="read_close">READ</a>');
		var $read = $('#read_close');

		$read.click(function(e){			
			e.preventDefault();
			var status = $(this).html();			

			$about.slideToggle(1000, function(){
				var html = $read.html();
				$read.html((html == 'READ' ? 'CLOSE' : 'READ' ));
			});
		})
	};
};

function em(email){
	document.write('<a href="mailto:'+email+'@woodworkslewes.com">'+email+'@woodworkslewes.com'+"</a>");
}

$(function(){
	$wrapper = $('#wrapper');

	topBlocker();
	initSlidingText();	
	initSlideshow();
	brochureForm();	
	removeAttributes($wrapper);	
	externalLinks();
});

$(window).resize(function(){
	topBlocker();
});
