$(function() {
	$("#s").autocomplete({
		source: "search/",
		minLength: 2,
		focus: function (event, ui) {
			$(event.target).val(ui.item.label);
			return false;
		},
		select: function (event, ui) {
			$(event.target).val(ui.item.label);
			window.location = ui.item.value;
			return false;
		}
	});
});


function send_form(form, url){
	
	var form_name = form;
	var form = $("form#"+form);
	
	if(form.size()==1){
		
		$.ajax({
			cache:false,
			data:$(form).serialize(),
			dataType:"json",
			complete:function(){
			},
			error:function(xhr, status, error){
				alert("Error sending the form: '"+status+"'");
			},
			success:function(data, status){
				if(data.status=="success"){
					alert(data.message);
					enable_form(form, false);
				} else {
					alert(data.message);
					enable_form(form, false);
				}
				if(data.fields){ 
					mark_fields(form_name, data.fields);
				}
			},
			url:url
		});
		
		disable_form(form, "Sending...");
		
	} else {
		alert("Form not found");
	}
	
	return false;
	
}

function disable_form(form, message){
	$(form).find("input, textarea").each(function(){
		$(this).attr("disabled", "disabled");
	});
	if(message){
		var revert = $(form).find("input[type='submit']").val();
		$(form).find("input[type='submit']").val(message).attr("revert", revert);
	}
}

function enable_form(form, reset){
	$(form).find("input, textarea").each(function(){
		// $(this).attr("disabled", "");
		$(this).removeAttr("disabled");
		if(reset){ $(this).val(""); }
		if($(this).attr("type")=="submit"){
			var revert = $(this).attr("revert");
			// var revert = $("#email").attr("revert");
			if(revert){
				$(this).val(revert);
				$(this).attr("revert", "");
			}
		}
	});
}

function mark_fields(form, fields){
	$("#"+form+" .mark").each(function(){
		$(this).removeClass("mark");
	});
	for(var i=0; i<fields.length; i++){
		// console.log(fields[i]);
		$("#"+fields[i]).addClass("mark");
		$("label[for='"+fields[i]+"']").addClass("mark");
	}
}

var Slideshow = {
	
	currentID: 1,
	autoplayInterval: 5000,
	intervalID: null,
	
	slide: function(newID, userClick){
		if(newID!=this.currentID){
			this.fadeImages(newID);
		}
		if (userClick) { clearTimeout(this.intervalID); }
	},
	
	fadeImages: function(newID){
		var currentSlide = $("#slide-"+this.currentID);
		var newSlide = $("#slide-"+newID);
		newSlide.show();
		currentSlide.fadeOut(500, function(){
			newSlide.css("z-index", 110);
			currentSlide.css("z-index", 105);
			Slideshow.currentID = newID;
		});
	},
	
	autoPlay: function(){
		this.intervalID = setTimeout(function(){
			Slideshow.nextSlide()
		}, this.autoplayInterval);
	},
	
	nextSlide: function(){
		var possibleNewID = this.currentID + 1;
		var newID;
		if ($("#slide-"+possibleNewID).length!=1) {
			newID = 1;
		} else {
			newID = possibleNewID;
		}
		this.slide(newID);
		this.autoPlay();
	}
	
};
