$(document).ready(function(){

	$("form.validate").submit(function() {

		$("form.validate .alert").removeClass("alert");

		var msg = '';
		var valid = true;
		var email_pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/i;

		$(this).find(".required").each(function() {
			var value = $(this).val();
			if(value == "" || ($(this).is(".email") && !email_pattern.test(value))) {
				valid = false;
				var title = $(this).prev("label").text() || $(this).attr("title");
				msg += '\n-> '+title.replace(/[\*|:]/gi, "")+' is required';
				$(this).addClass("alert");
			}
		});

		if(!valid) {

			if(msg != '') {
				alert('Please fill in these fields. Thanks.'+msg);
				$(".alert:first", this).focus();
				return false;
			}

			return false;
		}
	});

	if($(".mycarousel").length) {

		$(".mycarousel").jcarousel({
			scroll: 1,
			animation: 1500, //Time picture takes to change to next one - 1500 stands for 1.5 sec
			wrap: 'circular',
			auto: 6 //Time picture stays before changing - in seconds
		});
	}

	if($(".gallery").length) {

		$(".gallery ul li a").click(function(){
			var parent = $(this).parents(".gallery");
			$("ul li a", parent).removeClass("on");
			$(this).addClass("on");
			load_img(this, $(".large", parent));
			return false;
		});

	}

});

function load_img(source, destination) {
	var path = $(source).attr('href');
	$('img:first', destination).remove();
	var imgsrc = path;
	var newimg = new Image();
	newimg.src = imgsrc;
	newimg.onload = function() {
		var randomnumber = Math.floor(Math.random()*11);
		$(destination).append('<img src="'+imgsrc+'" />');
		newimg.onload = function(){};
	}
	newimg.src = imgsrc;
}
