
function koUser(user) {
    //this.self = this;
    this.AccountNumber = user.AccountNumber || '';
    this.OrganizationName = user.OrganizationName || '';
    this.Email = ko.observable(user.Email || '');
    this.PartyType = user.PartyType || '';
    this.BizAreaCode = ko.observable(user.BizAreaCode || '');
    this.BizCountry = ko.observable(user.BizCountry || '');
    this.BizExtension = ko.observable(user.BizExtension || '');
    this.BizPhoneNumber = ko.observable(user.BizPhoneNumber || '');
    this.PersonalAreaCode = ko.observable(user.PersonalAreaCode || '');
    this.PersonalCountry = ko.observable(user.PersonalCountry || '');
    this.PersonalExtension = ko.observable(user.PersonalExtension || '');
    this.PersonalPhoneNumber = ko.observable(user.PersonalPhoneNumber || '');
    this.PersonalFaxNumber = ko.observable(user.PersonalFaxNumber || '');
    this.Person_FirstName = ko.observable(user.Person_FirstName || '');
    this.Person_LastName = ko.observable(user.Person_LastName || '');
    this.Person_MiddleName = ko.observable(user.Person_MiddleName || '');
    this.IsPrimary = user.IsPrimary == true;

    this.IsDistributor = this.PartyType == "ORGANIZATION";

    var addrArray = [];

    if (user.Addresses) {
        for (var i = 0; i < user.Addresses.length; i++) {
            addrArray.push(new koAddress(user.Addresses[i]));
        }
    }
    this.Addresses = ko.observableArray(addrArray);

    var dropshipArray = [];
    if (user.DropshipAddresses) {
        for (var i = 0; i < user.DropshipAddresses.length; i++) {
            dropshipArray.push(new koAddress(user.DropshipAddresses[i]));
        }
    }
    this.DropshipAddresses = ko.observableArray(dropshipArray);

    //computed
    this.Fullname = ko.computed(function () {
        return this.Person_FirstName() + " " + this.Person_MiddleName() + " " + this.Person_LastName();
    }, this);

    this.AddressesForShipping = ko.computed(function () {
        var list = [];
        ko.utils.arrayForEach(this.Addresses(), function (item) {
            if (item.SiteUseCode() == "1") {
                item.AddressGroupType = '';
                list.push(item);
            }
        });
        ko.utils.arrayForEach(this.DropshipAddresses(), function (item) {
            item.AddressGroupType = '[Past Dropship] ';
            list.push(item);
        });
        return list;
    }, this);
    this.AddressesForBilling = ko.computed(function () {
        return ko.utils.arrayFilter(this.Addresses(), function (item) {
            return item.SiteUseCode() == "0";
        });
    }, this);

    //more view aids
    this.editingAddress = ko.observable();
    this.editingCard = ko.observable();
    this.editing = ko.observable(false);


};

ko.utils.extend(koUser.prototype, {
    getFromServer: function () {
        var a = $.ajax({
            url: ko__pathToRoot + "/ideos/b2b2cUserService.svc/user/" + new Date().getTime(),
            type: "GET",
            timeout: 60000
        });
        a.fail(function (obj) {
            //console.log(obj);
        });
        return a;
    },
    addNewAddress: function () {
        var nwAddr = new koAddress({});
        this.Addresses.push(nwAddr);
        ko.editable(nwAddr);
        nwAddr.beginEdit();
        this.editingAddress(nwAddr);
    },
    addNewShippingAddress: function () {
        var nwAddr = new koAddress({});
        nwAddr.SiteUseCode("1");
        this.Addresses.push(nwAddr);
        ko.editable(nwAddr);
        nwAddr.beginEdit();
        this.editingAddress(nwAddr);
    },
    addNewBillingAddress: function () {
        var nwAddr = new koAddress({});
        nwAddr.SiteUseCode("0");
        this.Addresses.push(nwAddr);
        ko.editable(nwAddr);
        nwAddr.beginEdit();
        this.editingAddress(nwAddr);
    },
    editAddress: function (addr) {

        ko.editable(addr);
        addr.beginEdit();

        this.editingAddress(addr);
    },
    editAddressCommit: function (addr) {
        addr.commit();
        vm.user().editingAddress(undefined);
        vm.user().sendToServer('address');
    },
    editAddressCancel: function (addr) {
        addr.rollback();
        vm.user().editingAddress(undefined);
        vm.user().cleanAddresses();
    },
    addNewCard: function (addr) {
        var nwcard = new koCard({ LocationId: addr.LocationId() });
        addr.Cards.push(nwcard);
        ko.editable(nwcard);
        nwcard.beginEdit();
        this.editingCard(nwcard);
    },
    editCard: function (card) {

        ko.editable(card);
        card.beginEdit();

        this.editingCard(card);
    },
    editCardCommit: function (card) {
        card.commit();

        var edte = new Date(card.ExpirationYear(), card.ExpirationMonth(), 1);
        //console.log(card.ExpirationYear(), card.ExpirationMonth(), edte);
        card.ExpirationDate(edte.toMSJSON());

        vm.user().editingCard(undefined);
        vm.user().sendToServer('card');
    },
    editCardCancel: function (card) {
        card.rollback();
        vm.user().editingCard(undefined);
        vm.user().cleanCards();
    },
    sendToServer: function (specifics) {
        specifics = specifics || "";
        if (specifics.length > 0) specifics += "/";
        var cust = ko.toJS(this);
        cust.AddressesForShipping = [];
        cust.DropshipAddresses = [];
        var jsonstring = JSON.stringify(cust);
        ajaxHelper.request({
            id: 'noty-user-sendToServer',
            waitingText: "Saving Profile Information...",
            url: ko__pathToRoot + "/sitefinity/services/ideosity/b2b2cUserSecureService.svc/user/update/" + specifics + new Date().getTime(),
            type: "POST",
            data: jsonstring
        }).done(function (data) {
            if (data.cssClass == "ok") {
                window.location = window.location;
            } else {
                noty({ type: "error", text: data.message });
            }
        });
    }
    ,
    selectAddressForShipping: function (addr) {
        $.ajax({
            url: ko__pathToRoot + "/ideos/kartService.svc/checkout/shipto/" + addr + "/" + new Date().getTime(),
            type: "GET",
            timeout: 25000
        }).done(function (data) {
            if (data.cssClass == "ok") {

            } else {
                noty({ type: "error", text: data.message });
            }
        });
    },
    selectAddressForBilling: function (addr) {
        $.ajax({
            url: ko__pathToRoot + "/ideos/kartService.svc/checkout/billto/" + addr + "/" + new Date().getTime(),
            type: "GET",
            timeout: 20000
        }).done(function (data) {
            if (data.cssClass == "ok") {

            } else {
                noty({ type: "error", text: data.message });
            }
        });
    },
    selectCardForBilling: function (card) {
        //vm.checkout().BillingCard(card);
        $.ajax({
            url: ko__pathToRoot + "/ideos/kartService.svc/checkout/billto/card/" + card + "/" + new Date().getTime(),
            type: "GET",
            timeout: 20000
        }).done(function (data) {
            if (data.cssClass == "ok") {

            } else {
                noty({ type: "error", text: data.message });
            }
        });
    },
    selectShippingMethod: function (method) {
        $.ajax({
            url: ko__pathToRoot + "/ideos/kartService.svc/checkout/shipto/method/" + method + "/" + new Date().getTime(),
            type: "GET",
            timeout: 20000
        }).done(function (data) {
            if (data.cssClass == "ok") {

            } else {
                noty({ type: "error", text: data.message });
            }
        });
    },
    cleanCards: function () {
        for (var i = 0; i < this.Addresses().length; i++) {
            this.Addresses()[i].cleanCards();
        }
    },
    cleanAddresses: function () {
        var list = ko.utils.arrayFilter(this.Addresses(), function (item) {
            return item.LocationId() != '-1';
        }, this);
        this.Addresses(list);
    },
    editProfile: function () {
        ko.editable(this);
        this.beginEdit();
        this.editing(true);
    },
    editProfileCancel: function () {
        this.rollback();
        this.editing(false);
    },
    editProfileCommit: function () {
        this.commit();
        this.editing(false);
        this.sendToServer();
    }
});


function koAddress(addr) {
    this.Line1 = ko.observable(addr.Line1 || '');
    this.Line2 = ko.observable(addr.Line2 || '');
    this.Line3 = ko.observable(addr.Line3 || '');
    this.City = ko.observable(addr.City || '');
    this.State = ko.observable(addr.State || '');
    this.ZipCode = ko.observable(addr.ZipCode || '');
    this.Country = ko.observable(addr.Country || '');
    this.LocationId = ko.observable(addr.LocationId || '-1');
    this.SiteUseCode = ko.observable(addr.SiteUseCode || '0');
    this.IsPrimary = ko.observable(addr.IsPrimary || false);
    this.UseSameAddress = ko.observable(false);

    this.ValidationMessage = ko.observable('');

    var cardArray = [];

    if (addr.Cards) {
        for (var i = 0; i < addr.Cards.length; i++) {
            cardArray.push(new koCard(addr.Cards[i]));
        }
    }
    this.Cards = ko.observableArray(cardArray);

    //computed
    this.AddressAsCard = ko.computed(function () {
        var x = this.Line1();
        if (this.Line2().length > 0) x += "<br/>" + this.Line2();
        if (this.Line3().length > 0) x += "<br/>" + this.Line3();
        return x;
    }, this);

    this.AddressAsRow = ko.computed(function () {
        var x = this.Line1();
        if (this.Line2().length > 0) x += " / " + this.Line2();
        if (this.Line3().length > 0) x += " / " + this.Line3();
        return x;
    }, this);

    this.Type = ko.computed(function () {
        switch (this.SiteUseCode()) {
            case "0": return "Billing";
            case "1": return "Shipping";
        }
        return "Unknown";
    }, this);

    this.IsPrimaryAsString = ko.computed({
        read: function () {
            if (!vm.user()) return "true";
            if (!vm.user().Addresses()) return "true";
            if (vm.user().Addresses().length == 0) return "true";
            if (this.Type() == "Billing") {
                if (vm.user().AddressesForBilling().length == 0) return "true";
            }
            if (this.Type() == "Shipping") {
                if (vm.user().AddressesForShipping().length == 0) return "true";
            }
            return (this.IsPrimary() ? "true" : "false");
        },
        write: function (value) { this.IsPrimary(value == "true"); }
    }, this);

    this.IsSelectedForShipping = ko.computed(function () {
        if (!vm.checkout()) return false;
        if (!vm.checkout().ShippingAddress()) return false;
        return vm.checkout().ShippingAddress().LocationId() == this.LocationId();
    }, this);

    this.IsSelectedForBilling = ko.computed(function () {
        if (!vm.checkout()) return false;
        if (!vm.checkout().BillingAddress()) return false;
        return vm.checkout().BillingAddress().LocationId() == this.LocationId();
    }, this);

    this.IsValid = ko.computed(function () {
        this.ValidationMessage('');
        if (this.Line1().length == 0) {
            this.ValidationMessage('Address line 1 cannot be empty.');
            return false;
        }
        if (this.City().length == 0) {
            this.ValidationMessage('City cannot be empty.');
            return false;
        }
        if (this.State().length == 0) {
            this.ValidationMessage('State cannot be empty.');
            return false;
        }
        return true;
    }, this);

};

ko.utils.extend(koAddress.prototype, {
    sendToServer: function () {
        var addr = ko.toJS(this);
        var jsonstring = JSON.stringify(addr);
        /*
        $.ajax({
        url: ko__pathToRoot + "/sitefinity/services/ideosity/b2b2cUserSecureService.svc/user/address/update/" + new Date().getTime(),
        type: "POST",
        timeout: 20000,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: jsonstring
        }).done(function (data) {
        if (data.cssClass == "ok") {
        window.location = window.location;
        } else {
        noty({ type: "error", text: data.message });
        }
        });
        */
        ajaxHelper.request({
            waitingText: 'Saving address...',
            id: 'noty-addr-save-4922',
            url: ko__pathToRoot + "/sitefinity/services/ideosity/b2b2cUserSecureService.svc/user/address/update/" + new Date().getTime(),
            type: "POST",
            data: jsonstring
        }).done(function (data) {
            if (data.cssClass == "ok") {
                window.location = window.location;
            } else {
                noty({ type: "error", text: data.message });
            }
        });
    },
    deleteMe: function () {
        if (this.Cards) {
            if (this.Cards().length > 0) {
                noty({ type: "warning", text: "Please remove all cards in the location before deleting." });
                return;
            }
        }
        $.ajax({
            url: ko__pathToRoot + "/sitefinity/services/ideosity/b2b2cUserSecureService.svc/user/address/remove/" + this.LocationId() + "/" + new Date().getTime(),
            type: "GET",
            timeout: 20000
        }).done(function (data) {
            if (data.cssClass == "ok") {
                window.location = window.location;
            } else {
                noty({ type: "error", text: data.message });
            }
        });
    },
    cleanCards: function () {
        var list = ko.utils.arrayFilter(this.Cards(), function (item) {
            return item.Id() != '-1';
        }, this);
        this.Cards(list);
    }
});

function koCard(card) {
    this.AccountNumber = ko.observable(card.AccountNumber || '');
    this.ExpirationDate = ko.observable(card.ExpirationDate || new Date());
    var dte = moment(card.ExpirationDate) || moment();
    this.ExpirationYear = ko.observable(dte.year());
    this.ExpirationMonth = ko.observable(dte.month());
    this.Id = ko.observable(card.Id || '-1');
    this.LocationId = ko.observable(card.LocationId || '-1');
    this.HolderName = ko.observable(card.HolderName || '');
    this.IssuerName = ko.observable(card.IssuerName || '');
    this.Number = ko.observable(card.Number || '');

    //computed
    this.Expires = ko.computed(function () {
        return moment(this.ExpirationDate()).format('ll');
    }, this);
    this.JsonExpiration = ko.computed(function () {
        return new Date(this.ExpirationYear(), this.ExpirationMonth(), 1).toMSJSON();
    }, this);
    this.IsSelectedForCheckout = ko.computed(function () {
        if (!vm.checkout()) return false;
        if (!vm.checkout().BillingCard()) return false;
        return vm.checkout().BillingCard().Id() == this.Id();
    }, this);
}

ko.utils.extend(koCard.prototype, {
    sendToServer: function () {
        var card = ko.toJS(this);
        card.ExpirationDate = this.JsonExpiration();
        var jsonstring = JSON.stringify(card);
        /*
        $.ajax({
        url: ko__pathToRoot + "/sitefinity/services/ideosity/b2b2cUserSecureService.svc/user/card/update/" + new Date().getTime(),
        type: "POST",
        timeout: 20000,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: jsonstring
        }).done(function (data) {
        if (data.cssClass == "ok") {
        window.location = window.location;
        } else {
        noty({ type: "error", text: data.message });
        }
        });
        */
        ajaxHelper.request({
            waitingText: 'Saving Card...',
            id: 'noty-saving-ccard',
            url: ko__pathToRoot + "/sitefinity/services/ideosity/b2b2cUserSecureService.svc/user/card/update/" + new Date().getTime(),
            type: "POST",
            data: jsonstring
        }).done(function (data) {
            if (data.cssClass == "ok") {
                window.location = window.location;
            } else {
                noty({ type: "error", text: data.message });
            }
        });
    },
    deleteMe: function () {
        $.ajax({
            url: ko__pathToRoot + "/sitefinity/services/ideosity/b2b2cUserSecureService.svc/user/card/remove/" + this.Id() + "/" + new Date().getTime(),
            type: "GET",
            timeout: 20000
        }).done(function (data) {
            if (data.cssClass == "ok") {
                window.location = window.location;
            } else {
                noty({ type: "error", text: data.message });
            }
        });
    }
});