(function () {
    // Namespace
    var my = window.my = window.my || {};

    // Model - corresponds to data returned by services
    my.PackageReference = function (packagename, packageID) {
        this.packagename = packagename;
        this.packageID = packageID;
    };

    my.PackageDetail = function (packagename, description, tourpicurl) {
        this.packagename = ko.observable(packagename);
        this.description = ko.observable(description);
        this.tourpicurl = ko.observable(tourpicurl);
    };

    // View model
    my.ViewModel = function () {
        var self = this;
        self.availablePackages = ko.observableArray([]),
        self.selectedPackageID = ko.observable(), // Nothing selected by default
        self.selectedPackageDetail = new my.PackageDetail(),
        self.loadPackages = function () {
            $.ajax({
                type: "GET",
                url: "/Datasources/Packages",
                dataType: "json",
                success: function (json) {
                    self.availablePackages.removeAll();
                    $.each(json, function (i, item) {
                        self.availablePackages.push(
                             new my.PackageReference(item.packagename, item.packageID));
                    });
                }
            });
        },
        self.selectedPackageID.subscribe(function () {
            var url = "/Datasources/PackageDetails/" + self.selectedPackageID();
            $.ajax({
                type: "GET",
                url: url,
                dataType: "json",
                success: function (json) {
                    self.selectedPackageDetail.packagename(json.packagename);
                    self.selectedPackageDetail.description(json.description);
                    self.selectedPackageDetail.tourpicurl(json.tourpicurl);
                }
            });
        }, self);
    };
})();
