/*
 * vc.js - a way to do version control using HTML tags
 *
 * Copyright (C) 2009, Rudolf Olah
 *
 * Requires jQuery, tested against v1.3.2
 */

function parseVersionDate(s) {
    // s is a string, returns a Date object

    // the format is "YYYY-MM-DDThh:mm:ssZ", where YYYY is the year,
    // MM is the month, DD is the day, hh is the hour, mm is the
    // minute, ss is the second. T is a separator and Z is the
    // timezone which is greenwich mean time

    // TODO: parse out the time components
    return new Date(s.substr(0, 4), s.substr(5, 2) - 1, s.substr(8, 2));
}

function versionByTag(tagName) {
    // retrieves all tags related to a tagged version (a.k.a. a
    // version that is named by the user)
    return $("ins." + tagName + ", del." + tagName); 
}

function versionDates() {
    // Returns an array of DateTime objects of all INS and DEL
    // elements, sorted from oldest date to newest date
    return jQuery.map($("[datetime]"),
		      function (e, i) {
			  return parseVersionDate(e.getAttribute("datetime"));
		      }).sort(function (a, b) { return a >= b; });
}

function versionDateSelector(date) {
    var m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    var d = date.getDate();
    d = d < 10 ? "0" + d : d;
    return "[datetime^=" + date.getFullYear() + "-" + m + "-" + d + "]";
}

function versionByDate(year, month, day) {
    return $(versionDateSelector(new Date(year, month - 1, day)));
}

function applyChangesUntilDate(year, month, day) {
    var date = new Date(year, month - 1, day);
    var dates = versionDates();
    for (var i = 0; i < dates.length; i++) {
	var dateSelector = versionDateSelector(dates[i]);
	// applied change
	if (dates[i] <= date) {
	    $("ins" + dateSelector).fadeIn(800); // show
	    $("del" + dateSelector).fadeOut(800); // hide
	    var di = $("del ins" + dateSelector);
	    for (var j = 0; j < di.length; j++)
		$(di[j].parentNode).fadeIn(800); // show
	} else {
	    // change not yet applied
	    $("ins" + dateSelector).fadeOut(800); // hide
	    $("del" + dateSelector).fadeIn(800); // show
	}
    }
}
