(function (factory) {
	factory(jQuery);
}(function ($) {
	var config = $.IbCookie = function (key, value, options) {
		if (value !== undefined) {
			try {
				if (typeof(config.defaults.domain) === "string") {
					var mainDomain = config.defaults.domain;
					var domain = $.getIbCookieDomain(0);
					var domainLevel = domain.split(".").length;
					var delOptions;
					
					for (var i = 0; i < domainLevel - 1; i++) {
						domain = $.getIbCookieDomain(-1 * i);
						if (domain === mainDomain)
							continue;
	
						delOptions = $.extend({}, config.defaults, options, {"domain": domain});		
						$.removeCookie(key, delOptions);
					}
				}
	
				// TODO: To be removed after will be cleansed in customer browsers
				delOptions = $.extend({}, config.defaults, options);
				if (typeof(delOptions.domain) === "string") {
					delete delOptions["domain"];
					$.removeCookie(key, delOptions);
				}
				if (typeof(delOptions.path) === "string") {
					delete delOptions["path"];
					$.removeCookie(key, delOptions);
				}
				// TODO: End of removal
			} catch (e) {
				console.error("IbCookie error" + e.toString());
			}
			
			options = $.extend({}, config.defaults, options);
		}

		return $.cookie(key, value, options);
	};

	$.getIbCookieDomain = function (domainLevel) {
		var fullDomain = window.location.hostname;

		try {
			var domain = fullDomain;
			var posDot = 0;
			
			if (typeof(domainLevel) === 'undefined')
				return $.getIbCookieDomain(-1);
	
			if (domainLevel >= 0)
				return domain;
			
			for (var i = domainLevel; i < 0; i++) {
				posDot = domain.indexOf(".", 1);
				if (posDot === -1) {
					domain = "";
					break;
				}
				
				domain = domain.slice(posDot);
			}
	
			return domain;
		} catch (e) {
			console.error("getIbCookieDomain error: " + e.toString());
			return fullDomain;
		}
	};
	
	config.defaults = {"domain": ($.getIbCookieDomain(-1) === "" ? $.getIbCookieDomain(0) : $.getIbCookieDomain(-1)), "path": "/", "secure": true}; // "sameSite": "Lax"
		
	$.removeIbCookie = function (key, options) {
		if ($.IbCookie(key) !== undefined) {
			options = $.extend(options, {expires: -1});
			$.IbCookie(key, "", options);
			return true;
		}

		return false;
	};
}));