/*!
 * Callback Widget Script v1.0
 * https://www.phpjabbers.com/callback-widget/
 * 
 * Copyright 2015, StivaSoft Ltd.
 * 
 */
(function (window, undefined){
	"use strict";
	
	pjQ.$.ajaxSetup({
		xhrFields: {
			withCredentials: true
		}
	});
	
	var document = window.document,
		validate = (pjQ.$.fn.validate !== undefined),
		datepicker = (pjQ.$.fn.datepicker !== undefined),
		dialog = (pjQ.$.fn.dialog !== undefined),
		routes = [
		          	
		          ];
	
	function log() {
		if (window.console && window.console.log) {
			for (var x in arguments) {
				if (arguments.hasOwnProperty(x)) {
					window.console.log(arguments[x]);
				}
			}
		}
	}
	
	function assert() {
		if (window && window.console && window.console.assert) {
			window.console.assert.apply(window.console, arguments);
		}
	}
	
	function hashBang(value) {
		if (value !== undefined && value.match(/^#!\//) !== null) {
			if (window.location.hash == value) {
				return false;
			}
			window.location.hash = value;
			return true;
		}
		
		return false;
	}
	
	function onHashChange() {
		var i, iCnt, m;
		for (i = 0, iCnt = routes.length; i < iCnt; i++) {
			m = window.location.hash.match(routes[i].pattern);
			if (m !== null) {
				pjQ.$(window).trigger(routes[i].eventName, m.slice(1));
				break;
			}
		}
		if (m === null) {
			pjQ.$(window).trigger("loadEvents");
		}
	}
	pjQ.$(window).on("hashchange", function (e) {
    	onHashChange.call(null);
    });
	
	function CallbackWidget(opts) {
		if (!(this instanceof CallbackWidget)) {
			return new CallbackWidget(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	CallbackWidget.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	CallbackWidget.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				size += 1;
			}
		}
		return size;
	};
	
	CallbackWidget.prototype = {
		reset: function () {
			this.$container = null;
			this.container = null;
			this.$sectionCallBack = null;
			this.opts = {};
			
			return this;
		},
		disableButtons: function () {
			var $el;
			this.$container.find(".btn").each(function (i, el) {
				$el = pjQ.$(el).attr('disabled', 'disabled').addClass("pjCWBtnDisabled");
			});
		},
		enableButtons: function () {
			this.$container.find(".btn").removeAttr('disabled').removeClass("pjCWBtnDisabled");
		},
		
		init: function (opts) {
			var self = this;
			this.opts = opts;
			this.container = document.getElementById("cmContainer_" + this.opts.index);
			this.$container = pjQ.$(this.container),
			
			this.$container.on('click.cm', '.btnSectionTrigger', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				if(!pjQ.$(this).hasClass('pjCWBtnDisabled'))
				{
					self.$sectionCallBack.toggleClass('sectionCallBackStepOne');
				}
			}).on('click.cm', '.btnFormRemove', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				if(!pjQ.$(this).hasClass('pjCWBtnDisabled'))
				{
					self.$sectionCallBack.removeClass('sectionCallBackStepOne');
				}
			}).on('click.cm', '.btnSectionRemove', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				self.$sectionCallBack.addClass('sectionCallBackHidden');
			}).on("focusin.cm", ".pjCwDateTimePicker", function (e) {
				var coeff = 1000 * 60 * 15;
				var date = new Date(); 
				var rounded = new Date(Math.round(date.getTime() / coeff) * coeff);
				var $this = pjQ.$(this),
					custom = {},
					o = {
						firstDay: $this.attr("data-fday"),
						dateFormat: $this.attr("data-dformat"),
						timeFormat: $this.attr("data-tformat"),
						dayNames: ($this.data("day")).split(","),
					    monthNames: ($this.data("months")).split(","),
					    monthNamesShort: ($this.data("shortmonths")).split(","),
					    dayNamesMin: ($this.data("daymin")).split(","),
					    timeText: $this.attr("data-timeText"),
					    hourText: $this.attr("data-hourText"),
					    minuteText: $this.attr("data-minuteText"),
					    currentText: $this.attr("data-currentText"),
					    closeText: $this.attr("data-closeText"),
						stepMinute: 15,
						minDateTime: rounded,
						beforeShow: function(input, inst) {
							pjQ.$('#ui-datepicker-div').addClass("pjCpjQueryUI");
						},
						onClose: function (dateTimeText){
							$this.valid();
						}
				};
				pjQ.$(this).datetimepicker(pjQ.$.extend(o, custom));
			});
			
			pjQ.$(window).on("loadForm", this.container, function (e) {
				self.loadForm.call(self);
			});
			
			if (window.location.hash.length === 0) {
				this.loadForm.call(this);
			} else {
				onHashChange.call(null);
			}
		},
		
		loadForm: function () {
			var self = this,
				index = this.opts.index,
				params = 	{
								"theme": this.opts.theme,
								"index": this.opts.index
							};
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionForm"].join(""), params).done(function (data) {
				self.$container.html(data);
				self.$sectionCallBack = self.$container.find('.sectionCallBack');
				
				if (validate) 
				{
					var $form = pjQ.$('#frmRequestCallBack_'+ self.opts.index);
					$form.validate({
						rules: {
							"captcha": {
								remote: self.opts.folder + "index.php?controller=pjFront&action=pjActionCheckCaptcha"
							}
						},
						errorPlacement: function (error, element) {
							error.insertAfter(element.parent());
						},
						onkeyup: false,
						onfocusout: false,
						errorClass: "err",
						wrapper: "em",
						ignor: "",
						submitHandler: function (form) {
							self.disableButtons.call(self);
							
							pjQ.$.post([self.opts.folder, "index.php?controller=pjFront&action=pjActionSave"].join(""), $form.serialize()).done(function (data) {
								if(data.code == '200')
								{
									self.$sectionCallBack.removeClass('sectionCallBackStepOne').addClass('sectionCallBackStepTwo');
									
									var timeoutValue = 5;
									setTimeout(function() {
										self.$sectionCallBack.addClass('sectionCallBackHidden');
									}, timeoutValue*1000);

								}
								self.enableButtons.call(self);
							}).fail(function () {
								self.enableButtons.call(self);
							});
							
							return false;
						}
					});
				}
				
			}).fail(function () {
				self.enableButtons.call(self);
			});
		}
	};
	
	window.CallbackWidget = CallbackWidget;	
})(window);