var Cache = Class.create();
Object.extend(Cache.prototype, {
    initialize: function(id) {
        this.data = {};
        this.query(id);
    },
    query: function(id) {
        var id = parseInt(id);
        var url = "/flights/?action=cache&id=" + id;
        var options = {
            method: "post",
            onSuccess: this.onSuccess.bind(this),
            onFailure: function (response, error) {
                dispatchException(error);
            }
        };
        new Ajax.Request(url, options);
    },
    set: function() {
        $("departureDay").value   = this.data.outbound_day;
        $("departureMonth").value = this.data.outbound_date;

        $("returnDay").value      = this.data.inbound_day;
        $("returnMonth").value    = this.data.inbound_date;
        $("cabin").value          = this.data.cabin;

        if ($("departureAirport").nodeName.toLowerCase() == "input") {
            $("departureAirport").value = "[" + this.data.departure + "]";
        } else {
            $("departureAirport").value = this.data.departure;
        }

        if ($("destinationAirport").nodeName.toLowerCase() == "input") {
            $("destinationAirport").value = "[" + this.data.destination + "]";
        } else {
            $("destinationAirport").value = this.data.destination;
        }
    },
    onSuccess: function(response) {
        var xml = response.responseXML;
        var elements = ["departure", "destination",
                        "outbound_day", "outbound_date",
                        "inbound_day", "inbound_date", "cabin"];

        elements.each(function(element) {
            this.data[element] = xml.getElementsByTagName(element)[0].firstChild.nodeValue;
        }.bind(this));
        this.set();
    },
    onFailure: function(r, e) {
        dispatchException(e);
    }
});
