/**
 * 
 */

function onExportICS() {
    var exporter = new Timegrid.ExportICS(miniEventSource);
    var cal = exporter.render();
    var formbody = document.getElementById("ical-reflection-body");
    formbody.value = cal;
    var calform = document.getElementById("ical-reflection");
    calform.submit();
}

Timegrid.ExportICS = function(source) {
    this._source = source;
    this._icsHeader = "BEGIN:VCALENDAR\nCALSCALE:GREGORIAN\nPRODID:-//Zepheira LLC//Scheduler Calendar//EN\nVERSION:2.0\nMETHOD:PUBLISH\n";

    this._icsFooter = "END:VCALENDAR\n";

    this._icsBody = "";

    this._icsFinal = "";
}

Timegrid.ExportICS.prototype.build = function() {
    var it = this._source.getAllEventIterator();
    while (it.hasNext()) {
        var event = it.next();
        this.buildEvent(event);
    }
}

Timegrid.ExportICS.prototype.buildDate = function(date) {
    return date.getUTCFullYear() + "" + this.fillDigits(date.getUTCMonth()+1) + "" + this.fillDigits(date.getUTCDate()) + "T" + this.fillDigits(date.getUTCHours()) + "" + this.fillDigits(date.getUTCMinutes()) + "" + this.fillDigits(date.getUTCSeconds()) + "Z";
}

Timegrid.ExportICS.prototype.fillDigits = function(number) {
    if (number < 10) {
        return "0" + number;
    } else {
        return number;
    }
}

Timegrid.ExportICS.prototype.buildEvent = function(event) {
    var vevent = "BEGIN:VEVENT\n";
    vevent    += "DTSTART:" +  this.buildDate(event.getStart()) + "\n";
    vevent    += "DTEND:" + this.buildDate(event.getEnd()) + "\n";
    vevent    += "DTSTAMP:" + this.buildDate(new Date()) + "\n";
    vevent    += "UID:" + event.getID() + "\n";
    if (event.getText())
        vevent    += "SUMMARY:" + event.getText() + "\n";
    if (event.getDescription())
        vevent    += "DESCRIPTION:" + event.getDescription().replace(/,/,"\\,").replace(/"/,"\\\"").replace(/\n/,"\\n") + "\n";
    if (event.getLink())
        vevent    += "URL;VALUE=URI:" + event.getLink() + "\n";
    vevent    += "END:VEVENT\n";

    this._icsBody += vevent;
}

Timegrid.ExportICS.prototype.render = function() {
    this.build();
    this._icsFinal = this._icsHeader + this._icsBody + this._icsFooter;
    return this._icsFinal;
}
