// makes the text 'read more' change colour
$(document).ready(function () {
	$("ul#projectoverview li").hover(function() {
	$(this).find('a:not(.thumb)').toggleClass('orange'); 
	});
});

// pointer over refresh icoon bij capcha
$(document).ready(function () {
	$('img#refresh').hover(function() {
			$(this).css('cursor', 'pointer');
	});
});

// adds black triangle in odd information boxes
$(document).ready (function () {
$("#maincontent .information:odd").append('<span></span>')	
});


// adds black triangle in even information boxes
$(document).ready (function () {
$("#maincontent .information:even").append('<span class="right"></span>')	
});


// adds selected class to appropriate pages (project pages)
$(document).ready (function () {
$("body#project header nav li#portfolio").addClass('selected')	
});
// adds selected class to appropriate pages (about page)
$(document).ready (function () {
$("body#about header nav li#aboutme").addClass('selected')	
});


// grey/colour thumb-effect on the homepage
$(document).ready(function() {
	$("ul#projectoverview li").hover(function() { //On hover...
	
		var thumbOver = $(this).find("img").attr("src"); //Get image url and assign it to 'thumbOver'
		//Set a background image(thumbOver) on the <a> tag - Set position to bottom
		$(this).find("a.thumb").css({'background' : 'url(' + thumbOver + ') no-repeat center bottom'});
		//Animate the image to 0 opacity (fade it out)
		
		$(this).find("span").stop().fadeTo('normal', 0 , function() {
			$(this).hide() //Hide the image after fade
		});
		
	} , function() { //on hover out...
		//Fade the image to full opacity 
		$(this).find("span").stop().fadeTo('normal', 1).show();
	});
});


// background-images in top navigation (in this case 'aboutme')
$(document).ready(function () {
	$("header nav li#aboutme").hover(function() {
	$(this).parent().parent().addClass('aboutmebgr');
	},
  function() {
	$(this).parent().parent().removeClass('aboutmebgr');	
 });
});


// Autoresize
$(document).ready(function() {
	$('textarea,input').autoResize({
	onBeforeResize: function(){
	console.log('Before');
	$(this).css('background', 'red');
	},
	onAfterResize: function(){
	console.log('After');
	$(this).css('background', '');
	}
	});
});


// Autoresize - the script
(function($){   
    $.fn.autoResize = function(options) {       
        // Just some abstracted details,
        // to make plugin users happy:
        var settings = $.extend({
            onResize : function(){},
            animate : true,
            animateDuration : 150,
            animateCallback : function(){},
            extraSpace : 20,
            limit: 1000
        }, options);       
        // Only textarea's auto-resize:
        this.filter('textarea').each(function(){
            
                // Get rid of scrollbars and disable WebKit resizing:
            var textarea = $(this).css({resize:'none','overflow-y':'hidden'}),
            
                // Cache original height, for use later:
                origHeight = textarea.height(),
                
                // Need clone of textarea, hidden off screen:
                clone = (function(){
                    
                    // Properties which may effect space taken up by chracters:
                    var props = ['height','width','lineHeight','textDecoration','letterSpacing'],
                        propOb = {};
                        
                    // Create object of styles to apply:
                    $.each(props, function(i, prop){
                        propOb[prop] = textarea.css(prop);
                    });
                    
                    // Clone the actual textarea removing unique properties
                    // and insert before original textarea:
                    return textarea.clone().removeAttr('id').removeAttr('name').css({
                        position: 'absolute',
                        top: 0,
                        left: -9999
                    }).css(propOb).attr('tabIndex','-1').insertBefore(textarea);				
                })(),
                lastScrollTop = null,
                updateSize = function() {					
                    // Prepare the clone:
                    clone.height(0).val($(this).val()).scrollTop(10000);				
                    // Find the height of text:
                    var scrollTop = Math.max(clone.scrollTop(), origHeight) + settings.extraSpace,
                        toChange = $(this).add(clone);					
                    // Don't do anything if scrollTip hasen't changed:
                    if (lastScrollTop === scrollTop) { return; }
                    lastScrollTop = scrollTop;					
                    // Check for limit:
                    if ( scrollTop >= settings.limit ) {
                        $(this).css('overflow-y','');
                        return;
                    }
                    // Fire off callback:
                    settings.onResize.call(this);
					
                    // Either animate or directly apply height:
                    settings.animate && textarea.css('display') === 'block' ?
                        toChange.stop().animate({height:scrollTop}, settings.animateDuration, settings.animateCallback)
                        : toChange.height(scrollTop);
                };          
            // Bind namespaced handlers to appropriate events:
            textarea
                .unbind('.dynSiz')
                .bind('keyup.dynSiz', updateSize)
                .bind('keydown.dynSiz', updateSize)
                .bind('change.dynSiz', updateSize);           
        });       
        // Chain:
        return this;        
    }; 
})(jQuery);





// Mailscript using jQuery and Ajax
$(document).ready(function() {
	
	//Hiding the reds once they have been filled in
	
		//Checking that when the contact form is loaded, if the required fields are not empty, if not error wont display
			if ($.trim($('#name').val()) != null && $.trim($('#name').val()) != '') {
				$('#red1').fadeOut('fast');
			} //end if
			
			if ($.trim($('#f').val()) != null && $.trim($('#email').val()) != '') {
				//$('#red2').fadeOut('fast');
				validateEmail();				
			} //end if	
			
			if ($.trim($('#message').val()) != null && $.trim($('#message').val()) != '') {
				$('#red4').fadeOut('fast');
			} //end if								
			
				
		//Name (Check not blank)
		$("#name").focusin(function() {
			$('#red1').fadeOut('fast');
		});
		
		$("#name").focusout(function() {
			if ($.trim($('#name').val()) == null || $.trim($('#name').val()) == '') {
				$('#red1').fadeIn('fast');
			} //end if
		});	
		
		//Email (Check not blank)
		$("#email").focusin(function() {
			$('#redemail').fadeOut('fast');
		});
		
		//email validation
		$("#email").focusout(function() {
			validateEmail();
		});	
		
		//message (Check not blank)
		$("#message").focusin(function() {
			$('#red4').fadeOut('fast');
		});
		
		$("#message").focusout(function() {
			if ($.trim($('#message').val()) == null || $.trim($('#message').val()) == '') {
				$('#red4').fadeIn('fast');
			} //end if
		});			
		
		function validateEmail ()	 {
			var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+[\.]{1}[a-zA-Z]{2,4}$/;
			var emailaddressVal = $("#email").val();
			
			if (emailReg.test(emailaddressVal) && $.trim(emailaddressVal) != '' && $.trim(emailaddressVal) != null) {
				//email not valid
				$("#redemail").fadeOut('fast');	
			} else {
				$("#redemail").fadeIn('fast');	
				//$("#redemail").removeClass('hide').fadeIn('fast');	
			}		
		}
		
			
		
	 // refresh captcha
	 $('img#refresh').click(function() {  			
			change_captcha();
	 });
	 
	 //initiate captcha
	 function change_captcha() {
		//src is relative to the form page (eg the form is in the index.php file in the parent folder, so src is relative to the index.php page, not this page
	 	document.getElementById('captcha').src ="includes/get_captcha.php?rnd=" + Math.random();
	 }		
		
	//jQuery AJAX connect
    $("#loadPost").click(function() {

		$.ajax({
			type: 'POST',
			url: 'includes/contact-send.php',
			data: {
				name : $('#name').val(),
				email : $('#email').val(),
				message : $('#message').val(),
				code : $('#code').val()			
			},
			success: function(data) {
				if ($.trim(data) == 'true') {
					DisplayAlert('Sendalertbox',100,700);
					// old code:   $("#form").html("<p>Thank you, your form has been sent</p>");
				}

				if ($.trim(data) == 'false') {
					DisplayAlert('Erroralertbox',100,700);
					// old code:   $('#captchaError-box').append('<br /><span class="red">Incorrect Captcha Code</span>');
				}
			
				if ($.trim(data) == 'aborted') {
					DisplayAlert('Erroralertbox',100,700);
					// old code:   $('#captchaError-box').append('<br /><span class="red">Incorrect Captcha Code</span>');
				}
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert('error'+' '+textStatus+' '+errorThrown);
			}			
		})	
		return false;
	});	
});


