function getDateString() {
  var now = new Date();
  var month = now.getMonth();
  if (month < 10)
    month = "0" + month;
  var day = now.getDay();
  if (day < 10)
    day = "0" + day;
  var hour = now.getHours();
  if (hour < 10)
    hour = "0" + hour;
  var minutes = now.getMinutes();
  if (minutes < 10)
    minutes = "0" + minutes;
  var seconds = now.getMinutes();
  if (seconds < 10)
    seconds = "0" + seconds;
  return now.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds; 
}

var title, datef, data, titleinput, datainput, preview_body;

var updateTimer;

function updateLivePreview(newtitle, newdata) {
	title.innerHTML = newtitle;
	datef.innerHTML = getDateString();
	data.innerHTML = newdata;
}

function updateReset() {
	if (updateTimer) clearTimeout(updateTimer);
	updateTimer = setTimeout("updateTyped()", 200);
}

function updateTyped() {
	updateLivePreview(titleinput.value, datainput.value);
	updateTimer = null;
}

// Synchronized scrolling
var scroll_lock = 0;

function dataScroll() {
	if (scroll_lock) {
		scroll_lock = 0;
		return;
	}
	scroll_lock = 1;
	var dh = datainput.scrollHeight - datainput.clientHeight;
	var ph = preview_body.scrollHeight - preview_body.clientHeight;
	preview_body.scrollTop = (datainput.scrollTop / dh) * ph;
}

function previewScroll() {
	if (scroll_lock) {
		scroll_lock = 0;
		return;
	}
	scroll_lock = 1;
	var dh = datainput.scrollHeight - datainput.clientHeight;
	var ph = preview_body.scrollHeight - preview_body.clientHeight;
	datainput.scrollTop = (preview_body.scrollTop / ph) * dh;
}

function previewInit() {
	title = document.getElementById("title");
	datef = document.getElementById("date");
	data = document.getElementById("data");

	titleinput = document.getElementsByName("title").item(0);
	datainput = document.getElementsByName("data").item(0);

	Bytex64.DOM.addEventListener(titleinput, 'keyup', updateReset);
	Bytex64.DOM.addEventListener(datainput, 'keyup', updateReset);

	updateTyped();

	preview_body = document.getElementById('body');

	Bytex64.DOM.addEventListener(datainput, 'scroll', dataScroll);
	Bytex64.DOM.addEventListener(preview_body, 'scroll', previewScroll);

	updateLivePreview(titleinput.value, datainput.value);
}

window.addEventListener('load', previewInit, false);

