/* ---------------------------------------------------------------------------
					
	57bit
	http://57bit.com
	
--------------------------------------------------------------------------- */

/* --------------------------------------------------------------------------
	=setup
--------------------------------------------------------------------------- */

var companyName = "57Bit",
	animationSpeed = 500,
	scrollSpeed = 500,
	fadeDelay = 100,
	currentWork = "",
	nextWork = "";

/* --------------------------------------------------------------------------
	=functions
--------------------------------------------------------------------------- */
function getActivePage(){
	var hashId = window.location.href.split('#')[1];
	$('#top-nav li a, #side-nav li a').removeClass('active');
	$('#nav-'+hashId+', #side-nav-'+hashId).addClass('active');
}

function getActivePageByClick(pageId){
	$('#top-nav li a, #side-nav li a').removeClass('active');
	$('#nav-'+pageId+', #side-nav-'+pageId).addClass('active');
}


function goToByScroll(id){
	$('html,body').animate({scrollTop: $("#"+id).offset().top}, 1000, 'easeOutExpo');
	getActivePageByClick(id);
}
function scrollToContact(title){
	$('#thanks').text('Just fill those little white boxes with as much info as you can and we\'ll get your '+title+' estimate over to you as soon as we can! Thanks a million');
	$('#subject').val(title);
	$('html,body').animate({scrollTop: $("#contact").offset().top}, 1000, 'easeOutExpo');
	getActivePageByClick('contact');
}
function checkMail(emailAddress){
	var x = emailAddress;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if (filter.test(x)){
		return true;
	}else{
		return false;
	}
}

function getWorkDetails(project) {
	return $("#work-"+project);
}

function getWorkLink(project) {
	return $("#work-list-"+project+" a");
}

function showWorkDetails(project, animate) {
	if ($("#work-list a.selected").attr("href")) {
		currentWork = getWorkDetails($("#work-list a.selected").attr("href").replace("\#",""));
	}
	nextWork = getWorkDetails(project);

	if (!getWorkLink(project).hasClass("selected")) {
		
		// dynamically add all images for selected project
		$.each(projectImages[project], function(i, projectImage) {
			loadProjectImage("_assets/images/our-work/"+projectImages[project][i].file, projectImages[project][i].alt, $(".project-image-"+project+"-"+(i*1+1)));
		});
		
		// fade out displayed work, if it exists
		if (currentWork) {currentWork.fadeOut(animationSpeed);}
		
		// fade in selected work
		nextWork.delay(fadeDelay).fadeIn(animationSpeed);
		// set selected flag
		$("#work-list a.selected").removeClass("selected");
		getWorkLink(project).addClass("selected");
		
		// change height of work
		$("#work-container").animate({
			height: nextWork.outerHeight()
		}, scrollSpeed );
		
		// fade in close project button
		$("#close-project").fadeIn(animationSpeed);
		// fade in work title the lazy way
		$("#work-name").fadeOut(animationSpeed/2);
		$("#work-name").empty();
		$("#work-name").append(" / "+$("h2", getWorkDetails(project)).text());
		$("#work-name").fadeIn(animationSpeed/2);
		
		// update document title
		document.title = companyName+" — "+$("h2", getWorkDetails(project)).text();
	}
	
	// scroll to top of work
	goToByScroll('work');
}

function hideWorkDetails() {
	currentWork = getWorkDetails($("#work-list a.selected").attr("href").replace("\#",""));
	
	// fade out displayed work
	currentWork.fadeOut(animationSpeed);
	// remove selected flag
	$("#work-list a.selected").removeClass("selected");
	
	// hide work section
	$("#work-container").delay(fadeDelay).animate({
		height: 0
	}, animationSpeed );
	
	// fade out close project button
	$("#close-project").fadeOut(animationSpeed);
	// fade out work title
	$("#work-name").fadeOut(animationSpeed);
	
	// update document title
	document.title = companyName;
}

function setupCloseProjectButton() {
	$("#work > header").append("<p id=\"close-project\"><a href=\"#index\">Close Project</a></p>");
	$("#close-project").click(function() {
		hideWorkDetails();
	});
}

function setUpProjectImages() {
	$.each(projectImages, function(project, projectImages) { 
		$.each(projectImages, function(i, projectImage) { 
			if (i>0) {
				$(".screenshots ul", getWorkDetails(project)).append("<li><img src=\"_assets/images/our-work/loading.gif\" alt=\"empty\" class=\"empty project-image-"+project+"-"+(i*1+1)+"\" /></li>");
			}
		});
	});
}

function setUpWorkListHook() {
	$(".project-name").after("<span class=\"project-extra\"></span>");
}

function setUpProjectSlider() {
	$("#work-list a").each(function(){
		var project = $(this).attr("href").replace("\#","");
		// fragile
		$(".screenshots", getWorkDetails(project)).easySlider({
			speed: animationSpeed,
			project: project
		});
	});
}

function loadProjectImage(src, alt, target) {
	if ($(target).hasClass("empty")) {
		$("<img />")
			.attr("src", src)
			.attr("alt", alt)
			.bind("imgload",
				function() {
					target.before($(this))
						.fadeOut(animationSpeed*0,
						function() {
							target.remove();
						}
					);
				}
			);
	}
}

/* doc ready */

$(function() {
	getActivePage();
	
	var topPadding = 15,
		offset = $("#side-nav").offset();
	
	function trailingNav() {
		var top = $(window).scrollTop();
			
		if (top > 120) {
			$("#side-nav").show();
			$("#side-nav").stop().animate({
				marginTop: top - topPadding
			}, { duration: 1000, easing: 'easeOutCirc'});
		} else {
			$("#side-nav").stop().hide();
			$("#side-nav").stop().animate({
				marginTop: 0
			}, { duration: 1000, easing: 'easeInCirc'});
		}
	}

	$(window).scroll(function() { trailingNav(); });
	$(window).load(function() { trailingNav(); });

	$('#contactForm').attr('autocomplete','off');

	// update ids so that scroll animation works
	$(".work-details").each(function(){
		$(this).attr("id","work-"+$(this).attr("id"));
	});

	// on click events for showing work
	$("#work-list a").click(function() {
		showWorkDetails($(this).attr("href").replace("\#",""));
	});
	
	// setup
	setupCloseProjectButton();
	setUpProjectImages();
	setUpWorkListHook();
	setUpProjectSlider();

	// display work if there is a valid hash in the url
	var project = location.hash.replace("\#","");
	if (getWorkDetails(project).length) {
		showWorkDetails(project, true);
	}

	$('p.error').each(function(){
		var inputs = $(this).parent().find('input, textarea');
		$(this).height(inputs.height());
		$(this).width(inputs.width());

		$(this).click(function(){
			$(this).fadeOut();
			inputs.focus();
		});
	});
	
	try {
		oHandler = $(".mydds").msDropDown().data("dd");
		oHandler.visible(true);
		$("#ver").html($.msDropDown.version);
	} catch(e) {
		alert("Error: "+e.message);
	}

});



/* --------------------------------------------------------------------------
	=contact form
--------------------------------------------------------------------------- */
inputLinkPrefixes = ['http://', 'https://'];

$(function(){
	$('label.error').each(function(){
		var inputHeight = $(this).parent().find('input, textarea').height();
		var inputWidth = $(this).parent().find('input, textarea').width();
		$(this).height(inputHeight);
		$(this).width(inputWidth);

		//My nice error message effect
		$(this).click(function(){
			$(this).fadeOut();
			$(this).parent().find('input, textarea').focus();
		});
	});
	
	
	//clear the dummy data on focus. Usability is key!
	$('.textinput, textarea').each(function(){
		var thisId = $(this).attr('id');
		var prefix = $(this).attr('title');

		$(this).focus(function(){
			var thisValue = $(this).val();
			var thisId = $(this).attr('id');
			var prefix = $(this).attr('title');
			if(thisValue == thisId) {
				$(this).val(prefix);
			}
		});
		
		$(this).blur(function(){
			var thisId = $(this).attr('id');
			var thisValue = $(this).val();
			checkFields(thisId, thisValue);
		});
	});
});

function checkFields(thisId, thisValue){
	var error = $('#'+thisId+'').parent().find('.error');
	
	if(thisId == 'Name'){
		if(thisValue == '' || thisValue == thisId){
			var pass = false;
			var errorText = 'We need to know your name!';
		}
	}else if(thisId == 'Email'){
		if(thisValue == '' || thisValue == thisId || checkMail(thisValue)==false){
			var pass = false;
			var errorText = 'Please enter a valid email address';
		}
	}else if(thisId == 'Website' || thisId == 'findusLink'){
		var pass = true;
	}else if(thisId == 'Message'){
		if(thisValue == '' || thisValue == thisId){
			var pass = false;
			var errorText = 'Go on say something, don\'t waste you right to free speech?';
		}
	}else if(thisId == 'Telephone'){
		if(thisValue != '' && thisValue != thisId && isNaN(thisValue)){
			var pass = false;
			var errorText = 'Only use digits 0-9 in this field';
		}else if(thisValue != '' && !isNaN(thisValue) && thisValue.length < 11){
			var pass = false;
			var errorText = 'errrmm... Not enough digits!';
		}
	}else if(thisId == 'Company'){
		var pass = true;
	}
	
	if(pass == false){
		error.text(errorText).fadeIn('fast');
		validationkey = false;
	} else {
		validationkey = true;
	}
}
function contactSubmit(){
	//Check all fields for acceptable values
	$('.textinput, textarea').each(function(){
		var thisId = $(this).attr('id'),
			thisValue = $(this).val();
		checkFields(thisId, thisValue);
	});
	if(validationkey == true){
		var str = $('#contactForm').serialize(),
			contactName = $('#Name').val(),
			contactEmail = $('#Email').val(),
			greeting = $('#greeting').val(),
			subject = $('#subject').val();
		$.ajax({
			type: "POST",
			url: '/cmd.php?action=contactSubmit&'+str,
			data: str+'&subject='+subject+'&greeting='+greeting,
			success: function(){
				$("#contactForm").ajaxComplete(function(event, request, settings){
					$('#contactForm').slideUp({duration:800, easing:"easeInOutCirc", complete:function(){
						$('#thanks').animate({Width: 0, easing: "easeInOutCirc", duration: 2000}, function(){
							$(this).html("Thanks <span style='text-transform: capitalize;'>"+contactName+"</span> you're great!, We've just received your request and sent a quick 'thanks' to "+contactEmail+". We're usually quite quick off the mark so you should hear from us very soon, until then go ahead enjoy the rest of your "+greeting+". :o)"), function(){
								$(this).animate({Width: 960, easing: "easeInOutCirc", duration:1000});
							}
						});
						}
					});
				});
				
			}
		});
	}
}
