$(document).ready(function() {

	URL_HOME = "http://www.waybook.cz/";
	
    /**
	 * When the open event is called, this function will be used to 'open'
	 * the overlay, container and data portions of the modal dialog.
	 *
	 * onOpen callbacks need to handle 'opening' the overlay, container
	 * and data.
	 */
	function modalOpen (dialog) {
		dialog.overlay.fadeIn('fast', function () {
			dialog.container.fadeIn('normal', function () {
				//$(".reg-driver").hide();
				$(".dolni").hide();
				//$("#registracni_form").jqTransform();
				dialog.data.hide().slideDown('normal', function() {
					$(".fselect").width(164);
					$("td.right").width(130);
					$(".left").width(165);
					$("table.forms > tr > td:not(.left)").width(140);
					$("table.forms").width(305);
					setActions();
					validateForm();
				});	 
			});
		});
	}
	
	/**
	 * Nastaví akce po ukončení animace reg. formuláře
	 * 
	 */
	function setActions() {
		
		/**
		 * mouse cursor
		 */
		$('input[type="text"]').css("cursor", "text");
		
		/**
		 * enable submit button
		 */
		$("#submit").removeAttr("disabled");
		$("#submit").val($("#submit_text").val());
		
		$("#checkboxridic").click(function() {
			if ($("#checkboxridic").is(':checked')) {
				$(".dolni").slideDown('normal', function() {
					//$("tr").removeAttr("style");
					$("#barva").css("color", $("#barva").val());
					$("#barva").css("background-color", $("#barva").val());
				});
			}
			else {
				$(".dolni").slideUp('fast');
			}
			//$(".reg-driver").removeAttr("style");
			$(".fselect").width(164);
		});
		
		$('#odjezd').datepicker({
	    	duration: '',
	        showTime: true,
	        constrainInput: false,
			minDate: minimalniDen,
			maxDate: maximalniDen,
			time24h: true
	     });
		$('#odjezd1').datepicker({
	    	duration: '',
	        showTime: true,
	        constrainInput: false,
			minDate: minimalniDen,
			maxDate: maximalniDen,
			time24h: true
	     });
		$('#odjezd2').datepicker({
	    	duration: '',
	        showTime: true,
	        constrainInput: false,
			minDate: minimalniDen,
			maxDate: maximalniDen,
			time24h: true
	     });
		 
		 // AJAX - počet míst vybraného vozidla
		 $("#select_auto").change(function() {
		 	var selekt = '<select name="seat" id="seat" class="seat">';
			var pocet = 0;
			
			$.post(URL_HOME+"ajax/fce.php", {akce: "pocet_mist", id: $("#select_auto").val()}, function(data) {
				pocet = data;
				for(var i=pocet-1; i>0; i--) 
					selekt = selekt + '<option value="'+i+'"> &nbsp; '+i+'</option>"'
				selekt = selekt + '</select>'
	
				$("#td-pocet-sedadel").html(selekt);	
				$("#seat").width(164);
			});
		 });
		 
		  /**
		  * AUTOCOMPLETE
		  */
		 
		$("#cesta1").autocomplete(cities, {
			autoFill: true,
			mustMatch: true,
			formatItem: function(row, i, max) {
				return /*i + "/" + max + ": \"" + */row.obec + " (okres " + row.okres + ")";
			},
			formatMatch: function(row, i, max) {
				return row.obec + " (okres " + row.okres + ")";
			},
			formatResult: function(row) {
				return row.obec + " (okres " + row.okres + ")";
			}
		});
		$("#cesta2").autocomplete(cities, {
			autoFill: true,
			mustMatch: true,
			formatItem: function(row, i, max) {
				return /*i + "/" + max + ": \"" + */row.obec + " (okres " + row.okres + ")";
			},
			formatMatch: function(row, i, max) {
				return row.obec + " (okres " + row.okres + ")";
			},
			formatResult: function(row) {
				return row.obec + " (okres " + row.okres + ")";
			}
		});
		$("#cestaB").autocomplete(cities, {
			autoFill: true,
			multiple: true,
			mustMatch: true,
			formatItem: function(row, i, max) {
				return /*i + "/" + max + ": \"" + */row.obec + " (okres " + row.okres + ")";
			},
			formatMatch: function(row, i, max) {
				return row.obec + " (okres " + row.okres + ")";
			},
			formatResult: function(row) {
				return row.obec + " (okres " + row.okres + ")";
			}
		});
		
		/**
		 * výchozí hodonoty formuláře
		 */
		$("#cesta1").DefaultValue("Zadejte město...");
		$("#cesta2").DefaultValue("Zadejte město...");
		$("#cestaB").DefaultValue("Můžete zadat více měst...");
		
	}
	
	
	/**
	 * Zakáže přesměrování a zobrazí registrační formulář nebo editaci údajů
	 * 
	 */
	function registrace_editace(trida, volba1) {
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: volba1}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");
    }
	
	$(".registrace").click(function(){
		var href = $(".registrace").attr("href");
		$(".registrace").removeAttr("href");
		registrace_editace(".registrace", "registrace");
		
		$(".registrace").attr("href", href);
		return false;
	});
	
	$(".editace-udaju").click(function(){
		var href = $(".editace-udaju").attr("href");
		$(".editace-udaju").removeAttr("href");
		registrace_editace(".editace-udaju", "editace");
		
		$(".editace-udaju").attr("href", href);
		return false;
	});
	
	$(".editace-avataru").click(function(){
		var href = $(".editace-avataru").attr("href");
		$(".editace-avataru").removeAttr("href");
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: "avatar"}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");		
		$(".editace-avataru").attr("href", href);
		return false;
	});
	
	$(".hledat_jizdu").click(function(){
		var href = $(this).attr("href");
		$(this).removeAttr("href");
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: "hledani"}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");		
		$(this).attr("href", href);
		return false;
	});
	$(".editace-hesla").click(function(){
		var href = $(this).attr("href");
		$(this).removeAttr("href");
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: "zmena_hesla"}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");		
		$(this).attr("href", href);
		return false;
	});
	$(".hodnoceni_jizdy").click(function(){
		var href = $(this).attr("href");
		$(this).removeAttr("href");
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: "hodnoceni_jizdy", id: $(this).attr("id")}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");		
		$(this).attr("href", href);
		return false;
	});
	$(".modify_ride").click(function(){
		var href = $(this).attr("href");
		$(this).removeAttr("href");
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: "uprava_jizdy", id: $(this).attr("id")}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");		
		$(this).attr("href", href);
		return false;
	});
	$(".cancel_ride").click(function(){
		var href = $(this).attr("href");
		$(this).removeAttr("href");
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: "zruseni_jizdy", id: $(this).attr("id")}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");		
		$(this).attr("href", href);
		return false;
	});
	
	/**
	 * funkce na změnu, smazání, vytvoření auta
	 * @param {Object} volba
	 */
	function registrace_editace_smazani_auta(volba1, id1) {
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: volba1, id: id1}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");
    }
	$(".pridat-vuz").click(function(){
		var href = $(this).attr("href"); $(this).removeAttr("href");
		registrace_editace_smazani_auta("pridat_auto", $(this).attr("id"));
		$(this).attr("href", href); return false;
	});
	$(".upravit-vuz").click(function(){
		var href = $(this).attr("href"); $(this).removeAttr("href");
		registrace_editace_smazani_auta("upravit_auto", $(this).attr("id"));
		$(this).attr("href", href); return false;
	});
	$(".smazat-vuz").click(function(){
		var href = $(this).attr("href"); $(this).removeAttr("href");
		registrace_editace_smazani_auta("smazat_auto", $(this).attr("id"));
		$(this).attr("href", href); return false;
	});
	
	/**
	 * Zakáže přesměrování a zobrazí formulář pro vypsání jízdy
	 * 
	 */
	$(".vypsat_jizdu").click(function() {
		var href = $(".vypsat_jizdu").attr("href");
		$(".vypsat_jizdu").removeAttr("href");
		
		if (ma_auto) {
			var regform;
			$.post(URL_HOME + "ajax/forms.php", {
				volba: "vypsat_jizdu"
			}, function(data){
				if (true) {
					regform = data.txt;
					$.modal(regform, {
						onOpen: modalOpen,
						position: [100, ]
					});
				}
			}, "json");
		}
		else {
			var regform;
			$.post(URL_HOME + "ajax/forms.php", {
				volba: "neni_auto"
			}, function(data){
				if (true) {
					regform = data.txt;
					$.modal(regform, {
						onOpen: modalOpen,
						position: [100, ]
					});
				}
			}, "json");
		}
		
		$(".vypsat_jizdu").attr("href", href);
		return false;
    });
	
	// nastavení výšky text divu
	var windowheight = $(".allpage").height();
	var destheight = $(document).height() - $(".allpage").height() + $(".textcontent").height() - 30;
	if (destheight > $(".textcontent").height())
		$(".textcontent").animate({
			height: destheight
			}, 2000);
		
	// nastavení výšky divu seznamu jízd
	function resizeTab(){
		var levy_height = $("div.nabidka > div.obsah").height();
		var pravy_height = $(".detail > div.obsah").height();
		if (!pravy_height) {
			pravy_height = $("div#main-logged").height();
			pravy_height = pravy_height - 55;
		}
		else {
			pravy_height = pravy_height - 15;
		}
		if (pravy_height > levy_height) {
			$('#obsah-jizdy').jScrollPaneRemove();
			$("div.nabidka > div.obsah").animate({
				height: pravy_height
			}, 000, function(){
			//$('#obsah-jizdy').jScrollPane({showArrows:true, scrollbarWidth: 15, arrowSize: 16});
			});
		}
		else if (pravy_height < levy_height) {
			// jScrollPane
			//$('#obsah-jizdy').jScrollPane({showArrows:true, scrollbarWidth: 15, arrowSize: 16});
			/*$(".detail > div.obsah").animate({
				height: levy_height + 15
			}, 000);*/
			//$(".detail > div.obsah").height(levy_height + 15);
		}
	}
	resizeTab();
		
	//$(".reg-driver").hide();	
	setActions();
	
	/**
	 * 
	 * VALIDACE REGISTRAČNÍHO FORMULÁŘE
	 */
	function validateForm(){
		// funkce na ověření, zda již zadané uživatelské jméno v DB existuje
		jQuery.validator.addMethod('usernameCheck', function(username){
			var postURL = URL_HOME + "ajax/nick_check.php";
			$.ajax({
				cache: false,
				async: false,
				type: "POST",
				data: "username=" + username,
				url: postURL,
				success: function(msg){
					result = (msg == '1' ? false : true);
				}
			});
			return result;
		}, '');
		
		jQuery.validator.addMethod("alphanumeric", function(value, element) {
			return this.optional(element) || /^\w+$/i.test(value);
		}, "Letters, numbers, spaces or underscores only please"); 
		
		jQuery.validator.addMethod("nowhitespace", function(value, element) {
			return this.optional(element) || /^\S+$/i.test(value);
		}, "No white space please"); 
		jQuery.validator.addMethod('greaterThan', function(value, element, param) { 
			return ( IsNaN( value ) && IsNaN( jQuery(param).val() ) ) || ( value > jQuery(param).val() ); 
		}, 'Must be greater than {0}.' );
		
		// validace registračního formuláře
		$("#registracni_form").validate({
			rules: {
				nick: {
					required: true,
					alphanumeric: true,
					nowhitespace: true,
					minlength: 4,
					maxlength: 12,
					usernameCheck: true
				},
				name: {
					required: true,
					maxlength: 50
				},
				surname: {
					required: true,
					maxlength: 50
				},
				email: {
					required: true,
					email: true,
					maxlength: 50
				},
				pass1: {
					required: true,
					rangelength: [5, 40]
				},
				vyrobce: {
					minlength: 1,
					required: function(element) { return $('#checkboxridic').is(':checked')},
					number: true
				},
				model: {
					required: function(element) { return $('#checkboxridic').is(':checked')}
				},
				rok: {
					required: function(element) { return $('#checkboxridic').is(':checked')},
					number: true
				},
				seat_count: {
					required: function(element) { return $('#checkboxridic').is(':checked')},
					number: true
				}

			},
			messages: {
				nick: {
					usernameCheck: "<font color='red'> Toto jméno už je obsazené, zvolte jiné.</font>",
					alphanumeric: "<b><font color='red'> Zadávejte pouze znaky a-z A-Z 0-9.</font>",
					nowhitespace: "<b><font color='red'> Zadávejte pouze znaky a-z A-Z 0-9.</font>",
					minlength: "<b><font color='red'> Prosím, zadejte nejméně 4 znaky.</font>"
				}
			}/*,
			errorPlacement: function(error, element) {
		    	error.appendTo(element.parent("td").parent("tr") .next("td").next("td"));
		   	}*/
		});
		
		
		// validace formuláře pro vypsání jízdy
		$("#form_jizda").validate({
			rules: {
				odjezd: {
					required: true
				},
				cesta1: {
					required: true
				},
				cesta2: {
					required: true
				},
				auto: {
					minlength: 1,
					required: true //function(element) { return $("#selectauto").val() == 0}
				},
				seat: {
					required: true,
					number: true
				},
				cena: {
					required: true,
					number: true
				}
			},
			messages: {
				seat: {
					required: "<b><font color='red'> Špatný počet míst.</font>"
				}
			}
		});
		
		// validace formuláře pro auto
		$("#car_form").validate({
			rules: {
				vyrobce: {
					minlength: 1,
					required: true,
					number: true
				},
				model: {
					required: true
				},
				rok: {
					required: true,
					number: true
				},
				seat_count: {
					required: true,
					number: true
				}
			}
		});
		
	}
	validateForm();
	
	$(".dolni").hide();
	$(".fselect").width(164);
	
	 
	/**
	 * KOMENTÁŘE
	 */
	var textarea_used = false;
	$(".textclosed").click(function() {
		if (!textarea_used) {
			$("#textareacomment").val("");
			textarea_used = true;
		}
		$(this).removeClass("textclosed").addClass("textopen");
		$("#submitcomment").show(0);
		textopen_blur();
	})
	function textopen_blur(){
		$(".textopen").blur(function(){		
			if ($("#textareacomment").val() == "") {
				$("#submitcomment").hide(0)
	 			$("#textareacomment").val("Začněte psát...");
	 			textarea_used = false;
				var size_open = $(this).height() + $("#submitcomment").height() + 2;
	 			$(this).removeClass("textopen").addClass("textclosed");
				var size_closed = $(this).height();
				
				//$(".detail > div.obsah").height($(".detail > div.obsah").height() + size_closed - size_open);
				//$("div.nabidka > div.obsah").height($("div.nabidka > div.obsah").height() + size_closed - size_open + 15);
	 		}
	 	})
		resizeTab();
	}
	textopen_blur();$("#submitcomment").hide(0);
	 
	/**
	 * Scroll k vybrané jízdě
	 */
	jQuery.easing.bounceout = function(p, n, firstNum, delta, duration) {
		if ((n/=duration) < (1/2.75)) {
	    	return delta*(7.5625*n*n) + firstNum;
	    } else if (n < (2/2.75)) {
	    	return delta*(7.5625*(n-=(1.5/2.75))*n + .75) + firstNum;
	    } else if (n < (2.5/2.75)) {
	    	return delta*(7.5625*(n-=(2.25/2.75))*n + .9375) + firstNum;
	    } else {
	    	return delta*(7.5625*(n-=(2.625/2.75))*n + .984375) + firstNum;
	    }
	};
	var divOffset = $('#obsah-jizdy').offset().top;
    var pOffset = $('#obsah-jizdy div.jizda.active').offset().top;
    var pScroll = pOffset - divOffset - ($('#obsah-jizdy').height() / 2) + 10;
    $('#obsah-jizdy').animate({scrollTop: '+=' + pScroll + 'px'}, 0/*, 'bounceout'*/);
	
	$("table.hoverenabled tr.even td, table.hoverenabled tr.odd td").mouseover(function() {
		$(this).parent().children("td").css("background-color", "#ffd4b4");
		$(this).parent().children("td").css("cursor", "default");
	})
	$("table.hoverenabled tr.even td, table.hoverenabled tr.odd td").mouseout(function() {
		$(this).parent().children("td").removeAttr("style");
		$(this).parent().children("td").css("cursor", "auto");
	})
	
	/**
	 * hide/show hodnocení
	 */
	$("tr.hodnoceni").hide(0);
	
	function ukazat_hodnoceni(){
		$(".ukazat_hodnoceni").click(function() {
			if ($(this).html() == "zobrazit") {
				$("#ukaz-" + $(this).attr("id")).show();//slideDown(1000);
				$(this).html("schovat");
			}
			else {
				$("#ukaz-" + $(this).attr("id")).hide();//slideUp(1000);
				$(this).html("zobrazit");				
			}
			return false;
		})
	};
	ukazat_hodnoceni();
	
	/**
	 * poptávky
	 */
	
	$("div#obsah-poptavky").hide();
	$("a.poptavky").click(function(){
		$("div#obsah-jizdy").hide();
		$("div#obsah-poptavky").show();
		$("div.heading li.m01 span").attr("class", "inactive");
		$("div.heading li.m02 span").attr("class", "active");
		return false;
	});
	
	
	$(".pridat-poptavku").click(function(){
		var href = $(this).attr("href"); $(this).removeAttr("href");
		var regform;
		$.post(URL_HOME+"ajax/forms.php", {volba: "zadat_poptavku"}, function(data) {
			if (true) {
				regform = data.txt;
				$.modal(regform, {
					onOpen: modalOpen,
					position: [100,]
				});
			}
		}, "json");	
		$(this).attr("href", href); return false;
	});

});