window.OBooks = window.OBooks || {};

(function ($, window, document, _OBooks, undefined) {

	_OBooks.error = Function.prototype.bind.call(console.error, console, "OutputBooks : ");
	_OBooks.log = Function.prototype.bind.call(console.log, console, "OutputBooks : ");

	// toFixed Extends Begins

	var _toFixed = Number.prototype.toFixed;
	var myToFixed = function(digits){
		return _toFixed.call((Math.round(this * Math.pow(10,digits)) / Math.pow(10,digits)), digits);
	};

	Number.prototype.precision = function(min=2, max=4) {
		return (this).toFixed(max).replace(new RegExp("0{0," + min + "}$"), "");
	}

	myToFixed.toString = function(){ return 'function toFixed() { [native code] }'; };
	Number.prototype.toFixed = myToFixed;
	Number.prototype.orgToFixed = _toFixed;
	Number.prototype.toFixedRaw = function(digits) {
		return this.toString().match(new RegExp('^-?\\d+(?:\.\\d{0,' + (digits || -1) + '})?'))[0];
	}

	String.prototype.escapeForRegex = function(){
		return this.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
	};
	String.prototype.shuffle = function(){
		let arr = this.split(""); // Convert string to array of characters
		for (let i = arr.length - 1; i > 0; i--) {
			let j = Math.floor(Math.random() * (i + 1)); // Random index
			[arr[i], arr[j]] = [arr[j], arr[i]]; // Swap
		}
		return arr.join(""); // Convert back to string
	};


	// toFixed Extends End

	// OBooks.Parser.parse("Math.sqrt(2 * (#length + #breadth))");

	_OBooks.getGrid = function(component){
		return ng.getComponent(document.getElementsByTagName(component || "app-transgrid")[0]);
	};

	_OBooks.Parser = {
		expr: /\#(\w+)(\|(\w+))?/ig, // Updated regex to capture format types (e.g., |datetime, |date, |time)
		dispExpr: /\#(\w+)(\|([A-Za-z0-9: -]+))?/ig,
		parse: function (str) {
		    str = str.split(";");
		    var matches = str[0].matchAll(_OBooks.Parser.expr);
		    var ret = [];
		    for (const _match of matches) {
		        ret.push({
		            name: _match[1],
		            type: _match[3] || 'number' // Default to 'number' if no format is specified
		        });
		    }
		    return ret;
		},
		replace: function (str, obj, isDisplay) {
			if (!str) {
				return;
			}

		    str = str.split(";");

		    return str[0].replace(isDisplay ? _OBooks.Parser.dispExpr : _OBooks.Parser.expr, function (a, b, c, d) {
				let value = obj[b];

				if (c && d) {
					if (d === 'date') {
						return value ? new Date(value).getTime() : new Date();
					} else if (d === 'datetime') {
						return value ? new Date(value).getTime() : new Date();
					}

					return value !== undefined ? new Date(value).format(d) : 0;
				}

				return value !== undefined ? value : 0; // Default number case
		    });
		},
		eval: function (str, obj) {
		    str = str.split(";");
		    return eval(_OBooks.Parser.replace(str[0], obj, false));
		},
		backEval: function(str, obj, calcFieldByObj, qty){
			str = str.split(";");
			var ret = false;
			if (str[1] && qty)
			{
				var keys = Object.keys(obj);
				keys.forEach(function(key){
					if (str[1].indexOf("#" + key + "=") === 0) {
						calcFieldByObj[key].value = obj[key] = eval(_OBooks.Parser.replace(str[1].replace("#" + key + "=", "").replace("#Qty", qty), obj));
						ret = true;
					}
				});
			}
			return ret;
		}
	};

	_OBooks.enableHelps = true;
	_OBooks.toggleHelps = function(){
		$(".ohelp").toggle();
	};

	_OBooks.invTemplateColors = [
		"#000000", "#993300", "#333300", "#000080", "#333399", "#333333",
		"#800000", "#FF6600", "#808000", "#008000", "#008080", "#0000FF",
		"#666699", "#808080", "#FF0000", "#FF9900", "#339966", "#3682CD",
		"#3366FF", "#800080", "#999999", "#FF00FF", "#993366", "#C0C0C0",
		"#AA3B3B", "#208ED3"
	];

	_OBooks.patterns = {
		pan: /[a-zA-Z]{5}[0-9]{4}[a-zA-Z]/,
		pan_new: /[a-zA-Z]{4}[0-9]{5}[a-zA-Z]/,
		gstin: /[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z][0-9a-zA-Z]{3}/,
		gstin_new: /[0-9]{2}[a-zA-Z]{4}[0-9]{5}[a-zA-Z][0-9a-zA-Z]{3}/,
		gstin_new2:/[0-9]{4}[A-Z]{3}[0-9]{5}[UO]{1}[N][A-Z0-9]{1}/,
		gstin_99:/99[A-Z0-9]{2,3}[A-Z0-9]{10}[A-Z0-9]{1}/,
		gstin_96:/96[A-Z]{3}[0-9]{7}[UN]{1}[A-Z0-9]{1}/,
		cen: /[8]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z][0-9a-zA-Z]{3}/
	};

	_OBooks.Storage = {
		prefix: "ob_",
		get: function (key, defVal) {
			return localStorage.getItem(this.prefix + key) || defVal;
		},
		set: function (key, val) {
			if (!val) {
				localStorage.removeItem(this.prefix + key);
			}
			return localStorage.setItem(this.prefix + key, val);
		},
		remove: function(key) {
			localStorage.removeItem(this.prefix + key);
		},
		clear: function () {
			return localStorage.clear();
		}
	};
	_OBooks.PrinterStorage = {
		prefix: "ob_",
		get: function (key, defVal) {
			return localStorage.getItem(this.prefix + key) || defVal;
		},
		set: function (key, val) {
			if (!val) {
				localStorage.removeItem(this.prefix + key);
			}
			return localStorage.setItem(this.prefix + key, val);
		},
		remove: function(key) {
			localStorage.removeItem(this.prefix + key);
		},
		clear: function () {
			return localStorage.clear();
		}
	};
	_OBooks.getGSTINCheckSum = function (gstinWOCheckDigit){
		var factor = 2;
		var sum = 0;
		var checkCodePoint = 0;
		var cpChars = [];
		var inputChars = [];

		if (!gstinWOCheckDigit) {
			alert("GSTIN supplied for checkdigit calculation is null");
			return false;
		}

		var GSTN_CODEPOINT_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

		cpChars = GSTN_CODEPOINT_CHARS.split("");
		inputChars = gstinWOCheckDigit.toUpperCase().split("");

		var mod = cpChars.length;
		for (var i = inputChars.length - 1; i >= 0; i--)
		{
			/*
			var codePoint = -1;
			for (var j = 0; j < cpChars.length; j++)
			{
				if (cpChars[j] == inputChars[i])
				{
					codePoint = j;
				}
			}
			var digit = factor * codePoint;
			*/
			var digit = factor * cpChars.indexOf(inputChars[i]);
			factor = (factor == 2) ? 1 : 2;
			digit = parseInt(((digit / mod) + (digit % mod)) + "");
			sum += digit;
		}
		checkCodePoint = (mod - (sum % mod)) % mod;

		return gstinWOCheckDigit + cpChars[checkCodePoint];
	};
/*
function checksum(g){
    let a=65,b=55,c=36;
    return Array['from'](g).reduce((i,j,k,g)=>{ 
    p=(p=(j.charCodeAt(0)<a?parseInt(j):j.charCodeAt(0)-b)*(k%2+1))>c?1+(p-c):p;
    return k<14?i+p:j==((c=(c-(i%c)))<10?c:String.fromCharCode(c+b));
    },0);     
}

//console.log(checksum('27AAPFU0939F1ZV')) //true
//console.log(checksum('27AASCS2460H1Z0')) //false
//console.log(checksum('29AAGCB7383J1Z4')) //true
*/
	_OBooks.isValid = {
		gstin: function(val,stateTin='') {
			if (!val) {
				return true;
			}

			if(stateTin != '' && parseInt(stateTin) < 10){
				stateTin = '0' + parseInt(stateTin);
			}
			val = val.toUpperCase();
			// for foregin services provider company (NRTP)
			if (val &&  (_OBooks.patterns.gstin_99.test(val) ||  _OBooks.patterns.gstin_96.test(val)))
			{
				return true;
			}
			return (val && (_OBooks.patterns.gstin.test(val) || _OBooks.patterns.gstin_new.test(val) || _OBooks.patterns.gstin_new2.test(val)) && _OBooks.getGSTINCheckSum(val.substr(0, val.length-1)) == val && (stateTin == '' || stateTin == val.substr(0,2)));
		},
		pan: function(val) {
			return (val && (_OBooks.patterns.pan.test(val.toUpperCase()) || _OBooks.patterns.pan_new.test(val.toUpperCase())));
		},
		cen: function(val,stateTin='') {
			if (!val) {
				return true;
			}

			if(stateTin != '' && parseInt(stateTin) < 10){
				stateTin = '0' + parseInt(stateTin);
			}
			val = val.toUpperCase();
			return (val && _OBooks.patterns.cen.test(val));
		},
	};

	_OBooks.iframeform = function(url) {
		var object = this;
		object.time = new Date().getTime();
		object.form = $('<form action="'+url+'" target="iframe'+object.time+'" method="post" style="display:none;" id="form'+object.time+'" name="form'+object.time+'"></form>');

		object.addParameter = function(parameter,value)
		{
			$("<input type='hidden' />")
			.attr("name", parameter)
			.attr("value", value)
			.appendTo(object.form);
		}

		object.send = function()
		{
			var iframe = $('<iframe data-time="'+object.time+'" style="display:none;" id="iframe'+object.time+'"></iframe>');
			$( "body" ).append(iframe); 
			$( "body" ).append(object.form);
			object.form.submit();
			iframe.load(function(){  $('#form'+$(this).data('time')).remove();  $(this).remove();   });
		}
	}

	var anchorDownload = function(url){
		var filename = url.split("/").pop();
		if((pos = filename.indexOf('?t=')) != -1)
		{
			filename = filename.substr(0,pos);
		}
		var a = document.createElement("a");
		a.href = url;
		a.setAttribute("download", filename);
		a.click();
		return;
	};

	_OBooks.downloadFile = function(url, onload,ispreview=0) {
		if(ispreview){
			var ifrm = document.createElement("iframe");
			ifrm.setAttribute("src", url);
			ifrm.style.width = "0px";
			ifrm.style.height = "0px";
			ifrm.onload = function(){
				if (typeof onload === "function")
				{
					onload(ifrm);
				}

				try{
					var ifr_con = ifrm.contentWindow.document.body.innerText;
					ifr_con = JSON.parse(ifr_con);
					if (ifr_con[0])
					{
						if (ifr_con[2] && ifr_con[2].url && ifr_con[2].forceDownload)
						{
							return anchorDownload(ifr_con[2].url);
						}
						return new window["SnackBar"](ifr_con[1]).success(false);
					}
					else
					{
						return new window["SnackBar"](ifr_con[1]).danger(false);
					}
				} catch(err) {
					return;
				}
			};
			
			document.body.appendChild(ifrm);
			return ifrm;
		}
		else
		{
			return anchorDownload(url);
		}
	};

	var socketList = {};
	var socketTimeout = {};
	var printSuccess = false;
	var printQueue = {};
	function printWithoutPreviewKot(url, isPrint, onload, onResp) {
		setTimeout(function(){
			getPrintData(url, isPrint, onload, onResp);
		}, 2000);
	}

	function printWithoutPreview(url, isPrint, onload, onResp)
	{
		var hidePrintPreview = _OBooks.Storage.get("hidePrintPreview") ? (_OBooks.Storage.get("hidePrintPreview") - 0) > 0 : false;
		var defaultLocalPrinter= JSON.parse(_OBooks.PrinterStorage.get("devicePrinter") || "{}");

		if (!isPrint || !window["WebSocketPrinter"] || (!defaultLocalPrinter|| !defaultLocalPrinter.accessUrl))
		{
			printFile(url, isPrint, onload, onResp);
			return;
		}
		getPrintData(url, isPrint, onload, onResp);
		
	}
	function getPrintData(url, isPrint, onload, onResp) {
		var defaultLocalPrinter= JSON.parse(_OBooks.PrinterStorage.get("devicePrinter") || "{}");
		fetch(url + "?download=0").then(response => response.text()).then((response) => {
			try {
				let resp = JSON.parse(response);

				if (!resp || !resp[0] || !resp[2])
				{
					printFile(url, isPrint, onload, onResp);
					return false;
				}

				var accessUrl = resp[2].accessUrl;

				if (!accessUrl)
				{	
					if(defaultLocalPrinter && defaultLocalPrinter.accessUrl) {
						accessUrl = defaultLocalPrinter.accessUrl || "127.0.0.1:12212";
						resp[2].accessUrl = accessUrl;
					} else {
						printFile(url, isPrint, onload, onResp);
						return false;
					}	
					
				}

				if (!socketList[accessUrl] || !socketList[accessUrl].isConnected())
				{
					let protocol = (location.protocol == "https:") ? "wss://" : "ws://";
					socketList[accessUrl] = new WebSocketPrinter({
						url: (protocol + accessUrl + "/printer"),
						onConnect: function(){
							printSocket(resp[2], onload);
						},
						onDisconnect: function(){
							if (!printSuccess)
							{
								printFile(url, isPrint, onload, onResp);
							}
						},
						onUpdate: function(data){
							console.log("socket data : ", data);
							if (data) {
								/*
								data = JSON.parse(data);
								// {"status":0,"message":"Success"}
								if (data.message == "Success")
								{
									
								}
								*/
								if (printQueue[accessUrl] && printQueue[accessUrl].length > 0)
								{
									printQueue[accessUrl].splice(0, 1);
								}

								if (printQueue[accessUrl] && printQueue[accessUrl].length > 0)
								{
									setTimeout(function(){
										socketList[accessUrl].submit(printQueue[accessUrl]);
									}, 200);
								}
							}
						}
					});
				} else {
					if (socketTimeout[resp.accessUrl])
					{
						clearTimeout(socketTimeout[resp.accessUrl]);
						socketTimeout[resp.accessUrl] = null;
					}

					printSocket(resp[2], onload);

					typeof onload === "function" && onload(true);
				}
			} catch(e) {
				console.log("Catch ", e);
				printFile(url, isPrint, onload, onResp);
			}
		});
	}

	function printSocket(resp, onload)
	{
		printSuccess = true;
		console.log("printSocket : ", resp.name, resp.pdfUrl);
/*
		if (!printQueue[resp.accessUrl])
		{
			printQueue[resp.accessUrl] = [];
		}

		printQueue[resp.accessUrl].push({
			type: resp.name || "DEFAULT",
			url: resp.pdfUrl
		});

		
		if (printQueue[resp.accessUrl].length == 1)
		{
			socketList[resp.accessUrl].submit(printQueue[resp.accessUrl][0]);
		}
*/
		socketList[resp.accessUrl].submit({
			type: resp.name || "DEFAULT",
			url: resp.pdfUrl
		});

		if (typeof onload === "function")
		{
			onload(true);
		}
/*
		socketTimeout[resp.accessUrl] = setTimeout(function(){
			socketList[resp.accessUrl].close();
		}, 5000);
*/
	}

	var checkWebSocket = null;
	var webSocketConnected = false;
	_OBooks.print_socket_url = "";
	_OBooks.checkPrintSocket = function(onConnect,onUpdate) {
		if(!WebSocketPrinter)
		{
			onConnect(false);
			return;
		}

		_OBooks.print_socket_url = _OBooks.print_socket_url || "127.0.0.1:12212";
		let protocol = (location.protocol == "https:") ? "wss://" : "ws://";
		checkWebSocket = new WebSocketPrinter({
			url:(protocol + _OBooks.print_socket_url + "/printer"),
			onConnect: function () {
				webSocketConnected = true;
				if(checkWebSocket) {
					setTimeout(function(){
						checkWebSocket.close();
						checkWebSocket = null;
					}, 1000);
				}
				onConnect(true)
			},
			onDisconnect: function () {
				// console.log(checkWebSocket);
				// checkWebSocket.autoReconnect = false;
				// checkWebSocket.websocket.close();
				onConnect(webSocketConnected ? webSocketConnected : false);
				checkWebSocket = null;
			},
			onUpdate:function (e) {
				onUpdate(e);
			}
		});
	};

	_OBooks.printToPdf = function(url, isPrint, onload, onResp) {
		if (isPrint === undefined)
		{
			isPrint = false;
		}

		printWithoutPreview(url, isPrint, onload, onResp);
	};
	_OBooks.printkot = function(url, isPrint, onload, onResp) {
		if (isPrint === undefined)
		{
			isPrint = false;
		}

		printWithoutPreviewKot(url, isPrint, onload, onResp);
	};

	function printFile(url, isPrint, onload, onResp) {
		var ifrm = _OBooks.downloadFile(url, function(ifrm){
			if (typeof onload === "function")
			{
				onload(ifrm);
			}

			if (isPrint)
			{
				ifrm.contentWindow.print();
				/*
				try {
					var ifr_con = ifrm.contentWindow.document.body.innerText;
					ifr_con = JSON.parse(ifr_con);

					if (ifr_con[0] && ifr_con[2] && ifr_con[2].pdfUrl)
					{
						printFile(ifr_con[2].pdfUrl, true, onload, onResp);
					}

					typeof onResp === "function" && onResp(ifr_con);
				} catch(err) {
					ifrm.contentWindow.print();
				}
				*/
			}
		}, 1);
	}

	_OBooks.getGeoLocation = function(force){
		var pos = _OBooks.Storage.get("geolocation");
		if (pos && !force) {
			return pos;
		}

		if (!pos && navigator && navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(pos){
				console.log("geolocation : ", pos);
				_OBooks.Storage.set("geolocation", pos);
			}, function(err){
				console.log("geolocation Err : ", err);
			});
		}
	}

	_OBooks.print = function() {
		window.print();
	}

	_OBooks.progress = function(isShow, txt) {
		$(".ui.text.loader").text(txt || "");

		if (isShow){
			$("body > #loader").show();
		} else {
			$("body > #loader").hide();
		}
	}

	_OBooks.xhrHook = function(callback) {
		if (typeof callback !== "function")
		{
			console.log("Usage : OBooks.xhrHook(function(xhr,params){console.log(xhr,params);});");
			return;
		}

		var oldSend, i;
		if(XMLHttpRequest.callbacks)
		{
			XMLHttpRequest.callbacks.push(callback);
		}
		else
		{
			XMLHttpRequest.callbacks = [callback];

			oldSend = XMLHttpRequest.prototype.send;

			XMLHttpRequest.prototype.send = function(){
				for(i=0; i<XMLHttpRequest.callbacks.length; i++)
				{
					XMLHttpRequest.callbacks[i](this, arguments);
				}
				oldSend.apply(this, arguments);
			};
		}
	}

	_OBooks.crypt53 = function(str, seed=0) {
		let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
		for (var i=0, ch; i < str.length; i++)
		{
			ch = str.charCodeAt(i);
			h1 = Math.imul(h1 ^ ch, 2654435761);
			h2 = Math.imul(h2 ^ ch, 1597334677);
		}
		h1 = Math.imul(h1 ^ h1>>>16, 2246822507) ^ Math.imul(h2 ^ h2>>>13, 3266489909);
		h2 = Math.imul(h2 ^ h2>>>16, 2246822507) ^ Math.imul(h1 ^ h1>>>13, 3266489909);

		return (4294967296 * (2097151 & h2) + (h1>>>0)).toString(16);
	};

	_OBooks.HashStr = function(str){
		return _OBooks.crypt53(str) + _OBooks.crypt53(str, 1);
	};

	_OBooks.editTrans = function(tId, tType, tNo){
		console.log("Edit Trans : ", tId, tNo, tType);
	};

	_OBooks.showTrans = function(tId, tType, tNo){
		console.log("Show Trans : ", tId, tNo, tType);
	};

	_OBooks.Tracer = function(obj, key){
		let tmp = obj[key];
		Object.defineProperty(obj, key, {
			get(){
				return tmp;
			},
			set(val){
				console.error(key, " : ", val);
				tmp = val;
			}
		});
	};

	_OBooks.TraceArray = function(obj, key){
		obj[key] = new Proxy(obj[key], {
			set(target, prop, value) {
				console.error(`Prop : ${prop} changed →`, value);
				target[prop] = value;
				return true;
			}
		});
	};

	/*
	$(document).ready(function() {
		$('input').on('keydown', function(event) {
			if (this.selectionStart == 0 && event.keyCode >= 65 && event.keyCode <= 90 && !(event.shiftKey) && !(event.ctrlKey) && !(event.metaKey) && !(event.altKey) && !(this.value)) {
				var $t = $(this);
				event.preventDefault();
				var char = String.fromCharCode(event.keyCode);
				$t.val(char + $t.val().slice(this.selectionEnd));
				this.setSelectionRange(1,1);
			}
		});
	});
	*/
})(jQuery, window, document, window.OBooks);

// On user profile image error background color.
(function ($, window, document, _OBooks, undefined) {
	var colors = [
		'#5A8770', '#0088B9', '#A50A98', '#F12765', '#0677B3',
		'#A6B12E', '#BD7B16', '#D93A37', '#5D3372', '#82024A',
		'#424101', '#4B1B38',

		'#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5',
		'#004D45', '#214D22', '#5E661B', '#4D2C18', '#4D362E',
		'#4D4D4D', '#35454D',
	];

	var getColor = function(txt){
		var asciiTotal	= 0;
		for (var i=0, len=txt.length; i<len; i++){
			asciiTotal += txt.charCodeAt(i);
		}

		return colors[asciiTotal % colors.length];
	};
	var getRandomColors = function() {
		var letters = '0123456789ABCDEF'.split('');
		var _color = '#';
		for (var i = 0; i < 6; i++) {
			_color += letters[Math.floor(Math.random() * 16)];
		}
		return _color;
	};
	var getFirstAndLastName = function(data) {
		var names = data.split(" ");
		if (names && names.length) {
			var firstName = names[0];
			var lastName = names[1];
			if (firstName && lastName) {
				return (firstName.substr(0, 1) + lastName.substr(0, 1)).toUpperCase();
			} else {
				return data.substr(0, 2).toUpperCase();
			}
		}
		return 
	};
	var setAttr = function(tag, name, value) {
		tag.setAttribute(name, value);
	}
	var getImgTag = function(width, height, color) {
		var svgTag = document.createElement('svg');
		setAttr(svgTag, 'xmlns', 'http://www.w3.org/2000/svg');
		setAttr(svgTag, 'pointer-events', 'none');
		setAttr(svgTag, 'width', width);
		setAttr(svgTag, 'height', height);

		svgTag.style.backgroundColor = color;
		svgTag.style.width = width + 'px';
		svgTag.style.height = height + 'px';

		return svgTag;
	};
	var getCharacterObject = function(character) {
		var textTag = document.createElement('text');

		setAttr(textTag, 'text-anchor', 'middle');
		setAttr(textTag, 'y', '50%');
		setAttr(textTag, 'x', '50%');
		setAttr(textTag, 'dy', '0.35em');
		setAttr(textTag, 'pointer-events', 'auto');
		setAttr(textTag, 'fill', '#FFFFFF');
		setAttr(textTag, 'font-family', 'HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica, Arial,Lucida Grande, sans-serif');

		textTag.style.fontWeight = '400';
		textTag.style.fontSize = '25px';
		textTag.appendChild(document.createTextNode(character));

		return textTag;
	};

	var onImageError = function(elem){
		var txt = elem.getAttribute('title') || ':)';
		var tag = getImgTag(50, 50, getColor(txt));
		tag.appendChild(getCharacterObject(getFirstAndLastName(txt)));
		var svgHtml = 'data:image/svg+xml;base64,' + window.btoa(window["unescape"](encodeURIComponent(tag.outerHTML)));
		elem.setAttribute('src', svgHtml);
	};

	window['onImageError'] = _OBooks.onImageError = onImageError;

	window["onLogoError"] = _OBooks.onLogoError = function(elem){
		elem.setAttribute("src", window.OBooks.base_url + "assets/img/square-image.png");
	}

	// formatMoney(123456789.254, 'INR');
	window["formatNumber"] = function(value, currencyCode){
		value = value + "";
		if (currencyCode == "INR")
		{
			return value.replace(/(\d)(?=(\d{2})+\d\.)/g, "$1,");
		}

		return value.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
	};

	window.obScrollToView = function(container, item, direction) {
		container = $(container);
		item = $(item);
		var containerTop = container.scrollTop();
		var containerBottom = containerTop + container.height();
		var itemTop = item.position().top + container.scrollTop();
		var itemBottom = itemTop + item.outerHeight();

		if (direction === 'down' && itemBottom > containerBottom) {
			container.scrollTop(itemBottom - container.height());
		} else if (direction === 'up' && itemTop < containerTop) {
			container.scrollTop(itemTop);
		}
	}
})(jQuery, window, document, window.OBooks);

(function(window){
	var obiDBv = localStorage.getItem("obiDBv")-0;

	if (!obiDBv || obiDBv < window.OBooks.iDBv) {
		var indexedDB = window["indexedDB"] || window["webkitIndexedDB"] || window["mozIndexedDB"];
		indexedDB.databases().then(function(r){
			for (let i=0, iLen=r.length; i < iLen; i++) {
				console.log("Deleting : ", r[i].name);
				indexedDB.deleteDatabase(r[i].name);
			}
		}).then(function(){
			localStorage.setItem("obiDBv", window.OBooks.iDBv);
			console.log("Deleted : ");
		});
	}
})(window);
