// function to validate contact form
function validateContact() {
	var nm		= $("#fromName").val();
	var sub		= $("#subject").val();
	var em		= $("#sendFrom").val();
	var mess	= $("#sendBody").val();

	var err_count = 0;

		// VALIDATE NAME
		if (isEmpty(nm) || !isName(nm) || nm == 'Your name') {
			err_count++;
			
			$("#fromName").removeClass('pass');
			$("#fromName").addClass('fail');
		} else {
			$("#fromName").removeClass('fail');
			$("#fromName").addClass('pass');
		}

		// VALIDATE SUBJECT
		if (isEmpty(sub) || sub == 'Subject') {
			err_count++;
			
			$("#subject").removeClass('pass');
			$("#subject").addClass('fail');
		} else {
			$("#subject").removeClass('fail');
			$("#subject").addClass('pass');
		}

		// VALIDATE EMAIL
		if (isEmpty(em) || !isEmail(em)) {
			err_count++;
			
			$("#sendFrom").removeClass('pass');
			$("#sendFrom").addClass('fail');
		} else {
			$("#sendFrom").removeClass('fail');
			$("#sendFrom").addClass('pass');
		}

		// VALIDATE MESSAGE
		if (isEmpty(mess) || mess == 'Message') {
			err_count++;
			
			$("#sendBody").removeClass('pass');
			$("#sendBody").addClass('fail');
		} else {
			$("#sendBody").removeClass('fail');
			$("#sendBody").addClass('pass');
		}

	// check for errors and alert the user, or submit the form
	if (err_count > 0) {
		$("#formsuccess").hide();
		$("#formerrors").fadeIn();
		$("#formerrors").find('p').html('One or more of the fields below requires your attention.');
		// hasErrors();
	} else {
		$("#formerrors").hide();
		var pars = "subject="+sub+"&fromname="+nm+"&sendBody="+mess+"&sendFrom="+em;
		
		$.ajax({
			   type: "POST",
			   url: "form.contact.php",
			   data: pars,
			   success: function(msg){
			   		if (msg == 0) {
						$("#formsuccess").hide();
						$("#formerrors").find('p').html('One or more of the fields below requires your attention.');
						$("#formerrors").fadeIn();
					} else {
						$("#formerrors").hide();
						$("#formsuccess").find('p').html('Success. Your request has been submitted.');
						$("#formsuccess").fadeIn();
						
						// empty input values
						$('#questions-form').find('input').val('');
						$('#questions-form').find('textarea').val('');
						
						// reset form
						formEvents();
						return false
					}
				}
		});
		return false;
	}
	return false
}

// returns true if the string only contains characters A-Z or a-z
function isAlpha(str) {
	var re = /[^a-zA-Z]/g;
	
	if (re.test(str)) return true;
	return false;
}

// returns true if the string only contains characters A-Z or a-z or 0-9
function isAlphaNumeric(str) {
	var re = /[^a-zA-Z0-9]/g;
	
	if (re.test(str)) return true;
	return false;
}

function isEmpty(str) {
	if(str.length == 0 || str == null) {
		return true;
	} else {
		return false;
	}
}

// returns true if string follows proper name conventions A-Z or - or ' or space 
function isName(str) {
	var re = /^[a-zA-Z-'\s]*$/;
	
	if (re.test(str)) return true;
	return false;
}

function isEmail(str){
	if (str == '') return false;
	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
	return re.test(str);
}

function stripWhitespace(str, replacement){
	if (replacement == null) replacement = '';
	var result = str;
	var re = /\s/g;
	if (str.search(re) != -1) {
		result = str.replace(re, replacement);
	}
	return result;
}

// function for colouring the fields with errors
function hasErrors(fieldID, err) {
	if (err) {
		$("#"+fieldID).addClass('error');
	} else {
		$("#"+fieldID).removeClass('error');
		$("#"+fieldID).addClass('pass');
	}
}


// function sets form labels inline 
function formEvents() {
		// get all forms on page
		var allforms = document.getElementsByTagName('form');
		
		// loop through forms
		for (i=0;i<allforms.length;i++) {

		// get all input tags in current form
		var thisform = allforms[i].getElementsByTagName('input');
		var message = allforms[i].getElementsByTagName('textarea');

		// loop through those inputs
		for (j=0;j<thisform.length;j++) {

			// qualify that the input is a text input, and has a title, and isn't being excluded by using the 'noevents' class
			if (thisform[j].title && 
				thisform[j].title != '' && 
				thisform[j].type != 'image' && 
				thisform[j].type != 'button' && 
				thisform[j].type != 'submit' && 
				thisform[i].className != 'noevents') {

					// assign the title to the value
					thisform[j].value = thisform[j].title;
					message[0].value = message[0].title;
				
					// events that will replace default values into fields
					thisform[j].onfocus = function() {
						if (this.title == this.value) {
							this.value = '';
						}
					}
					thisform[j].onblur = function() {
						if (this.value == '') {
							this.value = this.title;
						}
					}
					message[0].onfocus = function() {
						if (this.title == this.value) {
							this.value = '';
						}
					}
					message[0].onblur = function(){
						if (this.value == '') {
							this.value = this.title;
						}
					}
				}
			}
		}
}

// grab json and display flickr photoset
function flickr() {
	$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=20474070@N00&lang=en-us&format=json&jsoncallback=?", function(data) {
			
			// grab photoset images
			$.each(data.items, function (i,item) {
					// check for device width 
					var pic = "<a class=\"fancy\" title='"+ item.title.replace("'", "&#8217;") +"' rel=\"flickr\" href='" + item.media.m.replace(/_m/i, "_z") + "'></a>";
					
					// wrap and attach to dom
						$("<img/>").attr("src", item.media.m.replace(/_m/i, "_s")).appendTo("#images").wrap(pic);
			});
			
			// author title 
			$("#title").html(data.title);
			
			// plugin
			$('a.fancy').fancybox({
				helpers : {
					title : {
						type : 'inside'
					},
					overlay : {
						css : {
								'background-color' : '#141414'	
							}
					}
				}
			});
	});
} 

// function to swap case studies
function switcheroo (theLink, setFirstItem) {
	var curBtn = setFirstItem; 
	
	$(theLink).click(function() {
			var el = $(this);
			var href = el.attr('href');
			
			$(theLink).parent().removeClass('curr');
			el.parent().addClass('curr');
			
			if (curBtn === href) {
				// prevent fadein from firing if matched
			} else {
				// otherwise fire event
				$('.scrollable').fadeOut('fast').addClass('hide absolute');
				$("div" + href).fadeIn('fast').removeClass('hide absolute');
				
				// reset first image position to 0
				$('.frontImage').attr('style', '');
				
				// reset navi position to 0
				$('.navi a').removeClass('active');
				$('.navi a:first').addClass('active');
			}
			
			// update curBtn to latest click state
			curBtn = href;
			return false;
	});
}

// show to-top scroll link on section roll over
function showtop (tugboat, anchor) {
	$(anchor).css({'display' : 'none'});
	
	$(tugboat).mouseenter(
		function () {
				var self = $(this);
				self.find(anchor).css({'display' : 'inline'});
			}
		).mouseleave(
		function () {
				var self = $(this);
				self.find(anchor).css({'display' : 'none'});
			}
		);
}

$(document).ready( function () {
	
	// initialize 
	formEvents();
	flickr();
	showtop('.section', '.to-top');
	switcheroo('.work-page a', '#evite');
	
	$(".scrollable").scrollable({
		speed		: 500,
		circular	: true
	});
	
	$('#top').localScroll({ 
		filter		: ':not(.stop)',
		duration	: 400
	});
	
	/*/iPhone/.test(MBP.ua) && !location.hash && setTimeout(function () {
		if (!pageYOffset) {
			window.scrollTo(0, 1);
		}
	}, 1000);*/
	
}); 
