/*
	Stempora Web Framework
	Copyright (c) 2002-2018 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com				
*/

var STBGlobalFormsDatePicker = Object.create(STBModule.prototype);

STBGlobalFormsDatePicker.name		= "GlobalFormsDatePicker";
STBGlobalFormsDatePicker.script		= site.assets + "plugins/datepicker/plugin.js";
STBGlobalFormsDatePicker.scriptIntl = site.assets + "plugins/datepicker/plugin-intl.js";

STBGlobalFormsDatePicker.initPluginCallback = function() {
		
	var elements = null,
		html = jQuery("html"),
		locale = STBUtils.momentConvertLocale(html.attr("lang"))

	//set the icons for calendar
	if (html.attr("dir") == "rtl") {
		icons = {
			next		: 'icon icomoon icon-arrow-left2',
			previous	: 'icon icomoon icon-arrow-right2',
			up			: 'icon icomoon icon-arrow-up2',
			down		: 'icon icomoon icon-arrow-down2', 
			time		: 'icon icomoon icon-clock', 
			date		: 'icon icomoon icon-calendar2', 
		};

		horiz = "right";

	} else {
		icons = {
			next		: 'icon icomoon icon-arrow-right2',
			previous	: 'icon icomoon icon-arrow-left2',
			up			: 'icon icomoon icon-arrow-up2',
			down		: 'icon icomoon icon-arrow-down2', 
			time		: 'icon icomoon icon-clock', 
			date		: 'icon icomoon icon-calendar2', 
		};

		horiz = "left";
	}

	//initialize calendars

	elements = jQuery("input[data-calendar]:not(.__done)");

	if (elements.length) {
		elements.datetimepicker({
			format: "DD MMM YYYY",
			locale: locale,
			widgetPositioning: {
				horizontal: horiz,
				vertical: 'auto'
			},

			icons: icons
		});

		elements.on('change', function () {
			jQuery(this).blur();
		});

		elements.addClass("__done");
	}

	//initialize time pickes
	elements = jQuery("input[data-time]:not(._done)");

	if (elements.length) {
	   elements.datetimepicker({
			format: "H:mm A",
			locale: locale,
			widgetPositioning: {
				horizontal: horiz,
				vertical: 'auto'
			},

			icons: icons
		});

		elements.addClass("__done");
	}


	//initialize calendars with time picker
	elements = jQuery("input[data-calendar-time]:not(.__done)");

	if (elements.length) {
		elements.datetimepicker({
			format: "DD MMM YYYY H:mm A",
			locale: locale,
			widgetPositioning: {
				horizontal: horiz,
				vertical: 'auto'
			},

			icons: icons
		});

		elements.addClass("__done");
	}
}

STBGlobalFormsDatePicker.initPlugin = function() {
	var script  = jQuery("html").attr("lang") == "en" ? STBGlobalFormsDatePicker.script : STBGlobalFormsDatePicker.scriptInt,
		elements = jQuery("input[data-calendar-time],input[data-calendar],input[data-time]");

	if (elements.length > 0){
		STBUtils.loadScriptCallback(
			script,
			STBGlobalFormsDatePicker.initPluginCallback,
			true
		);
	}

}

STBGlobalFormsDatePicker.runOnReady = function() {
	STBGlobalFormsDatePicker.initPlugin();
}

STBGlobalFormsDatePicker.runOnContentUpdate = function() {
	STBGlobalFormsDatePicker.initPlugin();
}

site.registerModule(STBGlobalFormsDatePicker);