DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`roadmapStop_beforeInsert`
	BEFORE INSERT ON `roadmapStop`
	FOR EACH ROW
BEGIN
	DECLARE vMaxEta DATETIME;

	SET NEW.editorFk = account.myUser_getId();

	IF NEW.description IS NOT NULL THEN
		SET NEW.description = UCASE(NEW.description);
	END IF;

	IF NEW.roadmapFk IS NOT NULL THEN
		IF NEW.eta < (SELECT etd FROM roadmap WHERE id = NEW.roadmapFk) THEN
			CALL util.throw('Departure time can not be after arrival time');
		END IF;
	END IF;

	IF NEW.roadmapFk IS NOT NULL AND NEW.eta IS NOT NULL THEN
		SELECT MAX(eta)	INTO vMaxEta
			FROM roadmapStop
			WHERE roadmapFk = NEW.roadmapFk;

		IF NEW.eta > vMaxEta OR vMaxEta IS NOT NULL THEN
			UPDATE roadmap
				SET eta = GREATEST(COALESCE(vMaxEta, NEW.eta), NEW.eta)
				WHERE id = NEW.roadmapFk;
		END IF;
	END IF;
END$$
DELIMITER ;