﻿function showStatus(data){
	var html = '<p class="'+ (data.err === 0 ? "ok" : "err") +'">'+ data.msg +'</p>',
	o = $("#status");
	o.html(html).center().fadeIn();
	setTimeout(function() {o.fadeOut(100);}, 4000);
}

function validate(f){
	var inputs = f.find('input.required, textarea.required'),
	valid = true,

	vldt = {
		required : function(v,i) { return { r : !!v ,  msg : 'Nie sú výplnené povinné hodnoty'}; },
		email	 : function(v,i) { return { r : v.match( /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/ ), msg : 'Neplatná e-mailová adresa'}; },
		fiveplus : function(v,i) { return { r : v.length >= 5, msg : 'Hodnota musí mať min. 5 znakov'} ;},
		numeric  : function(v,i) { return { r : !isNaN(v), msg : 'Hodnota '+v+' nie je číslo.'} ;},
		mobil	 : function(v,i) { return { r : v.length > 8 && v.length <=10,  msg : 'Hodnota musí mať 9-10 znakov'} ;}
	};
	inputs.removeClass('formerr');
	inputs.each(function(){
		var input = $(this),
			val = input.val(),
			cls = input.attr("class").split(' ');

		for(i in cls){
			if(vldt.hasOwnProperty(cls[i])){
				var res = vldt[cls[i]](val,input);
				if(!res.r){
					input.addClass('formerr');
					showStatus({ err : 1, msg : res.msg});
					valid = false;
				}
			}
		}
	});
	return valid;	
}

function is_numeric(n){
    return !isNaN(parseInt(n)) && isFinite(n);
}

function renameArr(a){
	var d = {};	
	for (i in a) {
		d[a[i].name] = a[i].value;
	}
	return d;
}

function slideShow() {
	$('#slider img').css({opacity: 0.0});
	$('#slider img:first').css({opacity: 1.0});
	setInterval('gallery()',5000);
}

function gallery() {
	var current = ($('#slider img.show')?  $('#slider img.show') : $('#slider img:first')),
	next = ((current.next().length) ? ( (current.next().hasClass('r')) ? $('#slider img:first') :current.next()) : $('#slider img:first'));	
	next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);
	current.animate({opacity: 0.0}, 1000).removeClass('show');
}


$(function() {
		slideShow();
		$('.thumb').lightBox();
		
		$('form').submit(function(){
			var o = $(this),  
			arr = o.serializeArray(),
			data = renameArr(arr);
			if(!validate( o )){
				return false;
			}

			$.getJSON("/inc/ajax.php?cb=?", data, function(json) {  
					if(json.err === 0){
						$('form').html(json.html);	
					}else{
						showStatus(json);
					}
					
				});
			return false;
		});

});


jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
};

