// to-do
// contact forms labels don't move back if I re-open the contact form
// usibility stuff (hiding submit etc)
// finish no js form
// remove #thanks and #message, don't need em now

$(document).ready(function()					   
	{
		
	(function($) // set up preloading of images
		{
		var cache = [];
		// Arguments are image paths relative to the current page.
		$.preLoadImages = function() 
			{
			var args_len = arguments.length;
			for (var i = args_len; i--;) 
				{
				var cacheImage = document.createElement('img');
				cacheImage.src = arguments[i];
				cache.push(cacheImage);
				}
			}
		})(jQuery)
	
	// what should I preload?
	jQuery.preLoadImages("nav background", "http://www.craigwinton.com/images/form-bkgd.png");
	
	// switch off .js fallbacks.
	// contact form will default to a page due to return false.
	// sweeeet... this targets descendants of page-photos, removes all dumb classes, adds proper one.
	$("ul.page-photos *").removeClass('d-no-js').removeClass('p-no-js').removeClass('i-no-js');

	// set up homepage fading images.
	$('.big').innerfade({ speed: 2000, timeout: 5000, type: 'sequence', containerheight: '600px' }); 

	
	function isValidEmailAddress(emailAddress) // this function checks that emails are valid. It's bung tho, thinks that 6 chars is okay on the end.
		{ 
		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);
		}
	
	
	function isValidName(theirName) // this function checks that emails are valid. It's bung tho, thinks that 6 chars is okay on the end.
		{ // checks for numbers, new lines, bad email shit
		var pattern = new RegExp(/(\d+|\n+|\r+|content-type:|to:|cc:|bcc:)/i);
		return pattern.test(theirName); 
		}
	
	
	function isValidSubject(theirSubject) // checks for numbers, new lines, bad email shit
		{ 
		var pattern = new RegExp(/(\n+|\r+|content-type:|to:|cc:|bcc:)/i);
		return pattern.test(theirSubject); 
		}


	$(function() // contact form slide-out
		{ 
		$("#contactme").click(function(event)	
			{ 
			event.preventDefault();
			if ($("#contact-form").is(":hidden"))	
				{ 
				$('#thanks').addClass('hide');
				$("#contact .label").removeAttr("disabled");
				//$('form li').children('label').animate({ opacity: 1, left: '0', top: '0',}, 0, function() {/* Animation complete.*/}); /* put labels back inside the box */
				$('#contact').removeClass('hide');
				$('span.validation').removeClass('tick');
				// clears all forms. could just clear this form.
				$("form").each(function() 
					{
					this.reset();
					});
				$("label").show();
				$("span.validation").css({ "background-position": "0 -1px" });
				$('.label').each(function(ele)

						{
						if ($(this).is('.left'))
							{
							//$('label[for=' + $(this).attr('id') + ']').animate({ opacity: 1, left: '0',}, 200, function() {/* Animation complete.*/});
							$('label[for=' + $(this).attr('id') + ']').css({ "left": "0", "opacity":"1" });
							} else {
							$('label[for=' + $(this).attr('id') + ']').animate({ opacity: 1, top: '0',}, 200, function() {/* Animation complete.*/});
							};
						});
				
				$('#errormsg').html("");
				$("#contact-form input").removeClass('error');
				$("#contact-form").slideDown("slow");	
				} else {	
				$("#contact-form").slideUp("slow"); 
				}	
			});
		});
	
	
	$(function() // put labels inside the contact form elements
		{ 
		$('.label').focus(function() /* when they click on the input */ 
			{
			if ($(this).is('.left')) 
				{
				$('label[for=' + $(this).attr('id') + ']').animate({left: '-'+(parseFloat($(this).siblings("label").css().width()) + 12), opacity: 0.4,}, 200, function() {/* Animation complete.*/});
				} else { 
				$('label[for=' + $(this).attr('id') + ']').animate({top: '-'+(parseFloat($(this).siblings("label").css().height()) + 12), opacity: 0.4,}, 200, function() {/* Animation complete.*/});
				};
			});
		
		
		$('.label').each(function(ele)
			{
			if($(this).val().length = 0)
				{
				if ($(this).is('.left'))
					{
					$('label[for=' + $(this).attr('id') + ']').animate({ opacity: 1, left: '0',}, 200, function() {/* Animation complete.*/});
					} else {
					$('label[for=' + $(this).attr('id') + ']').animate({ opacity: 1, top: '0',}, 200, function() {/* Animation complete.*/});
					};
				};
			// not sure why I need this..?
			});
		
		
		$('.label').blur(function() // check each time they interact with the input
			{ 
			// if there is nothing inside
			if($(this).val().length == 0) 
				{
				if ($(this).is('.left')) 
					{
					$('label[for=' + $(this).attr('id') + ']').animate({ opacity: 1, left: '0',}, 200, function() {/* Animation complete.*/});
					} else {
					$('label[for=' + $(this).attr('id') + ']').animate({ opacity: 1, top: '0',}, 200, function() {/* Animation complete.*/});
					};
				}
			});
		});
	
	
	$('.txt').blur(function() // Validate inputs with class .txt
		{ 
		if (($(this).val() == "")) 
			{ // it's wrong
			$('label[for=' + $(this).attr('id') + ']').siblings('span.validation').css({ "background-position": "0 -21px" });
			} else { // it's right
			$('label[for=' + $(this).attr('id') + ']').siblings('span.validation').css({ "background-position": "0 -11px" });
			$('#errormsg').html("");
			}
		});
	
	
	$("#cf_email").blur(function() // validate the email address as you type
		{
		var email = $("#cf_email").val();
		if(email != 0)
			{
			if(isValidEmailAddress(email))
				{ // it's right, show tick
				$(this).siblings("span.validation").css({ "background-position": "0 -11px" });
				$('#errormsg').html("");
				} else { // it's wrong, show cross
				$(this).siblings("span.validation").css({ "background-position": "0 -21px" });
				}
			}
		});
	
	
	$("#cf_email").keyup(function() // validate the email address as you type
		{
		var email = $("#email").val();
		if(email != 0) /* only do this if there's something typed */
			{
			if(isValidEmailAddress(email))
				{ // it's right
				$(this).siblings("span.validation").css({ "background-position": "0 -11px" });
				$('#errormsg').html("");
				} else { // it's wrong
				$(this).siblings("span.validation").css({ "background-position": "0 -21px" });
				}
			}
		});
	
	
	$(function() //submit email w/o page refresh
		{  
		$('.error').hide();
		$("#cf_submit").click(function() // validate and process form. Should prob be .submit() not click. Pushing enter can submit it too
			{ 
			$("#contact-form *").removeClass('error');
			  

			// validation stuff that mimics the php validation, cause I don't know how to display the php errors
			// check for bad shit. I think I only need it for email and subject. Do they need separate var names?
			var badshit = $('input#cf_name').val();
			if (isValidName(badshit))
				{ this 
				$("input#cf_name").addClass('error');
				$('#errormsg').html("sorry, your name has to be just letters");
				return false;
				}
			var badshit = $('input#cf_subject').val();
			if (isValidSubject(badshit))
				{ this 
				$("input#cf_subject").addClass('error');
				$('#errormsg').html("sorry, the subject can't have things like cc: or bcc: (spammers use those)");
				return false;
				}
			//  check the invisible field is empty, spambots will prob fill it in cause they're dumb
			var spambot = $("input#bender").val();
			if (spambot != "") 
				{
				$("input#bender").addClass('error');
				$('#errormsg').html("I think you're a spam robot");
				return false;
				}
			// check if they've entered a name
			var cf_name = $("input#cf_name").val();
			if (cf_name == "") 
				{
				$("input#cf_name").addClass('error');
				$('#errormsg').html("what should we call you?");
				$("input#cf_name").focus();
				return false;
				}
			// check if they've entered an email
			var cf_email = $("input#cf_email").val();
			if(isValidEmailAddress(cf_email)) 
				{ // if they did, sweet
				} else {
				$("input#cf_email").addClass('error');
				$('#errormsg').html("don't forget your email");
				$("input#cf_email").focus();
				return false;
				}
			// check if they've entered a subject
			var cf_subject = $("input#cf_subject").val();
			if (cf_subject == "") 
				{
				$("input#cf_subject").addClass('error');
				$('#errormsg').html("please enter a subject");
				$("input#cf_subject").focus();
				return false;
				}
			// check if they've entered a message
			var cf_message = $("textarea#cf_message").val();
			if (cf_message == "") 
				{
				$("textarea#cf_message").addClass('error');
				$('#errormsg').html("please enter a message");
				$("textarea#cf_message").focus();
				return false;
				}

		
			// submit via jquery 
			var dataString = "cf_name="+ cf_name + "&cf_email=" + cf_email + "&cf_subject=" + cf_subject + "&cf_message=" + cf_message;
			// usibility stuff.
			// sending message.
			$("#errormsg").html("Sending your email.");
			
			// disable the fields so they can't clik clik clik
			$("#contact .label").attr("disabled", "disabled");
			  
			$.ajax(
			{
			type: "POST",
			url: "php/emailication.php",
			data: dataString,
			error: function() // for now we'll just pretend nothing happened...
				{
				setTimeout('$("#contact-form").slideUp("slow")', 3000);
				},
			success: function() // do some nice stuff
				{
				//$('#thanks').removeClass('hide');
				//$('#contact').addClass('hide')
				$("#errormsg").html("Thanks, your email has been sent");
				setTimeout('$("#contact-form").slideUp("slow")', 2000);
				}
			});
			return false;
		});  
	});


	/* ===================== thumbnail magic ============================= */
	
	$("li.pieces").hover(function() // makes the thumbnail you're on have the highest z-index
		{
		$(this).addClass("highest")
		if ($(this).siblings().hasClass("highest") ) 
			{
			$(this).siblings().removeClass("highest");
			}
		});
	
	$("img.photo-shadow").hover(function(event) // gets things going
		{
		event.preventDefault();
		$(this).siblings("a.zoomer").removeClass('hide');
		});
	
	
	$("a.zoomer").hover( 
		function() 
			{ // this makes images disappear if you try to open a new one without closing the current one
			$('div.zooimage').zoomimageClear(); 
			$('a.zoomer').zoomimage( 
				{ // this will make .zoomer links zoom on a click
				border: 20,
				centered: true,
				hideSource: true,
				controls: false
				});
			$(this).animate({ opacity:1 }, 500);
			// triggering on .trigger means 'click to zoom' and 'trigger' won't get out of sync
			if ($(this).children().is(":hidden"))
				{
				$(this).siblings(".info").slideUp("slow");
				$(this).siblings(".info").removeClass('shadow');
				} else{
				$(this).siblings(".info").slideDown("slow");
				$(this).siblings(".info").addClass('shadow');
				}
			}, 
		function()
			{
			$(this).animate({ opacity:0 }, 500);
			if ($(this).children().is(":hidden"))
				{
				$(this).siblings(".info").slideDown("slow");
				} else {
				$(this).siblings(".info").slideUp("slow");
				}
			});
		});


// ========================================================= */


(function($) {

    $.fn.innerfade = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
        	'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $.innerfade.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}



