window.OBooks = window.OBooks || {};
(function(_OBooks, $, ko){

	var locale = _OBooks.localE || window.navigator.language || window.navigator.userLanguage || "en-IN";

	var formatNumber = function(num, prefix){
		return isNaN(num-0) ? "" : (prefix + (num-0).toLocaleString(locale));
		// return (num-0).toLocaleString(locale, {minimumFractionDigits: 2});
		// .replace(/[\d.]/ig, "").trim()
	};

	ko.bindingHandlers.currency = {
		update: function (element, params) {
			params = ko.utils.unwrapObservable(params)();

			var val = ko.utils.unwrapObservable(params.val);
			return ko.bindingHandlers.html.update(element, function() {
				return val ? formatNumber(val, params.cur ? "&#8377; " : "") : "-";
			});
		}
	};
	ko.virtualElements.allowedBindings.currency = true;

	var lOrderdata = {};
	try {
		if (localStorage.getItem("orderdata")) {
			lOrderdata = JSON.parse(localStorage.getItem("orderdata"));
		} else {
			lOrderdata = {};
		}
	} catch(ex) {
		lOrderdata = {};
	}

	if (!lOrderdata.items) {
		lOrderdata.items = {};
	}

	var orderModel = {};
/*
	var mMediaListener = function(mMedia){
		if (mMedia.matches) {
			orderModel.colspan4(1);
			orderModel.colspan5(2);
		} else {
			orderModel.colspan4(4);
			orderModel.colspan5(5);
		}
	};
*/
	var initKo = function(data){
		data = data || {};

		data.categories.forEach(function(cat){
			cat.isVisible = ko.observable(true);

			cat.items.forEach(function(item){
				item.rate = ((item.rate-0) || (item.saleRate-0))-0 || "-";
				item.showDiscRate = (item.orgRate != item.rate);
				item.qty = ko.observable(lOrderdata.items[item.itemId] || item.qty || "");
				item.addQty = function(){
					item.qty((item.qty()-0 || 0) + 1);
				};
				item.lessQty = function(){
					let qty = (item.qty() || 0) - 1;
					if (qty <= 0) {
						qty = "";
					}
					item.qty(qty);
				};
				item.itemTotal = ko.computed(function(){
					return ((item.qty()-0) * (item.rate-0)) || "";
				});
				if (!item.filePath) {
					item.filePath = "assets/img/item.png";
				}
			});
		});

		orderModel.categories = data.categories;
		orderModel.totalAmount = ko.observable();
		orderModel.fTotalAmount = ko.observable();
		orderModel.totProd = ko.observable();
		orderModel.totQty = ko.observable();
		orderModel.colspan4 = ko.observable(4);
		orderModel.colspan5 = ko.observable(5);

		orderModel.address = {
			name: ko.observable(data.address.name),
			address1: ko.observable(data.address.address1),
			address2: ko.observable(data.address.address2),
			city: ko.observable(data.address.city),
			stateCode: ko.observable(data.address.stateCode),
			stateName: ko.observable(data.address.stateName),
			stateId: ko.observable(data.address.stateId),
			zip: ko.observable(data.address.zip),
			country: ko.observable(data.address.country),
			countryCode: ko.observable(data.address.countryCode),
			phone: ko.observable(data.address.phone),
			email: ko.observable(data.address.email),
			gstin: ko.observable(data.address.gstin),
			captcha: ko.observable(""),
		};

		orderModel.setState = function(model, elem){
			if (elem.target && elem.target.selectedOptions && elem.target.selectedOptions[0])
			{
				var opt = elem.target.selectedOptions[0];
				model.stateCode(opt.getAttribute("code"));
			}
		};

		var orderdata = {items:{},address: {}};
		orderModel._compute = ko.computed(function(){
			let tot = 0, totQty = 0, totProd = 0;
			orderModel.categories.forEach(function(cat){
				cat.items.forEach(function(item){
					tot += item.itemTotal()-0;
					totQty += item.qty()-0;

					if (item.qty()-0)
					{
						orderdata.items[item.itemId] = item.qty();
						totProd++;
					}
				});
			});

			orderModel.totalAmount(tot);
			orderModel.totQty(totQty);
			orderModel.totProd(totProd);

			orderdata.address = JSON.parse(ko.toJSON(orderModel.address));

			localStorage.setItem("orderdata", JSON.stringify(orderdata));

			return;
		});

		orderModel.isFilterCart = ko.observable(false);
		orderModel.filterCartItems = function(){
			orderModel.isFilterCart(!orderModel.isFilterCart());
		};

		orderModel.filterCat = function(itm){
			orderModel.categories.forEach(function(cat){
				cat.isVisible(itm == orderModel);
			});

			if (itm != orderModel) {
				itm.isVisible(true);
			}
			
			hideMenu();
		};

		orderModel.clearCart = function(){
			if (!confirm("Are you sure to clear cart ?")) {
				return false;
			}

			orderModel.categories.forEach(function(cat){
				cat.items.forEach(function(item){
					item.qty("");
				});
			});
			localStorage.removeItem("orderdata");
		};

		orderModel.reCaptcha = function(){
			$.get("order/captcha", function(resp){
				if (resp && resp[2] && resp[2].captcha) {
					$("span#captcha").html(resp[2].captcha);
				}
			});
		};

		orderModel.page = ko.observable(1);
		orderModel.nextPage = function(){
			if (!data.hasContact) {
				orderModel.page(orderModel.page() + 1);
				orderModel.reCaptcha();
			} else {
				orderModel.submitCart();
			}
		};

		orderModel.prevPage = function(){
			if (!data.hasContact) {
				orderModel.page(orderModel.page() - 1);
			}
		};

		orderModel.submitCart = function(){
			if (!data.hasContact && !orderModel.address.phone || !orderModel.address.name) {
				alert("Phone no, Name required");
				return false;
			}

			var postData = {
				items: []
			};

			if (!data.hasContact) {
				postData.address = JSON.parse(ko.toJSON(orderModel.address));
			}

			orderModel.categories.forEach(function(cat){
				cat.items.forEach(function(item){
					if (item.qty()-0)
					{
						postData.items.push({
							itemId: item.itemId,
							// name: item.name,
							qty: item.qty()
						});
					}
				});
			});

			if (!postData.items.length) {
				alert("No items selected to submit.");
				return false;
			}
console.log("postData : ", postData);

			if (!hasContact) {
				if (!postData.address.phone){
					alert("Phone number required");
					return false;
				}

				if (!postData.address.name){
					alert("Name required");
					return false;
				}
			}

			/*if (!postData.address.email){
				alert("Email required");
				return false;
			}*/

			var REG_EXP_EMAIL = new RegExp(/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$$/);
			/*if (!postData.address.email.match(REG_EXP_EMAIL)){
				alert("Enter valid mail id");
				return false;
			}*/

			$.post(_OBooks.site_url + "/order/save?q=" + _OBooks.query, postData, function(resp){
				// alert("Order Submitted, One of our staff will contact you soon. Thank You...");
				// localStorage.removeItem("orderdata");
				// window.location.reload();

				if (resp && resp[0] == 1) {
					if (resp[2].tNo)
					{
						// Update order list in localstorage.
						var orders = localStorage.getItem("orders") || "[]";
						orders = JSON.parse(orders);
						orders.push(resp[2]);
						JSON.stringify(orders);
						localStorage.setItem("orders", JSON.stringify(orders));

						localStorage.removeItem("orderdata");
						alert("Order Submitted, your order no : " + resp[2].tNo + ".\nOne of our staff will contact you soon. Thank You...");
						window.location.reload();
					}
				} else if (resp[1]) {
					alert("Error : " + resp[1]);

					if (resp[2] && resp[2].captcha) {
						orderModel.address.captcha("");
						$("span#captcha").html(resp[2].captcha);
						$("input#captcha").focus();
					}
				}
			});
		};
	};

	var hideMenu = function(){
		$("body").removeClass("hasMenu");
	};

	$(document).ready(function(){
		var address = {
			/*
			name: "T.Suresh Pandi",
			address1: "529, 1st Street",
			address2: "Parasakthi Colony",
			city: "Sivakasi",
			zip: "626123",
			phone: "9698987388",
			email: "tsureshpandi@gmail.com",
			gstin: "33DOTPS9219R1ZN",
			*/
			stateName: "Tamil Nadu",
			stateId: 35,
			stateCode: "TN",
			country: "India",
			countryCode: "IN",
		};

		if (lOrderdata.address) {
			address = Object.assign(address, lOrderdata.address);
		}

		initKo({
			hasContact: hasContact,
			categories: categories,
			address: address
		});

		$("#leftMenu .dimmer").click(hideMenu);
		$("#toggleMenu").click(function(){
			$("body").toggleClass("hasMenu");
		});

		var itemTable = $("#main-container").get(0);
		ko.applyBindings(orderModel, itemTable);
/*
		var mMedia = window.matchMedia("(max-width: 767px)");
		mMediaListener(mMedia);
		mMedia.addEventListener("change", mMediaListener);
*/
	});

})(window.OBooks, jQuery, ko);
