var view = null;

function viewModel() {

    var t = this;

    t.all = ko.observableArray();

    t.newCartTemp = ko.observable(false);

    t.newSettingsTemp = ko.observable(false);

    t.ShowBody = ko.pureComputed(function () {
        return (!t.newCartTemp() && !t.newSettingsTemp()) ? true : false;
    })

    t.DataFromServer = ko.observableArray();

    t.showSearch = ko.observable(false);

    t.ModalBodyHeight = ko.observable(window.screen.availHeight - 120);

    t.data = ko.observableArray();

    t.Height = ko.observable(70);

    t.menuItems = ko.observableArray();

    t.elements = ko.observableArray();

    t.cartItems = ko.observableArray();

    t.cartItems.subscribe(function (val) {
        if (val.length == 0) {
            t.newCartTemp(false);
        }
    });

    t.ReadQrCode = function () {
        t.Next('dinner-table', 'code-reader');
        Open(function (response) {
            if (response) {
                t.QRCode(response);
                t.Next("code-reader", "code-reader-result");
                Close();
            }
        });
    };

    t.SelectedPriceAction = ko.observable("Tutar");

    t.CloseScanner = function () {
        t.Next('code-reader', 'dinner-table', t.ClearChildren("reader", 1), Close());
    }

    t.QRCode = ko.observable();

    t.IsSecureConnection = ko.observable(false);

    t.ClearChildren = function (element, startIndex) {
        var currentElem = document.getElementById(element);
        $.each(currentElem.children, function (index, value) {
            currentElem.children[0].remove();
        });
    }

    t.ReplayRead = function () {
        t.Next('code-reader-result', 'code-reader', undefined, Open(function (response) {
            if (response) {
                t.QRCode(response);
                Close();
            }
        }));
        //Open(function (response) {
        //    if (response) {
        //        t.QRCode(response);
        //        Close();
        //    }
        //});
    }

    t.Next = function (currentTemplateId, targetTemplateId, beforeCallback, afterCallback) {
        if (typeof (beforeCallback) == "function") {
            beforeCallback();
        }
        var curTemp = document.getElementById(currentTemplateId);
        var tarTemp = document.getElementById(targetTemplateId);
        if (curTemp && tarTemp) {
            curTemp.style.display = "none";
            tarTemp.style.display = "block";
            if (typeof (afterCallback) == "function") {
                afterCallback();
            }
        }
    }

    t.DinnerTableListEnabled = ko.observable(false);

    t.isMultiplePayment = ko.pureComputed(function () {
        if (t.PaymentType() && t.PaymentType() == "Multiple") {
            return true;
        }
        else {
            t.PaymentInputs([])
            return false;
        }
    });

    t.PaymentInputs = ko.observableArray();

    t.TotalPriceMultiplePayment = function () {
        var total = 0;
        for (var i = 0; i < t.PaymentInputs().length; i++) {
            total += t.PaymentInputs()[i].Price() > 0 ? parseFloat(t.PaymentInputs()[i].Price()) : 0;
        }
        return total.toFixed(2);
    };

    t.isEqual = ko.pureComputed(function () {
        return parseFloat(t.TotalPriceMultiplePayment()) === parseFloat(t.totalPriceFromServer());
    })

    t.PaymentInputsControl = function () {
        var currentPrice = parseFloat(t.TotalPriceMultiplePayment());
        var _remainingamount = t.RemainingAmount();
        var result = t.isEqual();
        if (result) {
            return true;
        }
        else if (currentPrice < parseFloat(t.totalPriceFromServer())) {
            t.PaymentInputs.push(new multiplePaymentModel(_remainingamount));
            return false;
        }

    };

    t.OrderCancellation = ko.observable(false);

    t.CancelBtnVisible = ko.pureComputed(function () {
        return t.selectedDataFromDbList && t.selectedDataFromDbList().length > 0 ? true : false;
    })

    t.RemoveFromPaymentInputs = function (index) {
        t.PaymentInputs.splice(index, 1);
        t.PaymentInputsControl();
    }

    t.TicketOptions = ko.observableArray([{ 'Name': 'Ticket', 'Id': '01' }, { 'Name': 'Multinet', 'Id': '02' }]);

    t.CCOptions = ko.observableArray([{ 'Name': 'Garanti', 'Id': '01' }, { 'Name': 'Yapı Kredi', 'Id': '02' }, { 'Name': 'FinansBank', 'Id': '03' }, { 'Name': 'Denizbank', 'Id': '04' }]);

    t.PaymentSubOption = ko.observable();

    t.PaymentSubOption.subscribe(function (val) {
        //if (val) {
        //    return t.PaymentInputs.push(1);
        //}
    })

    t.selectedDataFromDbList = ko.observableArray();

    t.selectedForRemove = function (index, data) {
        if (data) {
            if (!data.isSelected() && data.Quantity() !== -1) {
                t.selectedDataFromDbList.push(new settingsModel(data.ID(), data.Name(), data.Price(), 1, data.Quantity()));
                data.isSelected(!data.isSelected())
            }
            else if (data.isSelected()) {
                t.selectedDataFromDbList.remove(function (item) {
                    return item.ID() == data.ID();
                })
                data.isSelected(false)
            }
            else if (data.Quantity() !== -1) {
                data.isSelected(!data.isSelected())
            }
        }
    }

    t.TotalCountOfCartItems = ko.pureComputed(function () {
        var c = 0;
        t.cartItems().map(function (cart) {
            c += cart.Quantity()
        })
        return c;
    })

    t.ClearAll = function () {
        t.cartItems([]);
    }

    t.SelectedPaymetType = function (data) {
        t.PaymentType(data);
        t.PaymentInputs.push(new multiplePaymentModel());
    }

    t.Finish = function (data) {
        t.PaymentType(data && data.Id);
        t.ViewOrClose('close');
    }

    t.cartPopup = ko.observable(false);

    t.TotalPrice = ko.pureComputed(function () {
        var total = 0;
        $.each(view.cartItems(), function () {
            if (this.Extras && this.Extras().length > 0) {
                $.each(this.Extras(), function () {
                    if (this.Price && this.Price()) {
                        total += this.Price && this.Price();
                    }
                })
            }
            total += this.DisplayPrice() * 1
        })
        return total.toFixed(2);
    });

    t.TotalCountFromServer = ko.pureComputed(function () {
        var count = 0;
        t.viewListFromServer().map(function (item) {
            count += item.Quantity();
        })
        return count;
    });

    t.TotalCountCartItems = ko.pureComputed(function () {
        var count = 0;
        t.cartItems().map(function (item) {
            count += item.Quantity();
        })
        return count;
    });

    t.addToBasket = function (data, index, parentIndex) {
        if (t.cartItems && t.cartItems().length > 0) {

            var _self = this;

            this.result = ko.observable(-1);

            var _data = new cart(ko.toJS(data));

            var currrentItem = t.cartItems().filter(function (i, idx) { return i.ID() == _data.ID() && i.ExtrasKey() == _data.ExtrasKey(); });

            if (currrentItem.length == 0) {
                t.cartItems.push(_data);
                t.ClearAfterAdd(data, index, parentIndex);
                return true;
            }
            else {
                currrentItem = currrentItem[0];

                currrentItem.Quantity(currrentItem.Quantity() + 1);
                t.ClearAfterAdd(data, index, parentIndex);
                return true;

            }

        }
        else {

            t.cartItems.push(new cart(ko.toJS(data)));
            t.ClearAfterAdd(data, index, parentIndex);
            return true;
        }
    }

    t.AddToBasketAfterClose = function (data) {
        var result = t.addToBasket(data);
        if (result) {
            t.Next("product-detail", "container");
        }
    }

    t.Queue = ko.observableArray([]);

    t.DeskNo = ko.observable().extend({ required: { message: "Masa seçiniz!" } });

    t.DeskNoForCart = ko.observable().extend({ required: { message: "Masa seçiniz!" } });

    t.PaymentTypes = ko.observableArray();

    t.GetPaymentTypes = ko.computed(function () {
        var CC = [];
        var Tickets = []
        var C = [];
        var pt = app.LocalStorage.Read("PaymentTypes");
        if (pt !== "null") {
            return t.PaymentTypes(JSON.parse(pt));
        }
        return PostQuery("GET", "/Home/GetPaymentTypes", null, function (response) {

            response.paymentTypes.map(function (item) {
                if (item.Type === "Kredi Karti") {
                    CC.push(item);
                }
                else if (item.Type === "Ticket") {
                    Tickets.push(item);
                } else {
                    C.push(item);
                }
            })
            var types = [{ "Name": "Kredi Kartı", "Id": "KK", "Options": CC }, { "Name": "Ticket", "Id": "Ticket", "Options": Tickets }, { "Name": "Nakit", "Id": "Nakit", "Options": C }];
            app.LocalStorage.Write("PaymentTypes", types);
            return t.PaymentTypes(types);
        })
    })



    //[{ "Name": "Nakit", "Id": "Nakit" }, { "Name": "Kredi Kartı", "Id": "KK" }, { "Name": "Ticket", "Id": "Ticket" }];

    t.PaymentType = ko.observable();

    t.validationForCart = ko.validation.group([t.DeskNoForCart]);

    t.validationForClose = ko.validation.group([t.DeskNo]);

    t.lastItemOfCartItems = ko.pureComputed(function () {
        return t.cartItems && t.cartItems().length > 0 ? t.cartItems().reverse()[0].Name() : ''
    })

    t.viewMessage = ko.observable();

    t.PostToSafeData = {};

    t.OrderComplate = function (data, event) {

        if (t.validationForCart().length > 0) {
            t.validationForCart.showAllMessages();
            app.box.msg.text("Lütfen masa seçiniz!.")
            return
        } else {
            var model = {
                Products: ko.toJS(t.cartItems()),
                TotalPrice: t.TotalPrice(),
                DeskNo: t.DeskNoForCart()
            };
            t.AddOrder(model, function (response) {
                if (response.Error) {
                    if (response.Error == "NetWork Error") {

                        t.Queue.push(JSON.parse(response.Data)[0]);
                        app.LocalStorage.Write("Queue", t.Queue());
                        t.Next("dinner-table", "container");
                        t.cartItems([]);
                        t.DeskNoForCart(undefined);

                    } else {
                        app.box.msg.text(response.Error);
                    }
                } else {
                    t.cartItems([]);
                    t.DeskNoForCart(undefined);
                    t.validationForCart.showAllMessages(false);
                    t.viewListFromServer([]);
                    t.DeskNo(undefined);
                    t.Next("dinner-table", "binding");
                }
            })
        }
    }

    t.AddOrder = function (data, callback) {
        var model = {
            User: t.loginInfo().UserName,
            DepartmentNo: t.loginInfo().DepartNo,
            UserId: t.loginInfo().ID,
            DeskNo: data && data.DeskNo,
            Products: data && data.Products,
            TotalPrice: data && data.TotalPrice
        }
        PostQuery("POST", "/Home/AddOrder", { data: JSON.stringify([model]) }, callback || function (res) {
            console.log(res);
        });
    }

    t.AddOrderWithQrCode = function () {
        var model = {
            QRCode: t.QRCode(),
            User: t.loginInfo().UserName,
            DepartmentNo: t.loginInfo().DepartNo,
            UserId: t.loginInfo().ID,
            Products: ko.toJS(t.cartItems()),
        }
        PostQuery("POST", "/Home/AddOrderWithQrCode", { data: JSON.stringify(model) }, function (res) {
            if (res.Error) {
                app.box.msg.text(response.Error);
            } else {
                t.cartItems([]);
                t.QRCode(undefined);
                //qr-code-result
                t.Next("code-reader-result", "container");
                //t.Next("code-scanner-template", "container");
                Close();
            }
        })
    }

    t.PushQueue = function () {
        var data = app.LocalStorage.Read("Queue");
        PostQuery("POST", "/Home/AddOrder", { data }, function (res) {
            if (res.Error) {
            }
            else {
                t.Queue([]);
                app.LocalStorage.Remove("Queue");
            }
        });
    }

    t.BodyHeight = ko.pureComputed(function () {
        return (window.screen.height - 50) + "px";
    })

    t.ScrollDown = function () {
        var modal = $('.modal-body');
        modal.scrollTop(modal.height())
    }

    t.CartTitleText = ko.pureComputed(function () {
        if (t.TotalCountCartItems() > 0 && t.TotalPrice && t.TotalPrice()) {
            return t.TotalCountCartItems() + ' Adet ' + t.TotalPrice() + 'TL';
        } else {
            return "";
        }
    })

    t.Desks = ko.observableArray();

    t.Islogin = ko.computed(function () {
        var cookie = app.Cookie.Read("AU");
        if (cookie) {
            return true;
        }
        else {
            return false;
        }
    });

    t.Islogin.subscribe(function (newValue) {
        if (newValue) {
            //t.Icoroll();
            setCssUroll();
        }
        else {
            return
        }
    })

    t.user = ko.observable();

    t.loginInfo = ko.observable();

    t.getDesks = function (res) {
        if (app.LocalStorage.Read("Desk") !== "null") {
            t.Desks(JSON.parse(app.LocalStorage.Read("Desk")));
        } else {
            return PostQuery("GET", "/Home/DeskList", { departmentId: view.user().DepartNo() || t.loginInfo().DepartNo }, function (res) {
                t.Desks(res.desks);
                app.LocalStorage.Write("Desk", ko.toJS(view.Desks()));
            })
        }
    };

    t.DeskNo.subscribe(function (val) {
        t.ViewOrClose("view");
    })

    t.isModal = ko.pureComputed(function () {
        return t.cartItems && t.cartItems().length > 0 ? true : false;
    })

    t.deskErrorMessage = ko.observable();


    t.viewListFromServer = ko.observableArray();

    t.PriceActionValue = ko.observable(0);

    t.totalPriceFromServer = ko.pureComputed(function () {
        var price = 0;
        t.viewListFromServer().map(function (item) {
            price += item.Quantity() * parseFloat(item.Price());
        })
        if (t.PriceActionValue() != "") {
            switch (t.SelectedPriceAction()) {
                case "Yuzde":
                    var discount = parseFloat(t.PriceActionValue()) > 0 ? parseFloat(t.PriceActionValue()) / 100 * price : 0;
                    return discount > price ? price.toFixed(2) : (parseFloat(price) - parseFloat(discount)).toFixed(2);
                    break;
                case "Tutar":
                    return parseFloat(t.PriceActionValue()) > price ? price.toFixed(2) : (parseFloat(price) - parseFloat(t.PriceActionValue())).toFixed(2)
                    break;
                default:
                    return price.toFixed(2)
            }
        }
        else {
            return price.toFixed(2);
        }
    })

    t.RemainingAmount = ko.pureComputed(function () {
        var result = parseFloat(t.totalPriceFromServer()) - parseFloat(t.TotalPriceMultiplePayment());
        return result.toFixed(2);
    })

    t.subSelectOptions = ko.observableArray();

    t.selectionChangedType = function (value) {
        if (value && value.Price() === undefined) {
            value.Price(parseFloat(t.RemainingAmount()))
        }
        if (value && value.Type() == "KK") {
            value.SubTypes(t.PaymentTypes().filter(function (f) { return f.Id == value.Type(); }));
        }
        else if (value && value.Type() == "Ticket") {
            value.SubTypes(t.PaymentTypes().filter(function (f) { return f.Id == value.Type(); }));
        }
        else {
            value.SubType("Nakit");
            value.SubTypes([]);
            return
        }
    }

    t.DeletedList = ko.observableArray();

    t.ViewOrClose = function (param) {
        if (t.validationForClose().length > 0) {
            t.validationForClose.showAllMessages();
            return
        } else {
            if (param) {
                var params = {};
                params.IsViewOrClose = param;
                params.DepartmentId = t.user().DepartNo() || t.loginInfo().DepartNo;
                params.DeskNo = t.DeskNo();
                params.PaymentInfo = [];
                if (t.PaymentType() == "Multiple") {
                    params.PaymentInfo = ko.toJS(t.PaymentInputs());
                }
                else {
                    params.PaymentInfo = [{
                        "Price": parseFloat(t.totalPriceFromServer()), "Type": t.PaymentType(), "SubType": t.PaymentType()
                    }]
                }
                PostQuery("POST", "/Home/ViewOrClose", { "data": JSON.stringify(params) }, function (res) {
                    if (res.view) {
                        if (res.view.length == 0) {
                            t.viewListFromServer([]);
                            t.viewMessage(t.DeskNo() + " numaralı masanın açık hesabı bulunmamaktadır");
                            app.box.msg.text(t.DeskNo() + " numaralı masanın açık hesabı bulunmamaktadır");

                            // t.DeskNo(undefined);
                            t.validationForClose.showAllMessages(false)
                        } else {
                            res.view.map(function (item) {
                                item.isSelected = false;
                            })
                            t.viewListFromServer(ko.mapping.fromJS(res.view)());
                            t.viewMessage(undefined);
                            t.Next("dinner-table-2", "settings-new-template");
                            //t.newSettingsTemp(true);
                        }
                    }
                    else if (res.Message) {
                        t.DeskNo(undefined);
                        t.validationForClose.showAllMessages(false);
                        app.box.msg.text(res.Message);
                        t.newSettingsTemp(false);
                        t.viewListFromServer([]);
                        t.PaymentType(undefined);
                        t.Next("settings-new-template", "container");
                    }
                    else if (res.Error) {
                        app.box.msg.text(res.Error);
                    }
                });
            }
        }
    }

    t.afterSave = function () {
        if (t.validationForClose().length > 0) {
            t.validationForClose.showAllMessages();
            return
        } else {
            var model = {
                Products: ko.toJS(t.selectedDataFromDbList()),
                DeskNo: t.DeskNo()
            }
            t.AddOrder(model, function (response) {
                if (response.Error) {
                    debugger;
                    if (response.Error == "NetWork Error") {
                        t.Queue.push(JSON.parse(response.Data));
                    } else {
                        app.box.msg.text(response.Error);
                    }
                } else {
                    app.box.msg.text("Değişiklikler başarı ile gerçekleşti.");
                    t.selectedDataFromDbList([]);
                    t.ViewOrClose("view");
                    t.OrderCancellation(false);
                    t.validationForClose.showAllMessages(false);
                }
            })
        }
    }

    t.isShowViewOrClose = ko.observable(false);

    t.isShowViewOrClose.subscribe(function (val) {
        if (val) {
            t.viewMessage(undefined);
        }
    })

    t.ClearAndCloseForSettings = function () {
        t.viewListFromServer().map(function (m) { return m.isSelected(false) });
        t.selectedDataFromDbList([]);
    }

    t.LoginControl = function (data) {
        if (app.Cookie.Read("AU") !== "") {
            return t.loginInfo(data || JSON.parse(app.Cookie.Read("AU")));
        }
        else {
            return t.loginInfo(data || undefined);
        }
    }

    t.initUserModel = ko.computed(function () {
        if (!t.loginInfo()) {
            t.user(new userModel());
        } else {
            return;
        }
    })

    t.SignOut = function () {
        if (t.loginInfo()) {
            app.Cookie.Remove("AU")
            location.reload();
            return true;
        } else {
            return;
        }
    }

    t.Query = ko.observable();

    t.sortedCartItems = ko.pureComputed(function () {
        return t.cartItems() && t.cartItems().length > 0 ? t.cartItems().sort() : [];
    })

    t.onEnter = function (d, e) {
        if (e.keyCode === 13) {
            t.search();
        }
        return true;
    };

    t.searchList = ko.observableArray();

    t.searchView = ko.observable(false);

    t.visibleAll = function () {
        t.Query(undefined);
        t.searchView(false);
        t.searchList([]);
    }

    t.search = function () {
        if (t.Query()) {
            var q = t.Query().toLowerCase();
            var Data = [];
            var List = [];
            var Name = [];
            for (var i = 0; i < t.data().length; i++) {
                for (var j = 0; j < t.data()[i].Products().length; j++) {
                    if (t.data()[i].Products()[j].Name().toLowerCase().indexOf(q) >= 0)
                        List.push(t.data()[i].Products()[j]);
                }
            }
            if (List.length > 0) {
                var message = "Arama sonu";
                Name.push(List.length == 1 ? message + "cu" : message + "çları");
                Data.push({ Name: Name, Products: List });
            }
            if (Data.length > 0) {

                t.searchList(Data);
                t.searchView(true);
                // t.showSearch(!t.showSearch())
                // t.Query(undefined);
            }
        }
        else {
            return;
        }
    };

    t.SearchingList = ko.pureComputed({
        read: function () {
            if (t.Query()) {
                if (t.Query().length >= 2) {
                    var q = t.Query().toLowerCase();
                    var data = ko.observableArray();
                    var filteredData = ko.observableArray([]);
                    t.data().filter(function (f) {
                        return f.Products().filter(function (ff) {
                            if (ff.Name().toLowerCase().indexOf(q) >= 0) {
                                filteredData.push(ff);
                            }
                        })
                    });
                    if (filteredData().length > 0) {
                        var message = "Arama sonu";
                        t.searchView(true);
                        data([{ Name: filteredData().length == 0 ? message + "cu" : message + "cları" }, { Products: filteredData }]);
                        return data();
                    }

                } else {
                    t.searchView(false);
                    return [];
                }

            } else {
                t.searchView(false);

                return [];
            }
        },
        write: function (data) {
            return data;
        }
    });

    t.hideSearchList = function () {
        if (t.searchView()) {
            t.searchView(false);
        }
    }

    t.Direction = ko.observable(true);

    t.isCollapse = ko.observable(true);

    t.ProductDetails = ko.observable();

    t.showDetailDialog = ko.observable(false);

    t.showDetail = function (data) {
        t.ProductDetails(data);
        var _d = data.Details;
        t.ProductDetail(new EditViewModel(data.ID(), data.Name(), _d.ImgPath(), [], _d.Heat(), _d.Interval(), _d.CookingTime(), _d.Description(), _d.Calori()))
        t.Next("container","product-detail");
    }

    t.ProductDetail = ko.observable();

    t.EditDetail = function (data) {
        var _d = data.Details;
        t.ProductDetail(new EditViewModel(data.ID(),data.Name(), _d.ImgPath(), [], _d.Heat(), _d.Interval(), _d.CookingTime(),_d.Description(),_d.Calori()))
        t.Next("container", "product-edit");
        t.ProductDetails(data);
    }

    t.AddDetail = function () {
        alert();
    }

    t.GetFileInput = function (event) {
        var formData = GetFormData(event);
        if (formData) {
            fileUpload('/home/UploadImage', formData, function (res) {
                var data = JSON.parse(res)
                if (data.files.length > 0) {
                    for (var i = 0; i < data.files.length; i++) {
                        t.ProductDetail().File(data.files[i].Path);
                    }
                   
                }
            })
        }
    }

    t.backToindex = function () {
        t.Next("product-detail", "container");
        t.ProductDetail(undefined);
    }

    t.showCartView = ko.observable(false);

    t.showCart = ko.observable(false);

    t.openModal = function () { return t.cartItems().length > 0 ? ((t.Direction() == true ? t.Direction(false) : t.Direction(false)) && t.showCart(!t.showCart())) : false }

    t.openCart = function () {
        return t.cartItems().length > 0 ? ((t.Direction() == true ? t.Direction(false) : t.Direction(false)) && t.newCartTemp(!t.newCartTemp())) : false
    }

    t.refreshCache = function () {
        app.LocalStorage.Remove("alldata");
        app.LocalStorage.Remove("paymenttypes");
        app.LocalStorage.Remove("desk");
        location.reload();
    }
    
    t.Run = function () {
        if (app.LocalStorage.Read("AllData") != "null") {
            t.DataFromServer(ko.mapping.fromJS(JSON.parse(app.LocalStorage.Read("AllData")))());
        }
        else {
            t.load = ko.computed(function () {
                return PostQuery("GET", "/Home/GetAll", {}, function (res) {
                    t.DataFromServer(ko.mapping.fromJS(res.p)());
                })
            });
            app.LocalStorage.Write("AllData", t.DataFromServer());

        }
        t.data(t.DataFromServer());
        t.getDesks();
        var index = 0;
        t.data(ko.mapping.fromJS(t.DataFromServer())());
        t.data().map(function (item) {
            item.class = ko.observable();
            item.href = ko.observable(item.Name());
            item.content = ko.observable(item.Name());
            item.Products().map(function (subItem) {
                subItem.Query = ko.observable();
                subItem.Collapse = ko.observable(false);
                subItem.Quantity = ko.observable(1);
                var s = subItem;

                if (subItem.Extras && subItem.Extras()) {
                    subItem.Extras().map(function (Ex,idx) {
                        Ex.ExtraCount = ko.observable(0);
                        if (Ex.Price && Ex.Price()) {
                            s.DisplayPrice += Ex.ExtraCount() * Ex.Price();
                        }
                        Ex.isOk = ko.observable();
                        Ex.AfterAdd = ko.observable(false);
                        Ex.ID = ko.observable(idx + 1);
                    })
                }
                else {

                }
                subItem.DisplayPrice = ko.pureComputed(function () {

                    return (subItem.Quantity() * parseFloat(subItem.Price()));

                })

            })

            index += 1;

            t.menuItems.push({ "bgColor": item.titlebgcolor && item.titlebgcolor() || "#111111", "class": item.class && item.class(), "target": "#menu" + index, "displayName": item.content() });
        })
        if (app.LocalStorage.Read("Queue") !=="null") {
            debugger;
            t.Queue(JSON.parse(app.LocalStorage.Read("Queue")));
        }
    }

    t.latestTopping = ko.computed({
        read: function () {
            return t.cartItems().length > 0 ? t.TotalCountOfCartItems() : ""
        },
        write: function (value) {
            t.cartItems.push(value);
        },
        owner: this
    });

    t.AfterAdd = function (data) {
        if (data && data.Query()) {
            t.AddExtra(data);
        }
    }

    t.enterKey = function (data) {
        if (data && data.Query()) {
            data.Extras.push(new extraProductModel(0, data.Query(), true, undefined));
            data.AfterAdd(false);
            data.Query(undefined);
        }
    }

    t.CurrentExtra = ko.observableArray([]);

    t.AddExtra = function (data) {
        if (data && data.Query()) {
            var ID = data.Extras().length;
            var model = { AfterAdd: ko.observable(true), Name: ko.observable(data.Query()), Price: ko.observable(0), IsOk: ko.observable(), ExtraCount: ko.observable(1), isOk: ko.observable(true), ID: ko.observable(ID + 1)};
            data.Extras.push(model);
            data.Query(undefined);
        }
    }

    t.ClearAfterAdd = function (data, index, parentIndex) {
        if (data && data.Extras().length > 0) {
            var before = data.Extras().filter(function (ex) { return !ex.AfterAdd() });
            var after = data.Extras().filter(function (ex) { return ex.AfterAdd() });
            t.data()[parentIndex].Products()[index].Extras([]);
            t.data()[parentIndex].Products()[index].Extras(before == 0 ? [] : before);
            if (t.SearchingList().length > 0) {
                t.SearchingList()[parentIndex].Products()[index].Extras([]);
                t.SearchingList()[parentIndex].Products()[index].Extras(before == 0 ? [] : before);
            }
            
        }

    }
}


function detailModel(image, ingredients) {
    var t = this;

    t.ingredients = ko.observable(ingredients);
    t.images = ko.observable(image);
}


function settingsModel(_ID, _Name, _Price,_Quantity,_LastValue,) {
    var t = this;

    t.ID = ko.observable(_ID);

    t.Name = ko.observable(_Name);

    t.Price = ko.observable(_Price);

    t.Quantity = ko.observable(_Quantity);

    t.Extras = ko.observableArray();

    t.DisplayPrice = ko.pureComputed(function () {
        var price = + (t.Price() * t.Quantity());
        return price;
    })

    t.LastValue = ko.observable(-_LastValue);
}

function cart(data) {

    var t = this;

    t.ID = ko.observable(data && data.ID);

    t.Name = ko.observable(data && data.Name);

    t.Price = ko.observable(data && data.Price);

    t.Quantity = ko.observable(data && data.Quantity);

    t.Extras = ko.observableArray();

    t.ExtrasKey = ko.pureComputed(function () {
        return JSON.stringify(ko.toJS(t.Extras));
    });

    t.isOk = ko.observable();

    t.DisplayPrice = ko.pureComputed(function () {
        var price = + (t.Price() * t.Quantity());
        return price;
    })
    if (data.Extras && data.Extras.length > 0) {
        for (var i = 0; i < data.Extras.length; i++) {
            if (data.Extras[i].ExtraCount == 1 || data.Extras[i].ExtraCount == -1) {
                var calcPrice = (parseFloat(data.Extras[i].Price) * parseFloat(data.Extras[i].ExtraCount));
                t.Extras().push(new extraProductModel(calcPrice, data.Extras[i].Name, data.Extras[i].isOk, data.Extras[i].ID));
            }

        }
    }

    t.AfterAdd = ko.observable(false);

    t.Query = ko.observable();
}

function extraProductModel(price, name, isOk, ID) {
    var t = this;
    t.ID = ko.observable(ID);
    t.Price = ko.observable(price);
    t.Name = ko.observable(name);
    t.isOk = ko.observable(isOk);
}

function userModel() {

    var t = this;
    var userInfo = null;
    if (app.Cookie.Read("BL") === "") {
        userInfo = undefined;
    } else {
        userInfo = JSON.parse(app.Cookie.Read("BL"));
    }
    t.ID = ko.observable();

    t.UserName = ko.observable(userInfo && userInfo.UserName);

    t.Password = ko.observable(userInfo && userInfo.Password).extend({ required: {message:"Boş geçilemez!"}, maxLength: { params: 20, message: "En fazla 20 karekter girebilirsiniz!" } });

    t.RememberMe = ko.observable(true);

    t.DepartNo = ko.observable(userInfo && userInfo.DepartNo).extend({ required: {message: "Boş geçilemez!" }, maxLength: { params: 20, message: "En fazla 20 karekter girebilirsiniz!" } });

    t.errors = ko.validation.group(t, { deep: true });

    t.NotFound = ko.observable(false);

    t.ErrorMessage = ko.observable();

    t.RoleId = ko.observable(userInfo && userInfo.RoleId);

    t.Roles = ko.observableArray(userInfo && ko.mapping.fromJS(userInfo.Roles)() || [] );

    t.Login = function () {
        if (t.errors().length > 0) {
            t.errors.showAllMessages();
        } else {
            PostQuery("POST", "/Home/Login", { departmanCode: t.DepartNo(), password: t.Password() }, function (response) {
                if (response.Error) {
                    t.NotFound(true);
                    t.ErrorMessage(response.Error);
                } else if(response.user) {
                    
                    t.ID(response.user.ID);
                    t.UserName(response.user.UserName);
                    t.RoleId(response.user.RoleId);
                    if (response.roles.length > 0) {
                        t.Roles(response.roles);
                    }
                    view.LoginControl(ko.toJS(t));
                    app.Cookie.Write("AU", JSON.stringify(ko.toJS(t)), 1);
                    app.Cookie.Write("BL", JSON.stringify(ko.toJS(t)), t.RememberMe() == true ? 30 : 1);
                    //view.Run();
                    location.reload();
                }
            })
           
        }
    }

   // t.IsUpdate = ko.pureComputed(function () {
        //return view.user().Roles()[1].UseRole() || view.user().Roles()[3].UseRole();
   // })
}

ko.bindingHandlers.modal = {
    init: function (element, optionsAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var $element = $(element);

        if ($element.attr("tabindex") === undefined) {
            $element.attr("tabindex", -1);
        }

        $element.modal(ko.toJS(optionsAccessor()));

        $element.on("hidden.bs.modal", function () {
            var options = ko.utils.unwrapObservable(optionsAccessor());
            return false;
        });

        $(document).on("keyup", function (e) {
            return false;
            if (e.which === 27) {
                $element.modal("hide");
            }
        });

        // hide elements inside modal unless we are showing it
        var _showAccessor = showAccessor.bind(optionsAccessor, optionsAccessor);
        ko.bindingHandlers["if"].init(element, _showAccessor, allBindingsAccessor, viewModel, bindingContext);
    },
    update: function (element, optionsAccessor) {
        var _showAccessor = showAccessor.bind(optionsAccessor, optionsAccessor);

        $(element).modal(_showAccessor() ? "show" : "hide");
    }
};

function showAccessor(accessor) {
    var options = ko.utils.unwrapObservable(accessor());
    return ko.utils.unwrapObservable(options.show);
}

function PostQuery(Method, Url, Json, SuccessCallback ) {
   return $.ajax({
            type: Method || 'GET',
            url: Url,
            data: Json || {},
            dataType: "json",
            success: SuccessCallback,
            async: false,
            error: function (xhr, status, errorThrown) {
                alert(xhr.responseText);
            }
        });
}

ko.bindingHandlers.enterkey = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var allBindings = allBindingsAccessor();

        $(element).on('keypress', 'input, textarea, select', function (e) {
            var keyCode = e.which || e.keyCode;
            if (keyCode !== 13) {
                return true;
            }

            var target = e.target;
            target.blur();

            allBindings.enterkey.call(viewModel, viewModel, target, element);

            return false;
        });
    }
}

var app = {
    Cookie: {
        Read: function (c_name) {
            if (document.cookie.length > 0) {
                c_start = document.cookie.indexOf(c_name + "=");
                if (c_start != -1) {
                    c_start = c_start + c_name.length + 1;
                    c_end = document.cookie.indexOf(";", c_start);
                    if (c_end == -1) {
                        c_end = document.cookie.length;
                    }
                    return unescape(document.cookie.substring(c_start, c_end));
                }
            }
            return "";
        },
        Write: function (name, value, days) {
            var expires;
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            else {
                expires = "";
            }
            document.cookie = name + "=" + value + expires + ";path=/";
        },
        Remove: function (name) {
            this.Write(name, "", "1950-01-01");
        },
    },
    LocalStorage: {
        Read: function (name) {
            var lname = name.toLowerCase();
            return typeof (window.localStorage.getItem(lname)) == "string" ? window.localStorage.getItem(lname) : JSON.stringify(window.localStorage.getItem(lname));
        },
        Write: function (name, data) {
            return window.localStorage.setItem(name.toLowerCase(), JSON.stringify(ko.toJS(data)));
        },
        Remove: function (name) {
            return window.localStorage.removeItem(name.toLowerCase());
        }
    },
    box : {
        msg: {
            text: ko.observable(),
            show : ko.pureComputed({
                read: function () {
                    return app.box.msg.text() == undefined ? false : true;
                },
                write: function (value) {
                    return app.box.msg.text(undefined)
                }
            })
        },
        confirm: {
            message: ko.observable(),
            callback: confirm || function () {
                console.log("asdas");
            }
        }
    }
};

ko.bindingHandlers.fadeSwitcher = {
    init: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        element.setAttribute('previousValue', value);
        ko.bindingHandlers.text.update(element, ko.observable(value));
    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var previousValue = element.getAttribute('previousValue');
        if (value !== previousValue) {
            $(element).fadeOut('fast', function () {
                ko.bindingHandlers.text.update(element, ko.observable(value));
                $(element).fadeIn();
            });
            element.setAttribute('previousValue', value);
        }
    }
};

function multiplePaymentModel(_type, _price) {
    
    var t = this;

    t.Type = ko.observable();

    t.Price = ko.observable(_price);

    t.Price.subscribe(function (val) {
        var _val = (typeof (val) == "number" ? val.toString() : val);
        if (_val.indexOf(",") !== -1) {
            t.Price(parseFloat(val.replace(/,/g, '.')));
        }
    })

    t.SubType = ko.observable(_type);

    t.SubTypes = ko.observableArray();
}

ko.bindingHandlers.returnAction = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var value = ko.utils.unwrapObservable(valueAccessor());

        $(element).keydown(function (e) {
            if (e.which === 13) {
                value(viewModel);
            }
        });
    }
};

ko.bindingHandlers.doubleClick = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var handler = valueAccessor(),
            delay = 200,
            clickTimeout = false;

        $(element).click(function () {
            if (clickTimeout !== false) {
                handler.call(viewModel);
                clickTimeout = false;
            } else {
                clickTimeout = setTimeout(function () {
                    clickTimeout = false;
                }, delay);
            }
        });
    }
};


function customerModel(_Code, _RoomNo,_FirstName,_LastName) {
    var t = this;

    t.Code = ko.observable(_Code);

    t.RoomNo = ko.observable(_RoomNo);

    t.FirstName = ko.observable(_FirstName);

    t.LastName = ko.observable(_LastName);

}

ko.bindingHandlers.placeholder = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var underlyingObservable = valueAccessor();
        ko.applyBindingsToNode(element, { attr: { placeholder: underlyingObservable } });
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        debugger
        var underlyingObservable = valueAccessor();
        ko.applyBindingsToNode(element, { attr: { placeholder: underlyingObservable } });
    }
};


function GetFormData(e) {
    var control = false;
    for (var i = 0; i < e.files.length; i++) {
        control = checkFile(e.files[i].name)
    }
    if (!control) {
        return false
    }
    for (var i = 0; i < e.files.length; i++) {
        control = fileSizeControl(e.files[i])
    }
    if (!control) {
        return false
    }
    var files = e.files;
    var imageType = /image.*/;

    var form_data = new FormData();
    for (var i = 0; i < files.length; i++) {
        if (!files[i].type.match(imageType)) return;
        form_data.append('file' + i, files[i]);
    }
    return form_data;
};

function fileSizeControl(file) {
    var kb = file.size / 1024
    var mb = parseFloat(kb / 1024).toFixed(2);
    if (mb < 2) {
        return true
    } else {

        msgBox("Lütfen 2 mb dan daha düşük boyutlu resim yükleyiniz.")
        return false;
    }
}

function checkFile(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
        case 'jpg':
        case 'jpeg':
        case 'gif':
        case 'bmp':
        case 'png':
        case 'bmp':
        case 'tif':
            //etc
            return true;
    }  
    return false;
}

function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function fileUpload(url, formData, successCallback) {
    $.ajax({
        url: url,
        cache: false,
        contentType: false,
        processData: false,
        data: formData,
        type: 'POST',
        success: successCallback,
        error: function (error) {
            console.log(error);
        }
    });
}

function EditViewModel(_Id,_Name, _File, _Files, _Heat, _Interval, _CookingTime, _Description, _Calori) {

    var t = this;

    t.Id = ko.observable(_Id);

    t.Name = ko.observable(_Name);

    t.File = ko.observable(_File);/*.extend({ required: { message : "Bu alan zorunludur!" }});*/

   // t.Files = ko.observableArray(_Files || []);

    t.Heat = ko.observable(_Heat);

    t.Interval = ko.observable(_Interval);

    t.CookingTime = ko.observable(_CookingTime);

    t.Description = ko.observable(_Description).extend({ required: { message: "Bu alan zorunludur!" } });;

    t.Calori = ko.observable(_Calori);

    t.errors = ko.validation.group(t, { deep: true });

    t.SaveChanges = function () {
        if (t.errors().length > 0) {
            t.errors.showAllMessages();
        } else {
            var data =JSON.stringify(ko.mapping.toJS(view.ProductDetail()));
            PostQuery("Post", "/Home/AddDetail", { "data" : data }, function (res) {
                if (res.Error) {

                } else {
                    if (view.ProductDetails().Details) {
                        view.ProductDetails().Details.Calori(t.Calori());
                        view.ProductDetails().Details.CookingTime(t.CookingTime());
                        view.ProductDetails().Details.Description(t.Description());
                        view.ProductDetails().Details.Interval(t.Interval());
                        view.ProductDetails().Details.Heat(t.Heat());
                        view.ProductDetails().Details.ImgPath(t.File());
                        app.LocalStorage.Remove("Alldata")
                        app.LocalStorage.Write("AllData", view.data());
                    }
                    view.Next("product-edit", "container", undefined, function () { return view.ProductDetail(undefined); });
                }
            })
        }
    }
}

ko.bindingHandlers.returnAction = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var value = ko.utils.unwrapObservable(valueAccessor());

        $(element).keydown(function (e) {
            if (e.which === 13) {
                value(viewModel);
            }
        });
    }
};