/*Sets Themed Colors Based on Themes*/

var themeprimary = getThemeColorFromCss('themeprimary');
var themesecondary = getThemeColorFromCss('themesecondary');
var themethirdcolor = getThemeColorFromCss('themethirdcolor');
var themefourthcolor = getThemeColorFromCss('themefourthcolor');
var themefifthcolor = getThemeColorFromCss('themefifthcolor');

//Gets Theme Colors From Selected Skin To Use For Drawing Charts
function getThemeColorFromCss(style) {
	var $span = $("<span></span>").hide().appendTo("body");
	$span.addClass(style);
	var color = $span.css("color");
	$span.remove();
	return color;
}

//Handle RTL Support for Changer CheckBox
$("#skin-changer li a").click(function () {
	createCookie("current-skin", $(this).attr('rel'), 10);
	window.location.reload();
});

//Checks Not to Do rtl-support for Arabic and Persian Demo Pages
var rtlchanger = document.getElementById('rtl-changer');

if (location.pathname != "/index-rtl-fa.html" && location.pathname != "/index-rtl-ar.html") {
	if (readCookie("rtl-support")) {
		switchClasses("pull-right", "pull-left");
		switchClasses("databox-right", "databox-left");
		switchClasses("item-right", "item-left");
		$('.navbar-brand small img').attr('src', 'assets/img/logo-rtl.png');
		if (rtlchanger != null)
			document.getElementById('rtl-changer').checked = true;
	}
	else {
		if (rtlchanger != null)
			rtlchanger.checked = false;
	}

	if (rtlchanger != null) {
		rtlchanger.onchange = function () {
			if (this.checked) {
				createCookie("rtl-support", "true", 10);
			}
			else {
				eraseCookie("rtl-support");
			}
			setTimeout(function () {
				window.location.reload();
			}, 600);

		};
	}
}
/*Loading*/
$(window).load(function () {
	setTimeout(function () {
		/*$('.loading-container').addClass('loading-inactive');*/
		$.loadingScreen('hide');
	}, 300);
});

/*Account Area --> Setting Button*/
$('#btn-setting')
	.on('click', function (e) {
		$('.navbar-account')
			.toggleClass('setting-open');
	});

/*Toggle FullScreen*/
$('.page-content')
	// fullscreen
	.on('click', '#fullscreen-toggler', function (e) {
		var element = document.documentElement;
		if (!$('body')
			.hasClass("full-screen")) {

			$('body')
				.addClass("full-screen");
			$('#fullscreen-toggler')
				.addClass("active");
			if (element.requestFullscreen) {
				element.requestFullscreen();
			} else if (element.mozRequestFullScreen) {
				element.mozRequestFullScreen();
			} else if (element.webkitRequestFullscreen) {
				element.webkitRequestFullscreen();
			} else if (element.msRequestFullscreen) {
				element.msRequestFullscreen();
			}

		} else {
			$('body').removeClass("full-screen");
			$('#fullscreen-toggler').removeClass("active");

			if (document.exitFullscreen) {
				document.exitFullscreen();
			} else if (document.mozCancelFullScreen) {
				document.mozCancelFullScreen();
			} else if (document.webkitExitFullscreen) {
				document.webkitExitFullscreen();
			}
		}
	})
	// refresh
	.on('click', '#refresh-toggler', function (e) {
		if (typeof _windowSettings == 'undefined')
		{
			window.location.reload();
		}
		else
		{
			$.adminLoad(_windowSettings);
		}
	});

/* Handles Popovers and Tooltip */

$('body').popover({
	selector: '[data-toggle=popover]',
	html: true,
	trigger: 'focus'
});

$('body').on("mouseenter", '[data-toggle="popover"][data-trigger="hover"]', function() {
	$(this).popover("show");
});

// OLD
/*$('body').popover({
	html: true,
	selector: '[data-toggle=popover]',
	template: '<div class="popover ' + $(this).data("class") +
		'"><div class="arrow"></div><h3 class="popover-title ' +
		$(this).data("titleclass") + '"></h3><div class="popover-content"></div></div>'
});
$('body').on("mouseenter", '[data-toggle=popover-hover]', function() {
	var _this = this;
	$(this).popover({
		html: true,
		trigger: "manual",
		// animation: false
	})
	.popover("show");
	$(".popover").on("mouseleave", function() {
		$(_this).popover('destroy');
	});
}).on("mouseleave", '[data-toggle=popover-hover]', function() {
	var _this = this;
	setTimeout(function() {
		if (!$(".popover:hover").length) {
			$(_this).popover("destroy");
		}
	}, 300);
});*/

/*$("#pop123").popover({
	trigger: "manual",
	html: true,
	animation: false
	})
	.on("mouseenter", function() {
		var _this = this;
		$(this).popover("show");
		$(".popover").on("mouseleave", function() {
		$(_this).popover('hide');
	});
	}).on("mouseleave", function() {
		var _this = this;
		setTimeout(function() {
	if (!$(".popover:hover").length) {
		$(_this).popover("hide");
		}
	}, 300);
});*/

/*Handles ToolTips*/
$('body').tooltip({
	selector: 'acronym',
	template: '<div class="tooltip-magenta tooltip" role="tooltip"><div class="tooltip-inner"></div><div class="tooltip-arrow"></div></div>'
});

/*$("[data-toggle=tooltip]").tooltip({
	html: true
});*/

InitiateSideMenu();
InitiateSettings();
InitiateWidgets();

function InitiateSideMenu() {
	//Sidebar Toggler
	$(".page-content").on('click', '.sidebar-toggler', function () {
		$("#sidebar").toggleClass("hide");
		$(".sidebar-toggler").toggleClass("active");
		return false;
	});
	//End Sidebar Toggler

	//Sidebar Collapse
	var b = $("#sidebar").hasClass("menu-compact");
	$("#sidebar-collapse").on('click', function () {
		if (!$('#sidebar').is(':visible'))
			$("#sidebar").toggleClass("hide");
		$("#sidebar").toggleClass("menu-compact");
		$(".sidebar-collapse").toggleClass("active");
		b = $("#sidebar").hasClass("menu-compact");

		if ($(".sidebar-menu").closest("div").hasClass("slimScrollDiv")) {
			$(".sidebar-menu").slimScroll({ destroy: true });
			$(".sidebar-menu").attr('style', '');
		}
		if (b) {
			$(".open > .submenu")
				.removeClass("open");
		} else {
			if ($('.page-sidebar').hasClass('sidebar-fixed')) {
				var position = (readCookie("rtl-support") || location.pathname == "/index-rtl-fa.html" || location.pathname == "/index-rtl-ar.html") ? 'right' : 'left';
				$('.sidebar-menu').slimscroll({
					height: 'auto',
					position: position,
					size: '3px',
					color: themeprimary
				});
			}
		}
		//Slim Scroll Handle



	});
	//End Sidebar Collapse

	//Sidebar Menu Handle

	//HostCMS: Fix i.menu-expand
/* 	$(".sidebar-menu i.menu-expand").on('click touchend', function (e) {
		e.stopImmediatePropagation();
		e.preventDefault();

		$(this).closest('li').toggleClass('open');
	}); */

	$(".sidebar-menu").on('click touchend', function (e) {

		var menuLink = $(e.target).closest("a");

		// Скрываем все контекстные меню
		$('.context-menu').hide();

		// Сворачиваем открытые выпадающие списки
		$('.open [data-toggle="dropdown"]').dropdown('toggle');

		if (!menuLink || menuLink.length == 0)
			return;

		// HostCMS: Fix submenu
		if (menuLink.is('[href]') && !$(e.target).hasClass('menu-expand'))
		{
			e.stopImmediatePropagation();
			return;
		}

		if (!menuLink.hasClass("menu-dropdown")) {
			if (b && menuLink.get(0).parentNode.parentNode == this) {
				var menuText = menuLink.find(".menu-text").get(0);
				if (e.target != menuText && !$.contains(menuText, e.target)) {
					return false;
				}
			}
			return;
		}

		var submenu = menuLink.next().get(0);
		if (!$(submenu).is(":visible")) {
			var c = $(submenu.parentNode).closest("ul");
			if (b && c.hasClass("sidebar-menu"))
				return;
			c.find("> .open > .submenu")
				.each(function () {
					if (this != submenu && !$(this.parentNode).hasClass("active"))
						$(this).slideUp(200).parent().removeClass("open");
				});
		}
		if (b && $(submenu.parentNode.parentNode).hasClass("sidebar-menu"))
			return false;
		$(submenu).slideToggle(200).parent().toggleClass("open");
		return false;
	});
	//End Sidebar Menu Handle
}

function InitiateWidgets() {
	$('.page-content').on("click", '.widget-buttons *[data-toggle="maximize"]', function (event) {
		event.preventDefault();
		var widget = $(this).parents(".widget").eq(0);
		var button = $(this).find("i").eq(0);
		var compress = "fa-compress";
		var expand = "fa-expand";
		if (widget.hasClass("maximized")) {
			if (button) {
				button.addClass(expand).removeClass(compress);
			}
			widget.removeClass("maximized");
			widget.find(".widget-body").css("height", "auto");
		} else {
			if (button) {
				button.addClass(compress).removeClass(expand);
			}
			widget.addClass("maximized");
			maximize(widget);
		}
	});

	$('.page-content').on("click", '.widget-buttons *[data-toggle="collapse"]', function (event) {
		event.preventDefault();
		var widget = $(this).parents(".widget").eq(0);
		var body = widget.find(".widget-body");
		var button = $(this).find("i");
		var down = "fa-plus";
		var up = "fa-minus";
		var slidedowninterval = 300;
		var slideupinterval = 200;
		if (widget.hasClass("collapsed")) {
			if (button) {
				button.addClass(up).removeClass(down);
			}
			widget.removeClass("collapsed");
			body.slideUp(0, function () {
				body.slideDown(slidedowninterval);
			});
		} else {
			if (button) {
				button.addClass(down)
					.removeClass(up);
			}
			body.slideUp(slideupinterval, function () {
				widget.addClass("collapsed");
			});
		}
	});

	$('.page-content').on("click", '.widget-buttons *[data-toggle="dispose"]', function (event) {
		event.preventDefault();
		var toolbarLink = $(this);
		var widget = toolbarLink.parents(".widget").eq(0);
		var disposeinterval = 300;
		widget.hide(disposeinterval, function () {
			widget.remove();
		});
	});
}

// Fullscreen Widget
function maximize(widgetbox) {
	if (widgetbox) {
		var windowHeight = $(window).height();
		var headerHeight = widgetbox.find(".widget-header").height();
		widgetbox.find(".widget-body").height(windowHeight - headerHeight);
	}
}

/* Scroll To */
function scrollTo(el, offset) {
	var pos = (el && el.size() > 0) ? el.offset().top : 0;
	jQuery('html,body').animate({ scrollTop: pos + (offset ? offset : 0) }, 'slow');
}

/*Show Notification*/
function Notify(message, description, position, timeout, theme, icon, closable, sound) {
	soundAvailable = $('#sound-switch').data('soundEnabled') === undefined
		? false
		: !!$('#sound-switch').data('soundEnabled');

	if (typeof sound != 'undefined')
	{
		soundAvailable = soundAvailable && sound;
	}

	toastr.options.positionClass = 'toast-' + position;
	toastr.options.extendedTimeOut = 0; //1000;
	toastr.options.timeOut = timeout;
	toastr.options.closeButton = closable;
	toastr.options.iconClass = icon + ' toast-' + theme;
	toastr.options.playSound = soundAvailable;

	if (timeout == 0)
	{
		toastr.options.tapToDismiss = false;
	}

	toastr['custom'](description, message);
}

/*#region handle Settings*/
function InitiateSettings() {
	readCookiesForInitiateSettings();
	// $.readCookiesForInitiateSettings();

	$('#checkbox_fixednavbar')
		.change(function () {
			$('.navbar')
				.toggleClass('navbar-fixed-top');

			if (($('#checkbox_fixedsidebar')
				.is(":checked"))) {
				$('#checkbox_fixedsidebar')
					.prop('checked', false);
				$('.page-sidebar')
					.toggleClass('sidebar-fixed');
			}

			if (($('#checkbox_fixedbreadcrumbs')
				.is(":checked")) && !($(this)
				.is(":checked"))) {
				$('#checkbox_fixedbreadcrumbs')
					.prop('checked', false);
				$('.page-breadcrumbs')
					.toggleClass('breadcrumbs-fixed');
			}

			if (($('#checkbox_fixedheader')
				.is(":checked")) && !($(this)
				.is(":checked"))) {
				$('#checkbox_fixedheader')
					.prop('checked', false);
				$('.page-header')
					.toggleClass('page-header-fixed');
			}
			setCookiesForFixedSettings();
		});

	$('#checkbox_fixedsidebar')
		.change(function () {

			$('.page-sidebar')
				.toggleClass('sidebar-fixed');

			if (!($('#checkbox_fixednavbar')
				.is(":checked"))) {
				$('#checkbox_fixednavbar')
					.prop('checked', true);
				$('.navbar')
					.toggleClass('navbar-fixed-top');
			}
			if (($('#checkbox_fixedbreadcrumbs')
				.is(":checked")) && !($(this)
				.is(":checked"))) {
				$('#checkbox_fixedbreadcrumbs')
					.prop('checked', false);
				$('.page-breadcrumbs')
					.toggleClass('breadcrumbs-fixed');
			}

			if (($('#checkbox_fixedheader')
				.is(":checked")) && !($(this)
				.is(":checked"))) {
				$('#checkbox_fixedheader')
					.prop('checked', false);
				$('.page-header')
					.toggleClass('page-header-fixed');
			}
			setCookiesForFixedSettings();
		});
	$('#checkbox_fixedbreadcrumbs')
		.change(function () {

			$('.page-breadcrumbs')
				.toggleClass('breadcrumbs-fixed');


			if (!($('#checkbox_fixedsidebar')
				.is(":checked"))) {
				$('#checkbox_fixedsidebar')
					.prop('checked', true);
				$('.page-sidebar')
					.toggleClass('sidebar-fixed');
			}
			if (!($('#checkbox_fixednavbar')
				.is(":checked"))) {
				$('#checkbox_fixednavbar')
					.prop('checked', true);
				$('.navbar')
					.toggleClass('navbar-fixed-top');
			}
			if (($('#checkbox_fixedheader')
				.is(":checked")) && !($(this)
				.is(":checked"))) {
				$('#checkbox_fixedheader')
					.prop('checked', false);
				$('.page-header')
					.toggleClass('page-header-fixed');
			}
			setCookiesForFixedSettings();
		});

	$('#checkbox_fixedheader')
		.change(function () {

			$('.page-header')
				.toggleClass('page-header-fixed');

			if (!($('#checkbox_fixedbreadcrumbs')
				.is(":checked"))) {
				$('#checkbox_fixedbreadcrumbs')
					.prop('checked', true);
				$('.page-breadcrumbs')
					.toggleClass('breadcrumbs-fixed');
			}

			if (!($('#checkbox_fixedsidebar')
				.is(":checked"))) {
				$('#checkbox_fixedsidebar')
					.prop('checked', true);
				$('.page-sidebar')
					.toggleClass('sidebar-fixed');
			}
			if (!($('#checkbox_fixednavbar')
				.is(":checked"))) {
				$('#checkbox_fixednavbar')
					.prop('checked', true);
				$('.navbar')
					.toggleClass('navbar-fixed-top');
			}

			setCookiesForFixedSettings();
		});

	$('#checkbox_fixedtables')
		.change(function () {

			if (($('#checkbox_fixedheader')
				.is(":checked")) && !($(this)
				.is(":checked"))) {
				$('#checkbox_fixedheader')
					.prop('checked', false);
			}
			setCookiesForFixedSettings();
			setResizableAdminTableTh();
		});
}

function setCookiesForFixedSettings() {
	createCookie("navbar-fixed-top", $('#checkbox_fixednavbar').is(':checked'), 100);
	createCookie("sidebar-fixed", $('#checkbox_fixedsidebar').is(':checked'), 100);
	createCookie("breadcrumbs-fixed", $('#checkbox_fixedbreadcrumbs').is(':checked'), 100);
	createCookie("page-header-fixed", $('#checkbox_fixedheader').is(':checked'), 100);
	createCookie("tables-fixed", $('#checkbox_fixedtables').is(':checked'), 100);

	if ($('#checkbox_fixedsidebar').is(':checked')) {

		setSlimScrolling4SidebarMenu();

	} else {
		if ($(".sidebar-menu").closest("div").hasClass("slimScrollDiv")) {
			$(".sidebar-menu").slimScroll({ destroy: true });
			$(".sidebar-menu").attr('style', '');
		}
	}
}
/*#endregion handle Settings*/

/*#region Get Colors*/
//Get colors from a string base on theme colors
function getcolor(colorString) {
	switch (colorString) {
		case ("themeprimary"):
			return themeprimary;
		case ("themesecondary"):
			return themesecondary;
		case ("themethirdcolor"):
			return themethirdcolor;
		case ("themefourthcolor"):
			return themefourthcolor;
		case ("themefifthcolor"):
			return themefifthcolor;
		default:
			return colorString;
	}
}
/*#endregion Get Colors*/


//Switch Classes Function
function switchClasses(firstClass, secondClass) {

	var firstclasses = document.getElementsByClassName(firstClass);

	for (i = firstclasses.length - 1; i >= 0; i--) {
		if (!hasClass(firstclasses[i], 'dropdown-menu')) {
			addClass(firstclasses[i], firstClass + '-temp');
			removeClass(firstclasses[i], firstClass);
		}
	}

	var secondclasses = document.getElementsByClassName(secondClass);

	for (i = secondclasses.length - 1; i >= 0; i--) {
		if (!hasClass(secondclasses[i], 'dropdown-menu')) {
			addClass(secondclasses[i], firstClass);
			removeClass(secondclasses[i], secondClass);
		}
	}

	tempClasses = document.getElementsByClassName(firstClass + '-temp');

	for (i = tempClasses.length - 1; i >= 0; i--) {
		if (!hasClass(tempClasses[i], 'dropdown-menu')) {
			addClass(tempClasses[i], secondClass);
			removeClass(tempClasses[i], firstClass + '-temp');
		}
	}
}

//Add Classes Function
function addClass(elem, cls) {
	var oldCls = elem.className;
	if (oldCls) {
		oldCls += " ";
	}
	elem.className = oldCls + cls;
}

//Remove Classes Function
function removeClass(elem, cls) {
	var str = " " + elem.className + " ";
	elem.className = str.replace(" " + cls, "").replace(/^\s+/g, "").replace(/\s+$/g, "");
}

//Has Classes Function
function hasClass(elem, cls) {
	var str = " " + elem.className + " ";
	var testCls = " " + cls + " ";
	return (str.indexOf(testCls) != -1);
}

// Удалено 26/03/2018, проблема с вкладкой во вкладке
/*$('.page-content')
	.on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
		$($(this).attr('href')).find('button[type="submit"]').click();
	});*/