
jQuery.fn.femanagerValidation = function() {
	var element = $(this);
	var requestCallback;
	var submitFormAllowed = false;
	if (element.find('*[data-validation]').length == 0) {
		submitFormAllowed = true;
	}

	/**
	 * AJAX queue function
	 */
	var MyRequestsCompleted = (function() {
		var numRequestToComplete,
			requestsCompleted,
			callBacks,
			singleCallBack;

		return function(options) {
			if (!options) options = {};

			numRequestToComplete = options.numRequest || 0;
			requestsCompleted = options.requestsCompleted || 0;
			element = options.element || 0;
			callBacks = [];
			var fireCallbacks = function() {
				$('body').css('cursor', 'default');
				submitForm(element); // submit form
				for (var i = 0; i < callBacks.length; i++) callBacks[i]();
			};
			if (options.singleCallback) callBacks.push(options.singleCallback);

			this.addCallbackToQueue = function(isComplete, callback) {
				if (isComplete) requestsCompleted++;
				if (callback) callBacks.push(callback);
				if (requestsCompleted == numRequestToComplete) fireCallbacks();
			};
			this.requestComplete = function(isComplete) {
				if (isComplete) requestsCompleted++;
				if (requestsCompleted == numRequestToComplete) fireCallbacks();
			};
			this.setCallback = function(callback) {
				callBacks.push(callBack);
			};
		};
	})();

	// on field blur
	$('*[data-validation]').blur(function() {
		validateField($(this), false); // validate this field only
	});

	// form submit
	element.submit(function(e) {
		$('body').css('cursor', 'wait');
		if (!submitFormAllowed) {
			e.preventDefault();
			validateAllFields($(this));
		}
	});

	/**
	 * Validate every field in form
	 *
	 * @param object element		Form object
	 * @return void
	 */
	function validateAllFields(element) {
		// Store number of ajax requests for queue function
		requestCallback = new MyRequestsCompleted({
			numRequest: element.find('*[data-validation]').length,
			element: element
		});

		// one loop for every field to validate
		element.find('*[data-validation]').each(function() {
			validateField($(this), true);
		});
	}

	/**
	 * Validate single filed
	 *
	 * @param object element		Field object
	 * @return void
	 */
	function validateField(element, countForSubmit) {
		var user = element.closest('form').find('div:first').find('input[name="tx_femanager_pi1[user][__identity]"]').val();
		var url = Femanager.getBaseUrl() + 'index.php' + '?eID=' + 'femanagerValidate';
		var validations = getValidations(element);
		var elementValue = element.val();
		if ((element.prop('type') == 'checkbox') && (element.prop('checked') == false)) {
			elementValue = '';
		}
		var additionalValue = '';
		if (indexOfArray(validations, 'sameAs')) { // search for "sameAs(password)"
			var validationSameAs = indexOfArray(validations, 'sameAs');
			var fieldToCompare = getStringInBrackets(validationSameAs);
			var fieldToCompareObject = $('input[name="tx_femanager_pi1[user][' + fieldToCompare + ']"]');
			additionalValue = fieldToCompareObject.val();
			if ((fieldToCompareObject.prop('type') == 'checkbox') && (fieldToCompareObject.prop('checked') == false)) {
				additionalValue = '';
			}
		}

		$.ajax({
			url: url,
			data: {
				'tx_femanager_pi1[validation]': element.data('validation'),
				'tx_femanager_pi1[value]': elementValue,
				'tx_femanager_pi1[field]': getFieldName(element),
				'tx_femanager_pi1[user]': (user !== undefined ? user : ''),
				'tx_femanager_pi1[additionalValue]=': (additionalValue ? additionalValue : ''),
				'storagePid': $('#femanagerStoragePid').val(),
				'L': $('#femanagerLanguage').val(),
				'id': $('#femanagerPid').val()
			},
			type: 'POST',
			cache: false,
			success: function(data) { // return values
				if (countForSubmit) {
					requestCallback.addCallbackToQueue(true);
				}
				if (data) {
					try {
						var json = $.parseJSON(data);
						if (!json.validate) {
							writeErrorMessage(element, json.message)
						} else {
							cleanErrorMessage(element);
						}
					} catch(e) {
						element.before(data)
					}

				}
			},
			error: function() {
				logAjaxError();
			}
		});
	}

	/**
	 * Read fieldname
	 * 		get "email" out of "tx_femanager_pi1[user][email]"
	 * 		get "passwort_repeat" out of "tx_femanager_pi1[password_repeat]"
	 *
	 * @param element
	 * @return string
	 */
	function getFieldName(element) {
		var nameParts = element.prop('name').split('[');
		var name = nameParts[nameParts.length-1].replace(']', '');
		return name;
	}

	/**
	 * Write errormessage next to the field
	 *
	 * @param element				Field
	 */
	function writeErrorMessage(element, message) {
		cleanErrorMessage(element); // remove all errors to this field at the beginning
		var errorMessage = $('.femanager_validation_container').html().replace('{messages}', message); // get html for error
		element.before(errorMessage); // add message
		element.closest('.control-group').addClass('error');
		element.addClass('error');
	}

	/**
	 * Remove one error message
	 *
	 * @param element
	 */
	function cleanErrorMessage(element) {
		element.closest('.control-group').removeClass('error');
		element.siblings('.alert').remove(); // hide message to this field
		element.removeClass('error');
	}

	/**
	 * Check if there are errors and submit form
	 *
	 * @param element
	 */
	function submitForm(element) {
		// submit form if there are no errors
		if (element.find('.error').length == 0) {
			submitFormAllowed = true;
			element.submit();
		} else {
			$('html,body').animate({
				scrollTop: element.find('.error:first').offset().top
			});
		}
	}

	/**
	 * Check if part of a value exist in an array
	 *
	 * @param array
	 * @return string found value
	 */
	function indexOfArray(array, string) {
		for (var i=0; i < array.length; i++) {
			if (array[i].indexOf(string) !== -1) {
				return array[i];
			}
		}
		return '';
	}

	/**
	 * Get validation methods of a field
	 * 		data-validation="required,max(5)" => array
	 * 			required,
	 * 			max(5)
	 *
	 * @param element
	 * @return array
	 */
	function getValidations(element) {
		return element.data('validation').split(',');
	}

	/**
	 * Get string in brackets
	 * 		lala(lulu) => lulu
	 *
	 * @param string
	 * @return string
	 */
	function getStringInBrackets(string) {
		var result = '';
		if (string.indexOf('(') !== -1) {
			var parts = string.split('(');
			result = parts[1].substr(0, parts[1].length - 1);
		}
		return result;
	}

	/**
	 * Log Error in Console
	 *
	 * @return void
	 */
	function logAjaxError() {
		if (typeof console === 'object') {
			console.log('Error: The called url is not available - if you use TYPO3 in a subfolder, please use config.baseURL in TypoScript');
		}
	}
};

jQuery(document).ready(function($) {
	// javascript validation
	$('.feManagerValidation').femanagerValidation();

	// ajax uploader
	var images = createUploader();
	// Store initially present filenames from hidden #image input in data structure
	if ($('#femanager_field_image').length > 0) {
		$.each($('#femanager_field_image').val().split(','), function(index, filename) {
			if(filename.trim().length > 0) {
				images.addImageName(filename, filename)
			}
		});
	}

	// delete image
	$('#femanager_field_preview-image').find('.qq-upload-delete').click(function(e) {
		e.preventDefault();

		var item = $(e.target).parent();
		// Remove filename from hidden #image input
		images.deleteImageName(item.find('.qq-upload-file').text());

		item.fadeOut('', function() {
			$(this).remove();
		});
	});

	// confirmation
	$('*[data-confirm]').click(function(e) {
		var message = $(this).data('confirm');
		if (!confirm(message)) {
			e.preventDefault();
		}
	});
});

/**
 * Create Fileuploader
 *
 * @return object
 */
function createUploader() {
	if ($('#femanager_field_fine-uploader').length == 0) {
		return;
	}

	var imageNameHandler = {
		// Data structure to store image names for Femanager
		imageNames: {},
		// Join image names in data structure to be stored in hidden #image input
		getImageNames: function () {
			return $.map(this.imageNames, function(item) { return item; } ).join(',');
		},
		// Add filename to data structure and hidden #image input
		addImageName: function(id, filename) {
			this.imageNames[id] = filename;
			$('#femanager_field_image').val(this.getImageNames());
		},
		// Remove filename from data structure and hidden #image input
		deleteImageName: function (idToDelete) {
			delete this.imageNames[idToDelete];
			$('#femanager_field_image').val(this.getImageNames());
		}
	};
	var uploader = new qq.FineUploader({

		element: document.getElementById('femanager_field_fine-uploader'),
		request: {
			endpoint: Femanager.getBaseUrl() + 'index.php?eID=femanagerFileUpload&id=' + $('#femanagerPid').val(),
			customHeaders: {
				Accept: 'application/json'
			}
		},
		multiple: true,
		template: $('.image_container_template:first').html(),
		fileTemplate: '<li>' +
			'<div class="qq-progress-bar"></div>' +
			'<span class="qq-upload-spinner"></span>' +
			'<span class="qq-upload-finished"></span>' +
			'<span class="qq-upload-file"></span>' +
			'<span class="qq-upload-size"></span>' +
			'<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
			'<a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
			'<a class="qq-upload-delete icon-trash" href="#">{deleteButtonText}</a>' +
			'<span class="qq-upload-status-text">{statusText}</span>' +
			'</li>',
		deleteFile: {
			enabled: true,
			forceConfirm: true,
			endpoint: Femanager.getBaseUrl() + 'index.php?eID=femanagerFileDelete&id=' + $('#femanagerPid').val() // TODO delete file on server
		},
		classes: {
			success: 'alert alert-success',
			fail: 'alert alert-error'
		},
		validation: {
			allowedExtensions: getValueFromField('#uploadFileExtension', 'jpeg, jpg, gif, png, bmp', 'array'), // allowed file extensions
			sizeLimit: getValueFromField('#uploadSize', 25000000, 'int'), // in bytes
			itemLimit: getValueFromField('#uploadAmount', 1, 'int') // limit number of uploads
		},
		callbacks: {
			onComplete: function(id, fileName, responseJSON) {
				if (responseJSON.success) {
					// show preview image
					var image = $('<img />')
						.addClass('fileupload_image')
						.prop('src', $('#uploadFolder').val() + '/' + responseJSON.uploadName)
						.prop('alt', responseJSON.uploadName)

					image.appendTo(this.getItemByFileId(id));

					// add filename to Femanager data structure
					imageNameHandler.addImageName(id, responseJSON.uploadName);
				}
			},
			onDeleteComplete: function(id, xhr, isError) {
				// Remove filename from Femanager data structure
				imageNameHandler.deleteImageName(id);
			}
		}
	});
	return imageNameHandler;
}

window.Femanager = {};

/**
 * Get value from a hidden field
 *
 * @param selector string
 * @param fallback mixed
 * @param mode string ("int", "array")
 * @returns {*}
 */
function getValueFromField(selector, fallback, mode) {
	var value = fallback;
	if ($(selector).length) {
		value = $(selector).val();
	}
	if (mode !== undefined) {
		if (mode === 'int') {
			value = parseInt(value);
		} else if (mode === 'array') {
			value = value.toString();
			value = value.replace(/[\s,]+/g, ','); // replace " , " to ","
			value = value.split(',');
		}
	}
	return value;
}

/**
 * Return BaseUrl as prefix
 *
 * @return string Base Url
 */
window.Femanager.getBaseUrl = function() {
	var baseurl;
	if (jQuery('base').length > 0) {
		baseurl = jQuery('base').prop('href');
	} else if (window.location.hostname.indexOf('localhost') !== -1) {
		baseurl = '';
	} else {
		var port = '';
		if (window.location.port.length > 0) {
			port = ':' + window.location.port;
		}
		if (window.location.protocol !== "https:") {
			baseurl = 'http://' + window.location.hostname + port + '/';
		} else {
			baseurl = 'https://' + window.location.hostname + port + '/';
		}
	}
	return baseurl;
};

!function(e){"use strict";var t={i18n:{ru:{months:["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],dayOfWeek:["Вск","Пн","Вт","Ср","Чт","Пт","Сб"]},en:{months:["January","February","March","April","May","June","July","August","September","October","November","December"],dayOfWeek:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},de:{months:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],dayOfWeek:["So","Mo","Di","Mi","Do","Fr","Sa"]},nl:{months:["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"],dayOfWeek:["zo","ma","di","wo","do","vr","za"]},tr:{months:["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"],dayOfWeek:["Paz","Pts","Sal","Çar","Per","Cum","Cts"]},fr:{months:["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"],dayOfWeek:["Dim","Lun","Mar","Mer","Jeu","Ven","Sam"]},es:{months:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],dayOfWeek:["Dom","Lun","Mar","Mié","Jue","Vie","Sáb"]},th:{months:["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"],dayOfWeek:["อา.","จ.","อ.","พ.","พฤ.","ศ.","ส."]},pl:{months:["styczeń","luty","marzec","kwiecień","maj","czerwiec","lipiec","sierpień","wrzesień","październik","listopad","grudzień"],dayOfWeek:["nd","pn","wt","śr","cz","pt","sb"]},pt:{months:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],dayOfWeek:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"]},ch:{months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],dayOfWeek:["日","一","二","三","四","五","六"]},se:{months:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],dayOfWeek:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"]},kr:{months:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],dayOfWeek:["일","월","화","수","목","금","토"]},it:{months:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],dayOfWeek:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"]},da:{months:["January","Februar","Marts","April","Maj","Juni","July","August","September","Oktober","November","December"],dayOfWeek:["Søn","Man","Tir","ons","Tor","Fre","lør"]},ja:{months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayOfWeek:["日","月","火","水","木","金","土"]},vi:{months:["Tháng 1","Tháng 2","Tháng 3","Tháng 4","Tháng 5","Tháng 6","Tháng 7","Tháng 8","Tháng 9","Tháng 10","Tháng 11","Tháng 12"],dayOfWeek:["CN","T2","T3","T4","T5","T6","T7"]}},value:"",lang:"en",format:"Y/m/d H:i",formatTime:"H:i",formatDate:"Y/m/d",startDate:!1,step:60,closeOnDateSelect:!1,closeOnWithoutClick:!0,timepicker:!0,datepicker:!0,minDate:!1,maxDate:!1,minTime:!1,maxTime:!1,allowTimes:[],opened:!1,initTime:!0,inline:!1,onSelectDate:function(){},onSelectTime:function(){},onChangeMonth:function(){},onChangeDateTime:function(){},onShow:function(){},onClose:function(){},onGenerate:function(){},withoutCopyright:!0,inverseButton:!1,hours12:!1,next:"xdsoft_next",prev:"xdsoft_prev",dayOfWeekStart:0,timeHeightInTimePicker:25,timepickerScrollbar:!0,todayButton:!0,defaultSelect:!0,scrollMonth:!0,scrollTime:!0,scrollInput:!0,lazyInit:!1,mask:!1,validateOnBlur:!0,allowBlank:!0,yearStart:1950,yearEnd:2050,style:"",id:"",roundTime:"round",className:"",weekends:[],yearOffset:0};Array.prototype.indexOf||(Array.prototype.indexOf=function(e,t){for(var n=t||0,a=this.length;a>n;n++)if(this[n]===e)return n;return-1}),e.fn.xdsoftScroller=function(t){return this.each(function(){var n=e(this);if(!e(this).hasClass("xdsoft_scroller_box")){var a=function(e){var t={x:0,y:0};if("touchstart"==e.type||"touchmove"==e.type||"touchend"==e.type||"touchcancel"==e.type){var n=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0];t.x=n.pageX,t.y=n.pageY}else("mousedown"==e.type||"mouseup"==e.type||"mousemove"==e.type||"mouseover"==e.type||"mouseout"==e.type||"mouseenter"==e.type||"mouseleave"==e.type)&&(t.x=e.pageX,t.y=e.pageY);return t},r=0,o=n.children().eq(0),s=n[0].clientHeight,i=o[0].offsetHeight,d=e('<div class="xdsoft_scrollbar"></div>'),u=e('<div class="xdsoft_scroller"></div>'),c=100,l=!1;d.append(u),n.addClass("xdsoft_scroller_box").append(d),u.on("mousedown.xdsoft_scroller",function(a){s||n.trigger("resize_scroll.xdsoft_scroller",[t]);var o=a.pageY,i=parseInt(u.css("margin-top")),l=d[0].offsetHeight;e(document.body).addClass("xdsoft_noselect"),e([document.body,window]).on("mouseup.xdsoft_scroller",function f(){e([document.body,window]).off("mouseup.xdsoft_scroller",f).off("mousemove.xdsoft_scroller",r).removeClass("xdsoft_noselect")}),e(document.body).on("mousemove.xdsoft_scroller",r=function(e){var t=e.pageY-o+i;0>t&&(t=0),t+u[0].offsetHeight>l&&(t=l-u[0].offsetHeight),n.trigger("scroll_element.xdsoft_scroller",[c?t/c:0])})}),n.on("scroll_element.xdsoft_scroller",function(e,t){s||n.trigger("resize_scroll.xdsoft_scroller",[t,!0]),t=t>1?1:0>t||isNaN(t)?0:t,u.css("margin-top",c*t),o.css("marginTop",-parseInt((i-s)*t))}).on("resize_scroll.xdsoft_scroller",function(e,t,a){s=n[0].clientHeight,i=o[0].offsetHeight;var r=s/i,l=r*d[0].offsetHeight;r>1?u.hide():(u.show(),u.css("height",parseInt(l>10?l:10)),c=d[0].offsetHeight-u[0].offsetHeight,a!==!0&&n.trigger("scroll_element.xdsoft_scroller",[t?t:Math.abs(parseInt(o.css("marginTop")))/(i-s)]))}),n.mousewheel&&n.mousewheel(function(e,t){var a=Math.abs(parseInt(o.css("marginTop")));return n.trigger("scroll_element.xdsoft_scroller",[(a-20*t)/(i-s)]),e.stopPropagation(),!1}),n.on("touchstart",function(e){l=a(e)}),n.on("touchmove",function(e){if(l){var t=a(e),r=Math.abs(parseInt(o.css("marginTop")));n.trigger("scroll_element.xdsoft_scroller",[(r-(t.y-l.y))/(i-s)]),e.stopPropagation(),e.preventDefault()}}),n.on("touchend touchcancel",function(){l=!1})}n.trigger("resize_scroll.xdsoft_scroller",[t])})},e.fn.datetimepicker=function(n){var a=48,r=57,o=96,s=105,i=17,d=46,u=13,c=27,l=8,f=37,m=38,h=39,g=40,p=9,x=116,v=65,y=67,D=86,T=90,w=89,b=!1,_=e.isPlainObject(n)||!n?e.extend(!0,{},t,n):e.extend({},t),M=0,k=function(e){e.on("open.xdsoft focusin.xdsoft mousedown.xdsoft",function t(){e.is(":disabled")||e.is(":hidden")||!e.is(":visible")||e.data("xdsoft_datetimepicker")||(clearTimeout(M),M=setTimeout(function(){e.data("xdsoft_datetimepicker")||S(e),e.off("open.xdsoft focusin.xdsoft mousedown.xdsoft",t).trigger("open.xdsoft")},100))})},S=function(t){function n(){var e=_.value?_.value:t&&t.val&&t.val()?t.val():"";return e&&z.isValidDate(e=Date.parseDate(e,_.format))?M.data("changed",!0):e="",e||_.startDate===!1||(e=z.strToDateTime(_.startDate)),e?e:0}var M=e("<div "+(_.id?'id="'+_.id+'"':"")+" "+(_.style?'style="'+_.style+'"':"")+' class="xdsoft_datetimepicker xdsoft_noselect '+_.className+'"></div>'),k=e('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),S=e('<div class="xdsoft_datepicker active"></div>'),O=e('<div class="xdsoft_mounthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button><div class="xdsoft_label xdsoft_month"><span></span></div><div class="xdsoft_label xdsoft_year"><span></span></div><button type="button" class="xdsoft_next"></button></div>'),F=e('<div class="xdsoft_calendar"></div>'),I=e('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),C=I.find(".xdsoft_time_box").eq(0),H=e('<div class="xdsoft_time_variant"></div>'),Y=e('<div class="xdsoft_scrollbar"></div>'),P=(e('<div class="xdsoft_scroller"></div>'),e('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>')),A=e('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>');O.find(".xdsoft_month span").after(P),O.find(".xdsoft_year span").after(A),O.find(".xdsoft_month,.xdsoft_year").on("mousedown.xdsoft",function(t){O.find(".xdsoft_select").hide();var n=e(this).find(".xdsoft_select").eq(0),a=0,r=0;z.currentTime&&(a=z.currentTime[e(this).hasClass("xdsoft_month")?"getMonth":"getFullYear"]()),n.show();for(var o=n.find("div.xdsoft_option"),s=0;s<o.length&&o.eq(s).data("value")!=a;s++)r+=o[0].offsetHeight;return n.xdsoftScroller(r/(n.children()[0].offsetHeight-n[0].clientHeight)),t.stopPropagation(),!1}),O.find(".xdsoft_select").xdsoftScroller().on("mousedown.xdsoft",function(e){e.stopPropagation(),e.preventDefault()}).on("mousedown.xdsoft",".xdsoft_option",function(){z&&z.currentTime&&z.currentTime[e(this).parent().parent().hasClass("xdsoft_monthselect")?"setMonth":"setFullYear"](e(this).data("value")),e(this).parent().parent().hide(),M.trigger("xchange.xdsoft"),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,z.currentTime,M.data("input"))}),M.setOptions=function(n){if(_=e.extend(!0,{},_,n),n.allowTimes&&e.isArray(n.allowTimes)&&n.allowTimes.length&&(_.allowTimes=e.extend(!0,[],n.allowTimes)),n.weekends&&e.isArray(n.weekends)&&n.weekends.length&&(_.weekends=e.extend(!0,[],n.weekends)),!_.open&&!_.opened||_.inline||t.trigger("open.xdsoft"),_.inline&&(M.addClass("xdsoft_inline"),t.after(M).hide(),M.trigger("afterOpen.xdsoft")),_.inverseButton&&(_.next="xdsoft_prev",_.prev="xdsoft_next"),_.datepicker?S.addClass("active"):S.removeClass("active"),_.timepicker?I.addClass("active"):I.removeClass("active"),_.value&&(t&&t.val&&t.val(_.value),z.setCurrentTime(_.value)),_.dayOfWeekStart=isNaN(_.dayOfWeekStart)||parseInt(_.dayOfWeekStart)<0||parseInt(_.dayOfWeekStart)>6?0:parseInt(_.dayOfWeekStart),_.timepickerScrollbar||Y.hide(),_.minDate&&/^-(.*)$/.test(_.minDate)&&(_.minDate=z.strToDateTime(_.minDate).dateFormat(_.formatDate)),_.maxDate&&/^\+(.*)$/.test(_.maxDate)&&(_.maxDate=z.strToDateTime(_.maxDate).dateFormat(_.formatDate)),O.find(".xdsoft_today_button").css("visibility",_.todayButton?"visible":"hidden"),_.mask){var k=function(e){try{if(document.selection&&document.selection.createRange){var t=document.selection.createRange();return t.getBookmark().charCodeAt(2)-2}if(e.setSelectionRange)return e.selectionStart}catch(n){return 0}},F=function(e,t){var e="string"==typeof e||e instanceof String?document.getElementById(e):e;if(!e)return!1;if(e.createTextRange){var n=e.createTextRange();return n.collapse(!0),n.moveEnd(t),n.moveStart(t),n.select(),!0}return e.setSelectionRange?(e.setSelectionRange(t,t),!0):!1},C=function(e,t){var n=e.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g,"\\$1").replace(/_/g,"{digit+}").replace(/([0-9]{1})/g,"{digit$1}").replace(/\{digit([0-9]{1})\}/g,"[0-$1_]{1}").replace(/\{digit[\+]\}/g,"[0-9_]{1}");return RegExp(n).test(t)};switch(t.off("keydown.xdsoft"),!0){case _.mask===!0:_.mask=_.format.replace(/Y/g,"9999").replace(/F/g,"9999").replace(/m/g,"19").replace(/d/g,"39").replace(/H/g,"29").replace(/i/g,"59").replace(/s/g,"59");case"string"==e.type(_.mask):C(_.mask,t.val())||t.val(_.mask.replace(/[0-9]/g,"_")),t.on("keydown.xdsoft",function(n){var M=this.value,S=n.which;switch(!0){case S>=a&&r>=S||S>=o&&s>=S||S==l||S==d:var O=k(this),I=S!=l&&S!=d?String.fromCharCode(S>=o&&s>=S?S-a:S):"_";for(S!=l&&S!=d||!O||(O--,I="_");/[^0-9_]/.test(_.mask.substr(O,1))&&O<_.mask.length&&O>0;)O+=S==l||S==d?-1:1;if(M=M.substr(0,O)+I+M.substr(O+1),""==e.trim(M))M=_.mask.replace(/[0-9]/g,"_");else if(O==_.mask.length)break;for(O+=S==l||S==d?0:1;/[^0-9_]/.test(_.mask.substr(O,1))&&O<_.mask.length&&O>0;)O+=S==l||S==d?-1:1;C(_.mask,M)?(this.value=M,F(this,O)):""==e.trim(M)?this.value=_.mask.replace(/[0-9]/g,"_"):t.trigger("error_input.xdsoft");break;case!!~[v,y,D,T,w].indexOf(S)&&b:case!!~[c,m,g,f,h,x,i,p,u].indexOf(S):return!0}return n.preventDefault(),!1})}}_.validateOnBlur&&t.off("blur.xdsoft").on("blur.xdsoft",function(){_.allowBlank&&!e.trim(e(this).val()).length?(e(this).val(null),M.data("xdsoft_datetime").empty()):Date.parseDate(e(this).val(),_.format)?M.data("xdsoft_datetime").setCurrentTime(e(this).val()):(e(this).val(z.now().dateFormat(_.format)),M.data("xdsoft_datetime").setCurrentTime(e(this).val())),M.trigger("changedatetime.xdsoft")}),_.dayOfWeekStartPrev=0==_.dayOfWeekStart?6:_.dayOfWeekStart-1,M.trigger("xchange.xdsoft")},M.data("options",_).on("mousedown.xdsoft",function(e){return e.stopPropagation(),e.preventDefault(),A.hide(),P.hide(),!1});var N=I.find(".xdsoft_time_box");N.append(H),N.xdsoftScroller(),M.on("afterOpen.xdsoft",function(){N.xdsoftScroller()}),M.append(S).append(I),_.withoutCopyright!==!0&&M.append(k),S.append(O).append(F),e("body").append(M);var z=new function(){var e=this;e.now=function(){var e=new Date;return _.yearOffset&&e.setFullYear(e.getFullYear()+_.yearOffset),e},e.currentTime=this.now(),e.isValidDate=function(e){return"[object Date]"!==Object.prototype.toString.call(e)?!1:!isNaN(e.getTime())},e.setCurrentTime=function(t){e.currentTime="string"==typeof t?e.strToDateTime(t):e.isValidDate(t)?t:e.now(),M.trigger("xchange.xdsoft")},e.empty=function(){e.currentTime=null},e.getCurrentTime=function(){return e.currentTime},e.nextMonth=function(){var t=e.currentTime.getMonth()+1;return 12==t&&(e.currentTime.setFullYear(e.currentTime.getFullYear()+1),t=0),e.currentTime.setDate(Math.min(Date.daysInMonth[t],e.currentTime.getDate())),e.currentTime.setMonth(t),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,z.currentTime,M.data("input")),M.trigger("xchange.xdsoft"),t},e.prevMonth=function(){var t=e.currentTime.getMonth()-1;return-1==t&&(e.currentTime.setFullYear(e.currentTime.getFullYear()-1),t=11),e.currentTime.setDate(Math.min(Date.daysInMonth[t],e.currentTime.getDate())),e.currentTime.setMonth(t),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,z.currentTime,M.data("input")),M.trigger("xchange.xdsoft"),t},e.strToDateTime=function(t){var n,a,r=[];return(r=/^(\+|\-)(.*)$/.exec(t))&&(r[2]=Date.parseDate(r[2],_.formatDate))?(n=r[2].getTime()-1*r[2].getTimezoneOffset()*6e4,a=new Date(z.now().getTime()+parseInt(r[1]+"1")*n)):a=t?Date.parseDate(t,_.format):e.now(),e.isValidDate(a)||(a=e.now()),a},e.strtodate=function(t){var n=t?Date.parseDate(t,_.formatDate):e.now();return e.isValidDate(n)||(n=e.now()),n},e.strtotime=function(t){var n=t?Date.parseDate(t,_.formatTime):e.now();return e.isValidDate(n)||(n=e.now()),n},e.str=function(){return e.currentTime.dateFormat(_.format)}};O.find(".xdsoft_today_button").on("mousedown.xdsoft",function(){M.data("changed",!0),z.setCurrentTime(0),M.trigger("afterOpen.xdsoft")}).on("dblclick.xdsoft",function(){t.val(z.str()),M.trigger("close.xdsoft")}),O.find(".xdsoft_prev,.xdsoft_next").on("mousedown.xdsoft",function(){var t=e(this),n=0,a=!1;!function r(e){z.currentTime.getMonth();t.hasClass(_.next)?z.nextMonth():t.hasClass(_.prev)&&z.prevMonth(),!a&&(n=setTimeout(r,e?e:100))}(500),e([document.body,window]).on("mouseup.xdsoft",function o(){clearTimeout(n),a=!0,e([document.body,window]).off("mouseup.xdsoft",o)})}),I.find(".xdsoft_prev,.xdsoft_next").on("mousedown.xdsoft",function(){var t=e(this),n=0,a=!1,r=110;!function o(e){var s=C[0].clientHeight,i=H[0].offsetHeight,d=Math.abs(parseInt(H.css("marginTop")));t.hasClass(_.next)&&i-s-_.timeHeightInTimePicker>=d?H.css("marginTop","-"+(d+_.timeHeightInTimePicker)+"px"):t.hasClass(_.prev)&&d-_.timeHeightInTimePicker>=0&&H.css("marginTop","-"+(d-_.timeHeightInTimePicker)+"px"),C.trigger("scroll_element.xdsoft_scroller",[Math.abs(parseInt(H.css("marginTop"))/(i-s))]),r=r>10?10:r-10,!a&&(n=setTimeout(o,e?e:r))}(500),e([document.body,window]).on("mouseup.xdsoft",function s(){clearTimeout(n),a=!0,e([document.body,window]).off("mouseup.xdsoft",s)})});var W=0;M.on("xchange.xdsoft",function(t){clearTimeout(W),W=setTimeout(function(){for(var t="",n=new Date(z.currentTime.getFullYear(),z.currentTime.getMonth(),1,12,0,0),a=0,r=z.now();n.getDay()!=_.dayOfWeekStart;)n.setDate(n.getDate()-1);t+="<table><thead><tr>";for(var o=0;7>o;o++)t+="<th>"+_.i18n[_.lang].dayOfWeek[o+_.dayOfWeekStart>6?0:o+_.dayOfWeekStart]+"</th>";t+="</tr></thead>",t+="<tbody><tr>";var s=!1,i=!1;_.maxDate!==!1&&(s=z.strtodate(_.maxDate),s=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59,999)),_.minDate!==!1&&(i=z.strtodate(_.minDate),i=new Date(i.getFullYear(),i.getMonth(),i.getDate()));for(var d,u,c,l=[];a<z.currentTime.getDaysInMonth()||n.getDay()!=_.dayOfWeekStart||z.currentTime.getMonth()==n.getMonth();)l=[],a++,d=n.getDate(),u=n.getFullYear(),c=n.getMonth(),l.push("xdsoft_date"),(s!==!1&&n>s||i!==!1&&i>n)&&l.push("xdsoft_disabled"),z.currentTime.getMonth()!=c&&l.push("xdsoft_other_month"),(_.defaultSelect||M.data("changed"))&&z.currentTime.dateFormat("d.m.Y")==n.dateFormat("d.m.Y")&&l.push("xdsoft_current"),r.dateFormat("d.m.Y")==n.dateFormat("d.m.Y")&&l.push("xdsoft_today"),(0==n.getDay()||6==n.getDay()||~_.weekends.indexOf(n.dateFormat("d.m.Y")))&&l.push("xdsoft_weekend"),_.beforeShowDay&&"function"==typeof _.beforeShowDay&&l.push(_.beforeShowDay(n)),t+='<td data-date="'+d+'" data-month="'+c+'" data-year="'+u+'" class="xdsoft_date xdsoft_day_of_week'+n.getDay()+" "+l.join(" ")+'"><div>'+d+"</div></td>",n.getDay()==_.dayOfWeekStartPrev&&(t+="</tr>"),n.setDate(d+1);t+="</tbody></table>",F.html(t),O.find(".xdsoft_label span").eq(0).text(_.i18n[_.lang].months[z.currentTime.getMonth()]),O.find(".xdsoft_label span").eq(1).text(z.currentTime.getFullYear());var f="",m="",c="",h=function(e,t){var n=z.now();n.setHours(e),e=parseInt(n.getHours()),n.setMinutes(t),t=parseInt(n.getMinutes()),l=[],(_.maxTime!==!1&&z.strtotime(_.maxTime).getTime()<n.getTime()||_.minTime!==!1&&z.strtotime(_.minTime).getTime()>n.getTime())&&l.push("xdsoft_disabled"),(_.initTime||_.defaultSelect||M.data("changed"))&&parseInt(z.currentTime.getHours())==parseInt(e)&&(_.step>59||Math[_.roundTime](z.currentTime.getMinutes()/_.step)*_.step==parseInt(t))&&(_.defaultSelect||M.data("changed")?l.push("xdsoft_current"):_.initTime&&l.push("xdsoft_init_time")),parseInt(r.getHours())==parseInt(e)&&parseInt(r.getMinutes())==parseInt(t)&&l.push("xdsoft_today"),f+='<div class="xdsoft_time '+l.join(" ")+'" data-hour="'+e+'" data-minute="'+t+'">'+n.dateFormat(_.formatTime)+"</div>"};if(_.allowTimes&&e.isArray(_.allowTimes)&&_.allowTimes.length)for(var a=0;a<_.allowTimes.length;a++)m=z.strtotime(_.allowTimes[a]).getHours(),c=z.strtotime(_.allowTimes[a]).getMinutes(),h(m,c);else for(var a=0,o=0;a<(_.hours12?12:24);a++)for(o=0;60>o;o+=_.step)m=(10>a?"0":"")+a,c=(10>o?"0":"")+o,h(m,c);H.html(f);var g="",a=0;for(a=parseInt(_.yearStart,10)+_.yearOffset;a<=parseInt(_.yearEnd,10)+_.yearOffset;a++)g+='<div class="xdsoft_option '+(z.currentTime.getFullYear()==a?"xdsoft_current":"")+'" data-value="'+a+'">'+a+"</div>";for(A.children().eq(0).html(g),a=0,g="";11>=a;a++)g+='<div class="xdsoft_option '+(z.currentTime.getMonth()==a?"xdsoft_current":"")+'" data-value="'+a+'">'+_.i18n[_.lang].months[a]+"</div>";P.children().eq(0).html(g),e(this).trigger("generate.xdsoft")},10),t.stopPropagation()}).on("afterOpen.xdsoft",function(){if(_.timepicker){var e;if(H.find(".xdsoft_current").length?e=".xdsoft_current":H.find(".xdsoft_init_time").length&&(e=".xdsoft_init_time"),e){var t=C[0].clientHeight,n=H[0].offsetHeight,a=H.find(e).index()*_.timeHeightInTimePicker+1;a>n-t&&(a=n-t),H.css("marginTop","-"+parseInt(a)+"px"),C.trigger("scroll_element.xdsoft_scroller",[parseInt(a)/(n-t)])}}});var J=0;F.on("click.xdsoft","td",function(n){n.stopPropagation(),J++;var a=e(this),r=z.currentTime;return a.hasClass("xdsoft_disabled")?!1:(r.setDate(a.data("date")),r.setMonth(a.data("month")),r.setFullYear(a.data("year")),M.trigger("select.xdsoft",[r]),t.val(z.str()),(J>1||_.closeOnDateSelect===!0||0===_.closeOnDateSelect&&!_.timepicker)&&!_.inline&&M.trigger("close.xdsoft"),_.onSelectDate&&_.onSelectDate.call&&_.onSelectDate.call(M,z.currentTime,M.data("input")),M.data("changed",!0),M.trigger("xchange.xdsoft"),M.trigger("changedatetime.xdsoft"),void setTimeout(function(){J=0},200))}),H.on("click.xdsoft","div",function(t){t.stopPropagation();var n=e(this),a=z.currentTime;return n.hasClass("xdsoft_disabled")?!1:(a.setHours(n.data("hour")),a.setMinutes(n.data("minute")),M.trigger("select.xdsoft",[a]),M.data("input").val(z.str()),!_.inline&&M.trigger("close.xdsoft"),_.onSelectTime&&_.onSelectTime.call&&_.onSelectTime.call(M,z.currentTime,M.data("input")),M.data("changed",!0),M.trigger("xchange.xdsoft"),void M.trigger("changedatetime.xdsoft"))}),M.mousewheel&&S.mousewheel(function(e,t){return _.scrollMonth?(0>t?z.nextMonth():z.prevMonth(),!1):!0}),M.mousewheel&&C.unmousewheel().mousewheel(function(e,t){if(!_.scrollTime)return!0;var n=C[0].clientHeight,a=H[0].offsetHeight,r=Math.abs(parseInt(H.css("marginTop"))),o=!0;return 0>t&&a-n-_.timeHeightInTimePicker>=r?(H.css("marginTop","-"+(r+_.timeHeightInTimePicker)+"px"),o=!1):t>0&&r-_.timeHeightInTimePicker>=0&&(H.css("marginTop","-"+(r-_.timeHeightInTimePicker)+"px"),o=!1),C.trigger("scroll_element.xdsoft_scroller",[Math.abs(parseInt(H.css("marginTop"))/(a-n))]),e.stopPropagation(),o}),M.on("changedatetime.xdsoft",function(){if(_.onChangeDateTime&&_.onChangeDateTime.call){var e=M.data("input");_.onChangeDateTime.call(M,z.currentTime,e),e.trigger("change")}}).on("generate.xdsoft",function(){_.onGenerate&&_.onGenerate.call&&_.onGenerate.call(M,z.currentTime,M.data("input"))});var j=0;t.mousewheel&&t.mousewheel(function(e,n,a,r){return _.scrollInput?!_.datepicker&&_.timepicker?(j=H.find(".xdsoft_current").length?H.find(".xdsoft_current").eq(0).index():0,j+n>=0&&j+n<H.children().length&&(j+=n),H.children().eq(j).length&&H.children().eq(j).trigger("mousedown"),!1):_.datepicker&&!_.timepicker?(S.trigger(e,[n,a,r]),t.val&&t.val(z.str()),M.trigger("changedatetime.xdsoft"),!1):void 0:!0});var L=function(){var t=M.data("input").offset(),n=t.top+M.data("input")[0].offsetHeight-1,a=t.left;n+M[0].offsetHeight>e(window).height()+e(window).scrollTop()&&(n=t.top-M[0].offsetHeight+1),0>n&&(n=0),a+M[0].offsetWidth>e(window).width()&&(a=t.left-M[0].offsetWidth+M.data("input")[0].offsetWidth),M.css({left:a,top:n})};M.on("open.xdsoft",function(){var t=!0;_.onShow&&_.onShow.call&&(t=_.onShow.call(M,z.currentTime,M.data("input"))),t!==!1&&(M.show(),M.trigger("afterOpen.xdsoft"),L(),e(window).off("resize.xdsoft",L).on("resize.xdsoft",L),_.closeOnWithoutClick&&e([document.body,window]).on("mousedown.xdsoft",function n(){M.trigger("close.xdsoft"),e([document.body,window]).off("mousedown.xdsoft",n)}))}).on("close.xdsoft",function(e){var t=!0;_.onClose&&_.onClose.call&&(t=_.onClose.call(M,z.currentTime,M.data("input"))),t===!1||_.opened||_.inline||M.hide(),e.stopPropagation()}).data("input",t);var E=0;M.data("xdsoft_datetime",z),M.setOptions(_),z.setCurrentTime(n()),M.trigger("afterOpen.xdsoft"),t.data("xdsoft_datetimepicker",M).on("open.xdsoft focusin.xdsoft mousedown.xdsoft",function(){t.is(":disabled")||t.is(":hidden")||!t.is(":visible")||(clearTimeout(E),E=setTimeout(function(){t.is(":disabled")||t.is(":hidden")||!t.is(":visible")||(z.setCurrentTime(n()),M.trigger("open.xdsoft"))},100))}).on("keydown.xdsoft",function(t){var n=(this.value,t.which);switch(!0){case!!~[u].indexOf(n):var a=e("input:visible,textarea:visible");return M.trigger("close.xdsoft"),a.eq(a.index(this)+1).focus(),!1;case!!~[p].indexOf(n):return M.trigger("close.xdsoft"),!0}})},O=function(t){var n=t.data("xdsoft_datetimepicker");n&&(n.data("xdsoft_datetime",null),n.remove(),t.data("xdsoft_datetimepicker",null).off("open.xdsoft focusin.xdsoft focusout.xdsoft mousedown.xdsoft blur.xdsoft keydown.xdsoft"),e(window).off("resize.xdsoft"),e([window,document.body]).off("mousedown.xdsoft"),t.unmousewheel&&t.unmousewheel())};return e(document).off("keydown.xdsoftctrl keyup.xdsoftctrl").on("keydown.xdsoftctrl",function(e){e.keyCode==i&&(b=!0)}).on("keyup.xdsoftctrl",function(e){e.keyCode==i&&(b=!1)}),this.each(function(){var t;if(t=e(this).data("xdsoft_datetimepicker")){if("string"===e.type(n))switch(n){case"show":e(this).select().focus(),t.trigger("open.xdsoft");break;case"hide":t.trigger("close.xdsoft");break;case"destroy":O(e(this));break;case"reset":this.value=this.defaultValue,this.value&&t.data("xdsoft_datetime").isValidDate(Date.parseDate(this.value,_.format))||t.data("changed",!1),t.data("xdsoft_datetime").setCurrentTime(this.value)}else t.setOptions(n);return 0}"string"!==e.type(n)&&(!_.lazyInit||_.open||_.inline?S(e(this)):k(e(this)))})}}(jQuery),Date.parseFunctions={count:0},Date.parseRegexes=[],Date.formatFunctions={count:0},Date.prototype.dateFormat=function(e){if("unixtime"==e)return parseInt(this.getTime()/1e3);null==Date.formatFunctions[e]&&Date.createNewFormat(e);var t=Date.formatFunctions[e];return this[t]()},Date.createNewFormat=function(format){var funcName="format"+Date.formatFunctions.count++;Date.formatFunctions[format]=funcName;for(var code="Date.prototype."+funcName+" = function() {return ",special=!1,ch="",i=0;i<format.length;++i)ch=format.charAt(i),special||"\\"!=ch?special?(special=!1,code+="'"+String.escape(ch)+"' + "):code+=Date.getFormatCode(ch):special=!0;eval(code.substring(0,code.length-3)+";}")},Date.getFormatCode=function(e){switch(e){case"d":return"String.leftPad(this.getDate(), 2, '0') + ";case"D":return"Date.dayNames[this.getDay()].substring(0, 3) + ";case"j":return"this.getDate() + ";case"l":return"Date.dayNames[this.getDay()] + ";case"S":return"this.getSuffix() + ";case"w":return"this.getDay() + ";case"z":return"this.getDayOfYear() + ";case"W":return"this.getWeekOfYear() + ";case"F":return"Date.monthNames[this.getMonth()] + ";case"m":return"String.leftPad(this.getMonth() + 1, 2, '0') + ";case"M":return"Date.monthNames[this.getMonth()].substring(0, 3) + ";case"n":return"(this.getMonth() + 1) + ";case"t":return"this.getDaysInMonth() + ";case"L":return"(this.isLeapYear() ? 1 : 0) + ";case"Y":return"this.getFullYear() + ";case"y":return"('' + this.getFullYear()).substring(2, 4) + ";case"a":return"(this.getHours() < 12 ? 'am' : 'pm') + ";case"A":return"(this.getHours() < 12 ? 'AM' : 'PM') + ";case"g":return"((this.getHours() %12) ? this.getHours() % 12 : 12) + ";case"G":return"this.getHours() + ";case"h":return"String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + ";case"H":return"String.leftPad(this.getHours(), 2, '0') + ";case"i":return"String.leftPad(this.getMinutes(), 2, '0') + ";case"s":return"String.leftPad(this.getSeconds(), 2, '0') + ";case"O":return"this.getGMTOffset() + ";case"T":return"this.getTimezone() + ";case"Z":return"(this.getTimezoneOffset() * -60) + ";default:return"'"+String.escape(e)+"' + "}},Date.parseDate=function(e,t){if("unixtime"==t)return new Date(isNaN(parseInt(e))?0:1e3*parseInt(e));null==Date.parseFunctions[t]&&Date.createParser(t);var n=Date.parseFunctions[t];return Date[n](e)},Date.createParser=function(format){var funcName="parse"+Date.parseFunctions.count++,regexNum=Date.parseRegexes.length,currentGroup=1;Date.parseFunctions[format]=funcName;for(var code="Date."+funcName+" = function(input) {\nvar y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, z = -1;\nvar d = new Date();\ny = d.getFullYear();\nm = d.getMonth();\nd = d.getDate();\nvar results = input.match(Date.parseRegexes["+regexNum+"]);\nif (results && results.length > 0) {",regex="",special=!1,ch="",i=0;i<format.length;++i)ch=format.charAt(i),special||"\\"!=ch?special?(special=!1,regex+=String.escape(ch)):(obj=Date.formatCodeToRegex(ch,currentGroup),currentGroup+=obj.g,regex+=obj.s,obj.g&&obj.c&&(code+=obj.c)):special=!0;code+="if (y > 0 && z > 0){\nvar doyDate = new Date(y,0);\ndoyDate.setDate(z);\nm = doyDate.getMonth();\nd = doyDate.getDate();\n}",code+="if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n{return new Date(y, m, d, h, i, s);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n{return new Date(y, m, d, h, i);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0)\n{return new Date(y, m, d, h);}\nelse if (y > 0 && m >= 0 && d > 0)\n{return new Date(y, m, d);}\nelse if (y > 0 && m >= 0)\n{return new Date(y, m);}\nelse if (y > 0)\n{return new Date(y);}\n}return null;}",Date.parseRegexes[regexNum]=new RegExp("^"+regex+"$"),eval(code)},Date.formatCodeToRegex=function(e,t){switch(e){case"D":return{g:0,c:null,s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};case"j":case"d":return{g:1,c:"d = parseInt(results["+t+"], 10);\n",s:"(\\d{1,2})"};case"l":return{g:0,c:null,s:"(?:"+Date.dayNames.join("|")+")"};case"S":return{g:0,c:null,s:"(?:st|nd|rd|th)"};case"w":return{g:0,c:null,s:"\\d"};case"z":return{g:1,c:"z = parseInt(results["+t+"], 10);\n",s:"(\\d{1,3})"};case"W":return{g:0,c:null,s:"(?:\\d{2})"};case"F":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+t+"].substring(0, 3)], 10);\n",s:"("+Date.monthNames.join("|")+")"};case"M":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+t+"]], 10);\n",s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};case"n":case"m":return{g:1,c:"m = parseInt(results["+t+"], 10) - 1;\n",s:"(\\d{1,2})"};case"t":return{g:0,c:null,s:"\\d{1,2}"};case"L":return{g:0,c:null,s:"(?:1|0)"};case"Y":return{g:1,c:"y = parseInt(results["+t+"], 10);\n",s:"(\\d{4})"};case"y":return{g:1,c:"var ty = parseInt(results["+t+"], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",s:"(\\d{1,2})"};case"a":return{g:1,c:"if (results["+t+"] == 'am') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(am|pm)"};case"A":return{g:1,c:"if (results["+t+"] == 'AM') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(AM|PM)"};case"g":case"G":case"h":case"H":return{g:1,c:"h = parseInt(results["+t+"], 10);\n",s:"(\\d{1,2})"};case"i":return{g:1,c:"i = parseInt(results["+t+"], 10);\n",s:"(\\d{2})"};case"s":return{g:1,c:"s = parseInt(results["+t+"], 10);\n",s:"(\\d{2})"};case"O":return{g:0,c:null,s:"[+-]\\d{4}"};case"T":return{g:0,c:null,s:"[A-Z]{3}"};case"Z":return{g:0,c:null,s:"[+-]\\d{1,5}"};default:return{g:0,c:null,s:String.escape(e)}}},Date.prototype.getTimezone=function(){return this.toString().replace(/^.*? ([A-Z]{3}) [0-9]{4}.*$/,"$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/,"$1$2$3")},Date.prototype.getGMTOffset=function(){return(this.getTimezoneOffset()>0?"-":"+")+String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset())/60),2,"0")+String.leftPad(Math.abs(this.getTimezoneOffset())%60,2,"0")},Date.prototype.getDayOfYear=function(){var e=0;Date.daysInMonth[1]=this.isLeapYear()?29:28;for(var t=0;t<this.getMonth();++t)e+=Date.daysInMonth[t];return e+this.getDate()},Date.prototype.getWeekOfYear=function(){var e=this.getDayOfYear()+(4-this.getDay()),t=new Date(this.getFullYear(),0,1),n=7-t.getDay()+4;return String.leftPad(Math.ceil((e-n)/7)+1,2,"0")},Date.prototype.isLeapYear=function(){var e=this.getFullYear();return 0==(3&e)&&(e%100||e%400==0&&e)},Date.prototype.getFirstDayOfMonth=function(){var e=(this.getDay()-(this.getDate()-1))%7;return 0>e?e+7:e},Date.prototype.getLastDayOfMonth=function(){var e=(this.getDay()+(Date.daysInMonth[this.getMonth()]-this.getDate()))%7;return 0>e?e+7:e},Date.prototype.getDaysInMonth=function(){return Date.daysInMonth[1]=this.isLeapYear()?29:28,Date.daysInMonth[this.getMonth()]},Date.prototype.getSuffix=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}},String.escape=function(e){return e.replace(/('|\\)/g,"\\$1")},String.leftPad=function(e,t,n){var a=new String(e);for(null==n&&(n=" ");a.length<t;)a=n+a;return a},Date.daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31],Date.monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"],Date.dayNames=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Date.y2kYear=50,Date.monthNumbers={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},Date.patterns={ISO8601LongPattern:"Y-m-d H:i:s",ISO8601ShortPattern:"Y-m-d",ShortDatePattern:"n/j/Y",LongDatePattern:"l, F d, Y",FullDateTimePattern:"l, F d, Y g:i:s A",MonthDayPattern:"F d",ShortTimePattern:"g:i A",LongTimePattern:"g:i:s A",SortableDateTimePattern:"Y-m-d\\TH:i:s",UniversalSortableDateTimePattern:"Y-m-d H:i:sO",YearMonthPattern:"F, Y"},function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof exports?module.exports=e:e(jQuery)
}(function(e){function t(t){var r,o=t||window.event,s=[].slice.call(arguments,1),i=0,d=0,u=0,c=0,l=0;return t=e.event.fix(o),t.type="mousewheel",o.wheelDelta&&(i=o.wheelDelta),o.detail&&(i=-1*o.detail),o.deltaY&&(u=-1*o.deltaY,i=u),o.deltaX&&(d=o.deltaX,i=-1*d),void 0!==o.wheelDeltaY&&(u=o.wheelDeltaY),void 0!==o.wheelDeltaX&&(d=-1*o.wheelDeltaX),c=Math.abs(i),(!n||n>c)&&(n=c),l=Math.max(Math.abs(u),Math.abs(d)),(!a||a>l)&&(a=l),r=i>0?"floor":"ceil",i=Math[r](i/n),d=Math[r](d/a),u=Math[r](u/a),s.unshift(t,i,d,u),(e.event.dispatch||e.event.handle).apply(this,s)}var n,a,r=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],o="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"];if(e.event.fixHooks)for(var s=r.length;s;)e.event.fixHooks[r[--s]]=e.event.mouseHooks;e.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var e=o.length;e;)this.addEventListener(o[--e],t,!1);else this.onmousewheel=t},teardown:function(){if(this.removeEventListener)for(var e=o.length;e;)this.removeEventListener(o[--e],t,!1);else this.onmousewheel=null}},e.fn.extend({mousewheel:function(e){return e?this.bind("mousewheel",e):this.trigger("mousewheel")},unmousewheel:function(e){return this.unbind("mousewheel",e)}})});
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)}(function(e){"undefined"==typeof e&&"undefined"!=typeof window.jQuery&&(e=window.jQuery);var t={attr:function(e,t,i){var n,s={},r=this.msieversion(),a=new RegExp("^"+t,"i");if("undefined"==typeof e||"undefined"==typeof e[0])return{};for(var o in e[0].attributes)if(n=e[0].attributes[o],"undefined"!=typeof n&&null!==n&&(!r||r>=8||n.specified)&&a.test(n.name)){if("undefined"!=typeof i&&new RegExp(i+"$","i").test(n.name))return!0;s[this.camelize(n.name.replace(t,""))]=this.deserializeValue(n.value)}return"undefined"==typeof i?s:!1},setAttr:function(e,t,i,n){e[0].setAttribute(this.dasherize(t+i),String(n))},get:function(e,t){for(var i=0,n=(t||"").split(".");this.isObject(e)||this.isArray(e);)if(e=e[n[i++]],i===n.length)return e;return void 0},hash:function(e){return String(Math.random()).substring(2,e?e+2:9)},isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},isObject:function(e){return e===Object(e)},deserializeValue:function(t){var i;try{return t?"true"==t||("false"==t?!1:"null"==t?null:isNaN(i=Number(t))?/^[\[\{]/.test(t)?e.parseJSON(t):t:i):t}catch(n){return t}},camelize:function(e){return e.replace(/-+(.)?/g,function(e,t){return t?t.toUpperCase():""})},dasherize:function(e){return e.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()},msieversion:function(){var e=window.navigator.userAgent,t=e.indexOf("MSIE ");return t>0||navigator.userAgent.match(/Trident.*rv\:11\./)?parseInt(e.substring(t+5,e.indexOf(".",t)),10):0}},i={namespace:"data-parsley-",inputs:"input, textarea, select",excluded:"input[type=button], input[type=submit], input[type=reset], input[type=hidden]",priorityEnabled:!0,uiEnabled:!0,validationThreshold:3,focus:"first",trigger:!1,errorClass:"parsley-error",successClass:"parsley-success",classHandler:function(){},errorsContainer:function(){},errorsWrapper:'<ul class="parsley-errors-list"></ul>',errorTemplate:"<li></li>"},n=function(){};n.prototype={asyncSupport:!1,actualizeOptions:function(){return this.options=this.OptionsFactory.get(this),this},validateThroughValidator:function(e,t,i){return window.ParsleyValidator.validate.apply(window.ParsleyValidator,[e,t,i])},subscribe:function(t,i){return e.listenTo(this,t.toLowerCase(),i),this},unsubscribe:function(t){return e.unsubscribeTo(this,t.toLowerCase()),this},reset:function(){if("ParsleyForm"!==this.__class__)return e.emit("parsley:field:reset",this);for(var t=0;t<this.fields.length;t++)e.emit("parsley:field:reset",this.fields[t]);e.emit("parsley:form:reset",this)},destroy:function(){if("ParsleyForm"!==this.__class__)return this.$element.removeData("Parsley"),this.$element.removeData("ParsleyFieldMultiple"),void e.emit("parsley:field:destroy",this);for(var t=0;t<this.fields.length;t++)this.fields[t].destroy();this.$element.removeData("Parsley"),e.emit("parsley:form:destroy",this)}};var s=function(){var e={},t=function(e){this.__class__="Validator",this.__version__="1.0.0",this.options=e||{},this.bindingKey=this.options.bindingKey||"_validatorjsConstraint"};t.prototype={constructor:t,validate:function(e,t,i){if("string"!=typeof e&&"object"!=typeof e)throw new Error("You must validate an object or a string");return"string"==typeof e||a(e)?this._validateString(e,t,i):this.isBinded(e)?this._validateBindedObject(e,t):this._validateObject(e,t,i)},bind:function(e,t){if("object"!=typeof e)throw new Error("Must bind a Constraint to an object");return e[this.bindingKey]=new i(t),this},unbind:function(e){return"undefined"==typeof e._validatorjsConstraint?this:(delete e[this.bindingKey],this)},isBinded:function(e){return"undefined"!=typeof e[this.bindingKey]},getBinded:function(e){return this.isBinded(e)?e[this.bindingKey]:null},_validateString:function(e,t,i){var r,o=[];a(t)||(t=[t]);for(var l=0;l<t.length;l++){if(!(t[l]instanceof s))throw new Error("You must give an Assert or an Asserts array to validate a string");r=t[l].check(e,i),r instanceof n&&o.push(r)}return o.length?o:!0},_validateObject:function(e,t,n){if("object"!=typeof t)throw new Error("You must give a constraint to validate an object");return t instanceof i?t.check(e,n):new i(t).check(e,n)},_validateBindedObject:function(e,t){return e[this.bindingKey].check(e,t)}},t.errorCode={must_be_a_string:"must_be_a_string",must_be_an_array:"must_be_an_array",must_be_a_number:"must_be_a_number",must_be_a_string_or_array:"must_be_a_string_or_array"};var i=function(e,t){if(this.__class__="Constraint",this.options=t||{},this.nodes={},e)try{this._bootstrap(e)}catch(i){throw new Error("Should give a valid mapping object to Constraint",i,e)}};i.prototype={constructor:i,check:function(e,t){var i,n={};for(var o in this.nodes){for(var l=!1,u=this.get(o),h=a(u)?u:[u],d=h.length-1;d>=0;d--)"Required"!==h[d].__class__||(l=h[d].requiresValidation(t));if(this.has(o,e)||this.options.strict||l)try{this.has(o,this.options.strict||l?e:void 0)||(new s).HaveProperty(o).validate(e),i=this._check(o,e[o],t),(a(i)&&i.length>0||!a(i)&&!r(i))&&(n[o]=i)}catch(f){n[o]=f}}return r(n)?!0:n},add:function(e,t){if(t instanceof s||a(t)&&t[0]instanceof s)return this.nodes[e]=t,this;if("object"==typeof t&&!a(t))return this.nodes[e]=t instanceof i?t:new i(t),this;throw new Error("Should give an Assert, an Asserts array, a Constraint",t)},has:function(e,t){return t="undefined"!=typeof t?t:this.nodes,"undefined"!=typeof t[e]},get:function(e,t){return this.has(e)?this.nodes[e]:t||null},remove:function(e){var t=[];for(var i in this.nodes)i!==e&&(t[i]=this.nodes[i]);return this.nodes=t,this},_bootstrap:function(e){if(e instanceof i)return this.nodes=e.nodes;for(var t in e)this.add(t,e[t])},_check:function(e,t,n){if(this.nodes[e]instanceof s)return this._checkAsserts(t,[this.nodes[e]],n);if(a(this.nodes[e]))return this._checkAsserts(t,this.nodes[e],n);if(this.nodes[e]instanceof i)return this.nodes[e].check(t,n);throw new Error("Invalid node",this.nodes[e])},_checkAsserts:function(e,t,i){for(var n,s=[],r=0;r<t.length;r++)n=t[r].check(e,i),"undefined"!=typeof n&&!0!==n&&s.push(n);return s}};var n=function(e,t,i){if(this.__class__="Violation",!(e instanceof s))throw new Error("Should give an assertion implementing the Assert interface");this.assert=e,this.value=t,"undefined"!=typeof i&&(this.violation=i)};n.prototype={show:function(){var e={assert:this.assert.__class__,value:this.value};return this.violation&&(e.violation=this.violation),e},__toString:function(){return"undefined"!=typeof this.violation&&(this.violation='", '+this.getViolation().constraint+" expected was "+this.getViolation().expected),this.assert.__class__+' assert failed for "'+this.value+this.violation||""},getViolation:function(){var e,t;for(e in this.violation)t=this.violation[e];return{constraint:e,expected:t}}};var s=function(e){this.__class__="Assert",this.__parentClass__=this.__class__,this.groups=[],"undefined"!=typeof e&&this.addGroup(e)};s.prototype={construct:s,requiresValidation:function(e){return e&&!this.hasGroup(e)?!1:!e&&this.hasGroups()?!1:!0},check:function(e,t){if(this.requiresValidation(t))try{return this.validate(e,t)}catch(i){return i}},hasGroup:function(e){return a(e)?this.hasOneOf(e):"Any"===e?!0:this.hasGroups()?-1!==this.groups.indexOf(e):"Default"===e},hasOneOf:function(e){for(var t=0;t<e.length;t++)if(this.hasGroup(e[t]))return!0;return!1},hasGroups:function(){return this.groups.length>0},addGroup:function(e){return a(e)?this.addGroups(e):(this.hasGroup(e)||this.groups.push(e),this)},removeGroup:function(e){for(var t=[],i=0;i<this.groups.length;i++)e!==this.groups[i]&&t.push(this.groups[i]);return this.groups=t,this},addGroups:function(e){for(var t=0;t<e.length;t++)this.addGroup(e[t]);return this},HaveProperty:function(e){return this.__class__="HaveProperty",this.node=e,this.validate=function(e){if("undefined"==typeof e[this.node])throw new n(this,e,{value:this.node});return!0},this},Blank:function(){return this.__class__="Blank",this.validate=function(e){if("string"!=typeof e)throw new n(this,e,{value:t.errorCode.must_be_a_string});if(""!==e.replace(/^\s+/g,"").replace(/\s+$/g,""))throw new n(this,e);return!0},this},Callback:function(e){if(this.__class__="Callback",this.arguments=Array.prototype.slice.call(arguments),1===this.arguments.length?this.arguments=[]:this.arguments.splice(0,1),"function"!=typeof e)throw new Error("Callback must be instanciated with a function");return this.fn=e,this.validate=function(e){var t=this.fn.apply(this,[e].concat(this.arguments));if(!0!==t)throw new n(this,e,{result:t});return!0},this},Choice:function(e){if(this.__class__="Choice",!a(e)&&"function"!=typeof e)throw new Error("Choice must be instanciated with an array or a function");return this.list=e,this.validate=function(e){for(var t="function"==typeof this.list?this.list():this.list,i=0;i<t.length;i++)if(e===t[i])return!0;throw new n(this,e,{choices:t})},this},Collection:function(e){return this.__class__="Collection",this.constraint="undefined"!=typeof e?e instanceof s?e:new i(e):!1,this.validate=function(e,i){var s,o=new t,l=0,u={},h=this.groups.length?this.groups:i;if(!a(e))throw new n(this,array,{value:t.errorCode.must_be_an_array});for(var d=0;d<e.length;d++)s=this.constraint?o.validate(e[d],this.constraint,h):o.validate(e[d],h),r(s)||(u[l]=s),l++;return r(u)?!0:u},this},Count:function(e){return this.__class__="Count",this.count=e,this.validate=function(e){if(!a(e))throw new n(this,e,{value:t.errorCode.must_be_an_array});var i="function"==typeof this.count?this.count(e):this.count;if(isNaN(Number(i)))throw new Error("Count must be a valid interger",i);if(i!==e.length)throw new n(this,e,{count:i});return!0},this},Email:function(){return this.__class__="Email",this.validate=function(e){var i=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;if("string"!=typeof e)throw new n(this,e,{value:t.errorCode.must_be_a_string});if(!i.test(e))throw new n(this,e);return!0},this},EqualTo:function(e){if(this.__class__="EqualTo","undefined"==typeof e)throw new Error("EqualTo must be instanciated with a value or a function");return this.reference=e,this.validate=function(e){var t="function"==typeof this.reference?this.reference(e):this.reference;if(t!==e)throw new n(this,e,{value:t});return!0},this},GreaterThan:function(e){if(this.__class__="GreaterThan","undefined"==typeof e)throw new Error("Should give a threshold value");return this.threshold=e,this.validate=function(e){if(""===e||isNaN(Number(e)))throw new n(this,e,{value:t.errorCode.must_be_a_number});if(this.threshold>=e)throw new n(this,e,{threshold:this.threshold});return!0},this},GreaterThanOrEqual:function(e){if(this.__class__="GreaterThanOrEqual","undefined"==typeof e)throw new Error("Should give a threshold value");return this.threshold=e,this.validate=function(e){if(""===e||isNaN(Number(e)))throw new n(this,e,{value:t.errorCode.must_be_a_number});if(this.threshold>e)throw new n(this,e,{threshold:this.threshold});return!0},this},InstanceOf:function(e){if(this.__class__="InstanceOf","undefined"==typeof e)throw new Error("InstanceOf must be instanciated with a value");return this.classRef=e,this.validate=function(e){if(1!=e instanceof this.classRef)throw new n(this,e,{classRef:this.classRef});return!0},this},Length:function(e){if(this.__class__="Length",!e.min&&!e.max)throw new Error("Lenth assert must be instanciated with a { min: x, max: y } object");return this.min=e.min,this.max=e.max,this.validate=function(e){if("string"!=typeof e&&!a(e))throw new n(this,e,{value:t.errorCode.must_be_a_string_or_array});if("undefined"!=typeof this.min&&this.min===this.max&&e.length!==this.min)throw new n(this,e,{min:this.min,max:this.max});if("undefined"!=typeof this.max&&e.length>this.max)throw new n(this,e,{max:this.max});if("undefined"!=typeof this.min&&e.length<this.min)throw new n(this,e,{min:this.min});return!0},this},LessThan:function(e){if(this.__class__="LessThan","undefined"==typeof e)throw new Error("Should give a threshold value");return this.threshold=e,this.validate=function(e){if(""===e||isNaN(Number(e)))throw new n(this,e,{value:t.errorCode.must_be_a_number});if(this.threshold<=e)throw new n(this,e,{threshold:this.threshold});return!0},this},LessThanOrEqual:function(e){if(this.__class__="LessThanOrEqual","undefined"==typeof e)throw new Error("Should give a threshold value");return this.threshold=e,this.validate=function(e){if(""===e||isNaN(Number(e)))throw new n(this,e,{value:t.errorCode.must_be_a_number});if(this.threshold<e)throw new n(this,e,{threshold:this.threshold});return!0},this},NotNull:function(){return this.__class__="NotNull",this.validate=function(e){if(null===e||"undefined"==typeof e)throw new n(this,e);return!0},this},NotBlank:function(){return this.__class__="NotBlank",this.validate=function(e){if("string"!=typeof e)throw new n(this,e,{value:t.errorCode.must_be_a_string});if(""===e.replace(/^\s+/g,"").replace(/\s+$/g,""))throw new n(this,e);return!0},this},Null:function(){return this.__class__="Null",this.validate=function(e){if(null!==e)throw new n(this,e);return!0},this},Range:function(e,t){if(this.__class__="Range","undefined"==typeof e||"undefined"==typeof t)throw new Error("Range assert expects min and max values");return this.min=e,this.max=t,this.validate=function(e){try{return"string"==typeof e&&isNaN(Number(e))||a(e)?(new s).Length({min:this.min,max:this.max}).validate(e):(new s).GreaterThanOrEqual(this.min).validate(e)&&(new s).LessThanOrEqual(this.max).validate(e),!0}catch(t){throw new n(this,e,t.violation)}return!0},this},Regexp:function(e,i){if(this.__class__="Regexp","undefined"==typeof e)throw new Error("You must give a regexp");return this.regexp=e,this.flag=i||"",this.validate=function(e){if("string"!=typeof e)throw new n(this,e,{value:t.errorCode.must_be_a_string});if(!new RegExp(this.regexp,this.flag).test(e))throw new n(this,e,{regexp:this.regexp,flag:this.flag});return!0},this},Required:function(){return this.__class__="Required",this.validate=function(e){if("undefined"==typeof e)throw new n(this,e);try{"string"==typeof e?(new s).NotNull().validate(e)&&(new s).NotBlank().validate(e):!0===a(e)&&(new s).Length({min:1}).validate(e)}catch(t){throw new n(this,e)}return!0},this},Unique:function(e){return this.__class__="Unique","object"==typeof e&&(this.key=e.key),this.validate=function(e){var i,s=[];if(!a(e))throw new n(this,e,{value:t.errorCode.must_be_an_array});for(var r=0;r<e.length;r++)if(i="object"==typeof e[r]?e[r][this.key]:e[r],"undefined"!=typeof i){if(-1!==s.indexOf(i))throw new n(this,e,{value:i});s.push(i)}return!0},this}},e.Assert=s,e.Validator=t,e.Violation=n,e.Constraint=i,Array.prototype.indexOf||(Array.prototype.indexOf=function(e){if(null===this)throw new TypeError;var t=Object(this),i=t.length>>>0;if(0===i)return-1;var n=0;if(arguments.length>1&&(n=Number(arguments[1]),n!=n?n=0:0!==n&&1/0!=n&&n!=-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=i)return-1;for(var s=n>=0?n:Math.max(i-Math.abs(n),0);i>s;s++)if(s in t&&t[s]===e)return s;return-1});var r=function(e){for(var t in e)return!1;return!0},a=function(e){return"[object Array]"===Object.prototype.toString.call(e)};return"function"==typeof define&&define.amd?define("vendors/validator.js/dist/validator",[],function(){return e}):"undefined"!=typeof module&&module.exports?module.exports=e:window["undefined"!=typeof validatorjs_ns?validatorjs_ns:"Validator"]=e,e}();s="undefined"!=typeof s?s:"undefined"!=typeof module?module.exports:null;var r=function(e,t){this.__class__="ParsleyValidator",this.Validator=s,this.locale="en",this.init(e||{},t||{})};r.prototype={init:function(t,i){this.catalog=i;for(var n in t)this.addValidator(n,t[n].fn,t[n].priority,t[n].requirementsTransformer);e.emit("parsley:validator:init")},setLocale:function(e){if("undefined"==typeof this.catalog[e])throw new Error(e+" is not available in the catalog");return this.locale=e,this},addCatalog:function(e,t,i){return"object"==typeof t&&(this.catalog[e]=t),!0===i?this.setLocale(e):this},addMessage:function(e,t,i){return"undefined"==typeof this.catalog[e]&&(this.catalog[e]={}),this.catalog[e][t.toLowerCase()]=i,this},validate:function(){return(new this.Validator.Validator).validate.apply(new s.Validator,arguments)},addValidator:function(t,i,n,r){return this.validators[t.toLowerCase()]=function(t){return e.extend((new s.Assert).Callback(i,t),{priority:n,requirementsTransformer:r})},this},updateValidator:function(e,t,i,n){return this.addValidator(e,t,i,n)},removeValidator:function(e){return delete this.validators[e],this},getErrorMessage:function(e){var t;return t="type"===e.name?this.catalog[this.locale][e.name][e.requirements]:this.formatMessage(this.catalog[this.locale][e.name],e.requirements),""!==t?t:this.catalog[this.locale].defaultMessage},formatMessage:function(e,t){if("object"==typeof t){for(var i in t)e=this.formatMessage(e,t[i]);return e}return"string"==typeof e?e.replace(new RegExp("%s","i"),t):""},validators:{notblank:function(){return e.extend((new s.Assert).NotBlank(),{priority:2})},required:function(){return e.extend((new s.Assert).Required(),{priority:512})},type:function(t){var i;switch(t){case"email":i=(new s.Assert).Email();break;case"range":case"number":i=(new s.Assert).Regexp("^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)?(?:\\.\\d+)?$");break;case"integer":i=(new s.Assert).Regexp("^-?\\d+$");break;case"digits":i=(new s.Assert).Regexp("^\\d+$");break;case"alphanum":i=(new s.Assert).Regexp("^\\w+$","i");break;case"url":i=(new s.Assert).Regexp("(https?:\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)","i");break;default:throw new Error("validator type `"+t+"` is not supported")}return e.extend(i,{priority:256})},pattern:function(t){var i="";return/^\/.*\/(?:[gimy]*)$/.test(t)&&(i=t.replace(/.*\/([gimy]*)$/,"$1"),t=t.replace(new RegExp("^/(.*?)/"+i+"$"),"$1")),e.extend((new s.Assert).Regexp(t,i),{priority:64})},minlength:function(t){return e.extend((new s.Assert).Length({min:t}),{priority:30,requirementsTransformer:function(){return"string"!=typeof t||isNaN(t)?t:parseInt(t,10)}})},maxlength:function(t){return e.extend((new s.Assert).Length({max:t}),{priority:30,requirementsTransformer:function(){return"string"!=typeof t||isNaN(t)?t:parseInt(t,10)}})},length:function(t){return e.extend((new s.Assert).Length({min:t[0],max:t[1]}),{priority:32})},mincheck:function(e){return this.minlength(e)},maxcheck:function(e){return this.maxlength(e)},check:function(e){return this.length(e)},min:function(t){return e.extend((new s.Assert).GreaterThanOrEqual(t),{priority:30,requirementsTransformer:function(){return"string"!=typeof t||isNaN(t)?t:parseInt(t,10)}})},max:function(t){return e.extend((new s.Assert).LessThanOrEqual(t),{priority:30,requirementsTransformer:function(){return"string"!=typeof t||isNaN(t)?t:parseInt(t,10)}})},range:function(t){return e.extend((new s.Assert).Range(t[0],t[1]),{priority:32,requirementsTransformer:function(){for(var e=0;e<t.length;e++)t[e]="string"!=typeof t[e]||isNaN(t[e])?t[e]:parseInt(t[e],10);return t}})},equalto:function(t){return e.extend((new s.Assert).EqualTo(t),{priority:256,requirementsTransformer:function(){return e(t).length?e(t).val():t}})}}};var a=function(){this.__class__="ParsleyUI"};a.prototype={listen:function(){return e.listen("parsley:form:init",this,this.setupForm),e.listen("parsley:field:init",this,this.setupField),e.listen("parsley:field:validated",this,this.reflow),e.listen("parsley:form:validated",this,this.focus),e.listen("parsley:field:reset",this,this.reset),e.listen("parsley:form:destroy",this,this.destroy),e.listen("parsley:field:destroy",this,this.destroy),this},reflow:function(e){if("undefined"!=typeof e._ui&&!1!==e._ui.active){var t=this._diff(e.validationResult,e._ui.lastValidationResult);e._ui.lastValidationResult=e.validationResult,e._ui.validatedOnce=!0,this.manageStatusClass(e),this.manageErrorsMessages(e,t),this.actualizeTriggers(e),(t.kept.length||t.added.length)&&"undefined"==typeof e._ui.failedOnce&&this.manageFailingFieldTrigger(e)}},getErrorsMessages:function(e){if(!0===e.validationResult)return[];for(var t=[],i=0;i<e.validationResult.length;i++)t.push(this._getErrorMessage(e,e.validationResult[i].assert));return t},manageStatusClass:function(e){!0===e.validationResult?this._successClass(e):e.validationResult.length>0?this._errorClass(e):this._resetClass(e)},manageErrorsMessages:function(t,i){if("undefined"==typeof t.options.errorsMessagesDisabled){if("undefined"!=typeof t.options.errorMessage)return i.added.length||i.kept.length?(0===t._ui.$errorsWrapper.find(".parsley-custom-error-message").length&&t._ui.$errorsWrapper.append(e(t.options.errorTemplate).addClass("parsley-custom-error-message")),t._ui.$errorsWrapper.addClass("filled").find(".parsley-custom-error-message").html(t.options.errorMessage)):t._ui.$errorsWrapper.removeClass("filled").find(".parsley-custom-error-message").remove();for(var n=0;n<i.removed.length;n++)this.removeError(t,i.removed[n].assert.name,!0);for(n=0;n<i.added.length;n++)this.addError(t,i.added[n].assert.name,void 0,i.added[n].assert,!0);for(n=0;n<i.kept.length;n++)this.updateError(t,i.kept[n].assert.name,void 0,i.kept[n].assert,!0)}},addError:function(t,i,n,s,r){t._ui.$errorsWrapper.addClass("filled").append(e(t.options.errorTemplate).addClass("parsley-"+i).html(n||this._getErrorMessage(t,s))),!0!==r&&this._errorClass(t)},updateError:function(e,t,i,n,s){e._ui.$errorsWrapper.addClass("filled").find(".parsley-"+t).html(i||this._getErrorMessage(e,n)),!0!==s&&this._errorClass(e)},removeError:function(e,t,i){e._ui.$errorsWrapper.removeClass("filled").find(".parsley-"+t).remove(),!0!==i&&this.manageStatusClass(e)},focus:function(e){if(!0===e.validationResult||"none"===e.options.focus)return e._focusedField=null;e._focusedField=null;for(var t=0;t<e.fields.length;t++)if(!0!==e.fields[t].validationResult&&e.fields[t].validationResult.length>0&&"undefined"==typeof e.fields[t].options.noFocus){if("first"===e.options.focus)return e._focusedField=e.fields[t].$element,e._focusedField.focus();e._focusedField=e.fields[t].$element}return null===e._focusedField?null:e._focusedField.focus()},_getErrorMessage:function(e,t){var i=t.name+"Message";return"undefined"!=typeof e.options[i]?window.ParsleyValidator.formatMessage(e.options[i],t.requirements):window.ParsleyValidator.getErrorMessage(t)},_diff:function(e,t,i){for(var n=[],s=[],r=0;r<e.length;r++){for(var a=!1,o=0;o<t.length;o++)if(e[r].assert.name===t[o].assert.name){a=!0;break}a?s.push(e[r]):n.push(e[r])}return{kept:s,added:n,removed:i?[]:this._diff(t,e,!0).added}},setupForm:function(t){t.$element.on("submit.Parsley",!1,e.proxy(t.onSubmitValidate,t)),!1!==t.options.uiEnabled&&t.$element.attr("novalidate","")},setupField:function(t){var i={active:!1};!1!==t.options.uiEnabled&&(i.active=!0,t.$element.attr(t.options.namespace+"id",t.__id__),i.$errorClassHandler=this._manageClassHandler(t),i.errorsWrapperId="parsley-id-"+("undefined"!=typeof t.options.multiple?"multiple-"+t.options.multiple:t.__id__),i.$errorsWrapper=e(t.options.errorsWrapper).attr("id",i.errorsWrapperId),i.lastValidationResult=[],i.validatedOnce=!1,i.validationInformationVisible=!1,t._ui=i,t.$element.is(t.options.excluded)||this._insertErrorWrapper(t),this.actualizeTriggers(t))},_manageClassHandler:function(t){if("string"==typeof t.options.classHandler&&e(t.options.classHandler).length)return e(t.options.classHandler);var i=t.options.classHandler(t);return"undefined"!=typeof i&&i.length?i:"undefined"==typeof t.options.multiple||t.$element.is("select")?t.$element:t.$element.parent()},_insertErrorWrapper:function(t){var i;if("string"==typeof t.options.errorsContainer){if(e(t.options.errorsContainer).length)return e(t.options.errorsContainer).append(t._ui.$errorsWrapper);window.console&&window.console.warn&&window.console.warn("The errors container `"+t.options.errorsContainer+"` does not exist in DOM")}else"function"==typeof t.options.errorsContainer&&(i=t.options.errorsContainer(t));return"undefined"!=typeof i&&i.length?i.append(t._ui.$errorsWrapper):"undefined"==typeof t.options.multiple?t.$element.after(t._ui.$errorsWrapper):t.$element.parent().after(t._ui.$errorsWrapper)},actualizeTriggers:function(t){var i=this;if(t.options.multiple?e("["+t.options.namespace+'multiple="'+t.options.multiple+'"]').each(function(){e(this).off(".Parsley")}):t.$element.off(".Parsley"),!1!==t.options.trigger){var n=t.options.trigger.replace(/^\s+/g,"").replace(/\s+$/g,"");""!==n&&(t.options.multiple?e("["+t.options.namespace+'multiple="'+t.options.multiple+'"]').each(function(){e(this).on(n.split(" ").join(".Parsley ")+".Parsley",!1,e.proxy("function"==typeof t.eventValidate?t.eventValidate:i.eventValidate,t))}):t.$element.on(n.split(" ").join(".Parsley ")+".Parsley",!1,e.proxy("function"==typeof t.eventValidate?t.eventValidate:this.eventValidate,t)))}},eventValidate:function(e){new RegExp("key").test(e.type)&&!this._ui.validationInformationVisible&&this.getValue().length<=this.options.validationThreshold||(this._ui.validatedOnce=!0,this.validate())},manageFailingFieldTrigger:function(t){return t._ui.failedOnce=!0,t.options.multiple&&e("["+t.options.namespace+'multiple="'+t.options.multiple+'"]').each(function(){return new RegExp("change","i").test(e(this).parsley().options.trigger||"")?void 0:e(this).on("change.ParsleyFailedOnce",!1,e.proxy(t.validate,t))}),t.$element.is("select")&&!new RegExp("change","i").test(t.options.trigger||"")?t.$element.on("change.ParsleyFailedOnce",!1,e.proxy(t.validate,t)):new RegExp("keyup","i").test(t.options.trigger||"")?void 0:t.$element.on("keyup.ParsleyFailedOnce",!1,e.proxy(t.validate,t))},reset:function(t){t.$element.off(".Parsley"),t.$element.off(".ParsleyFailedOnce"),"undefined"!=typeof t._ui&&"ParsleyForm"!==t.__class__&&(t._ui.$errorsWrapper.children().each(function(){e(this).remove()}),this._resetClass(t),t._ui.validatedOnce=!1,t._ui.lastValidationResult=[],t._ui.validationInformationVisible=!1)},destroy:function(e){this.reset(e),"ParsleyForm"!==e.__class__&&("undefined"!=typeof e._ui&&e._ui.$errorsWrapper.remove(),delete e._ui)},_successClass:function(e){e._ui.validationInformationVisible=!0,e._ui.$errorClassHandler.removeClass(e.options.errorClass).addClass(e.options.successClass)},_errorClass:function(e){e._ui.validationInformationVisible=!0,e._ui.$errorClassHandler.removeClass(e.options.successClass).addClass(e.options.errorClass)},_resetClass:function(e){e._ui.$errorClassHandler.removeClass(e.options.successClass).removeClass(e.options.errorClass)}};var o=function(i,n,s,r){this.__class__="OptionsFactory",this.__id__=t.hash(4),this.formOptions=null,this.fieldOptions=null,this.staticOptions=e.extend(!0,{},i,n,s,{namespace:r})};o.prototype={get:function(e){if("undefined"==typeof e.__class__)throw new Error("Parsley Instance expected");switch(e.__class__){case"Parsley":return this.staticOptions;case"ParsleyForm":return this.getFormOptions(e);case"ParsleyField":case"ParsleyFieldMultiple":return this.getFieldOptions(e);default:throw new Error("Instance "+e.__class__+" is not supported")}},getFormOptions:function(i){return this.formOptions=t.attr(i.$element,this.staticOptions.namespace),e.extend({},this.staticOptions,this.formOptions)},getFieldOptions:function(i){return this.fieldOptions=t.attr(i.$element,this.staticOptions.namespace),null===this.formOptions&&"undefined"!=typeof i.parent&&(this.formOptions=this.getFormOptions(i.parent)),e.extend({},this.staticOptions,this.formOptions,this.fieldOptions)}};var l=function(i,n){if(this.__class__="ParsleyForm",this.__id__=t.hash(4),"OptionsFactory"!==t.get(n,"__class__"))throw new Error("You must give an OptionsFactory instance");this.OptionsFactory=n,this.$element=e(i),this.validationResult=null,this.options=this.OptionsFactory.get(this)};l.prototype={onSubmitValidate:function(t){return this.validate(void 0,void 0,t),!1===this.validationResult&&t instanceof e.Event&&(t.stopImmediatePropagation(),t.preventDefault()),this},validate:function(t,i,n){this.submitEvent=n,this.validationResult=!0;var s=[];this._refreshFields(),e.emit("parsley:form:validate",this);for(var r=0;r<this.fields.length;r++)(!t||this._isFieldInGroup(this.fields[r],t))&&(s=this.fields[r].validate(i),!0!==s&&s.length>0&&this.validationResult&&(this.validationResult=!1));return e.emit("parsley:form:validated",this),this.validationResult},isValid:function(e,t){this._refreshFields();for(var i=0;i<this.fields.length;i++)if((!e||this._isFieldInGroup(this.fields[i],e))&&!1===this.fields[i].isValid(t))return!1;return!0},_isFieldInGroup:function(i,n){return t.isArray(i.options.group)?-1!==e.inArray(i.options.group,n):i.options.group===n},_refreshFields:function(){return this.actualizeOptions()._bindFields()},_bindFields:function(){var e=this;return this.fields=[],this.fieldsMappedById={},this.$element.find(this.options.inputs).each(function(){var t=new window.Parsley(this,{},e);"ParsleyField"!==t.__class__&&"ParsleyFieldMultiple"!==t.__class__||t.$element.is(t.options.excluded)||"undefined"==typeof e.fieldsMappedById[t.__class__+"-"+t.__id__]&&(e.fieldsMappedById[t.__class__+"-"+t.__id__]=t,e.fields.push(t))}),this}};var u=function(i,n,s,r,a){if(!new RegExp("ParsleyField").test(t.get(i,"__class__")))throw new Error("ParsleyField or ParsleyFieldMultiple instance expected");if("function"!=typeof window.ParsleyValidator.validators[n]&&"Assert"!==window.ParsleyValidator.validators[n](s).__parentClass__)throw new Error("Valid validator expected");var o=function(e,i){return"undefined"!=typeof e.options[i+"Priority"]?e.options[i+"Priority"]:t.get(window.ParsleyValidator.validators[i](s),"priority")||2};return r=r||o(i,n),"function"==typeof window.ParsleyValidator.validators[n](s).requirementsTransformer&&(s=window.ParsleyValidator.validators[n](s).requirementsTransformer()),e.extend(window.ParsleyValidator.validators[n](s),{name:n,requirements:s,priority:r,groups:[r],isDomConstraint:a||t.attr(i.$element,i.options.namespace,n)})},h=function(i,n,s){this.__class__="ParsleyField",this.__id__=t.hash(4),this.$element=e(i),"undefined"!=typeof s?(this.parent=s,this.OptionsFactory=this.parent.OptionsFactory,this.options=this.OptionsFactory.get(this)):(this.OptionsFactory=n,this.options=this.OptionsFactory.get(this)),this.constraints=[],this.constraintsByName={},this.validationResult=[],this._bindConstraints()};h.prototype={validate:function(t){return this.value=this.getValue(),e.emit("parsley:field:validate",this),e.emit("parsley:field:"+(this.isValid(t,this.value)?"success":"error"),this),e.emit("parsley:field:validated",this),this.validationResult},isValid:function(e,t){this.refreshConstraints();var i=this._getConstraintsSortedPriorities();if(t=t||this.getValue(),0===t.length&&!this._isRequired()&&"undefined"==typeof this.options.validateIfEmpty&&!0!==e)return this.validationResult=[];if(!1===this.options.priorityEnabled)return!0===(this.validationResult=this.validateThroughValidator(t,this.constraints,"Any"));for(var n=0;n<i.length;n++)if(!0!==(this.validationResult=this.validateThroughValidator(t,this.constraints,i[n])))return!1;return!0},getValue:function(){var e;
return e="undefined"!=typeof this.options.value?this.options.value:this.$element.val(),"undefined"==typeof e||null===e?"":!0===this.options.trimValue?e.replace(/^\s+|\s+$/g,""):e},refreshConstraints:function(){return this.actualizeOptions()._bindConstraints()},addConstraint:function(e,t,i,n){if(e=e.toLowerCase(),"function"==typeof window.ParsleyValidator.validators[e]){var s=new u(this,e,t,i,n);"undefined"!==this.constraintsByName[s.name]&&this.removeConstraint(s.name),this.constraints.push(s),this.constraintsByName[s.name]=s}return this},removeConstraint:function(e){for(var t=0;t<this.constraints.length;t++)if(e===this.constraints[t].name){this.constraints.splice(t,1);break}return this},updateConstraint:function(e,t,i){return this.removeConstraint(e).addConstraint(e,t,i)},_bindConstraints:function(){for(var e=[],t=0;t<this.constraints.length;t++)!1===this.constraints[t].isDomConstraint&&e.push(this.constraints[t]);this.constraints=e;for(var i in this.options)this.addConstraint(i,this.options[i]);return this._bindHtml5Constraints()},_bindHtml5Constraints:function(){(this.$element.hasClass("required")||this.$element.attr("required"))&&this.addConstraint("required",!0,void 0,!0),"string"==typeof this.$element.attr("pattern")&&this.addConstraint("pattern",this.$element.attr("pattern"),void 0,!0),"undefined"!=typeof this.$element.attr("min")&&"undefined"!=typeof this.$element.attr("max")?this.addConstraint("range",[this.$element.attr("min"),this.$element.attr("max")],void 0,!0):"undefined"!=typeof this.$element.attr("min")?this.addConstraint("min",this.$element.attr("min"),void 0,!0):"undefined"!=typeof this.$element.attr("max")&&this.addConstraint("max",this.$element.attr("max"),void 0,!0);var e=this.$element.attr("type");return"undefined"==typeof e?this:"number"===e?this.addConstraint("type","integer",void 0,!0):new RegExp(e,"i").test("email url range")?this.addConstraint("type",e,void 0,!0):this},_isRequired:function(){return"undefined"==typeof this.constraintsByName.required?!1:!1!==this.constraintsByName.required.requirements},_getConstraintsSortedPriorities:function(){for(var e=[],t=0;t<this.constraints.length;t++)-1===e.indexOf(this.constraints[t].priority)&&e.push(this.constraints[t].priority);return e.sort(function(e,t){return t-e}),e}};var d=function(){this.__class__="ParsleyFieldMultiple"};d.prototype={addElement:function(e){return this.$elements.push(e),this},refreshConstraints:function(){var t;if(this.constraints=[],this.$element.is("select"))return this.actualizeOptions()._bindConstraints(),this;for(var i=0;i<this.$elements.length;i++)if(e("html").has(this.$elements[i]).length){t=this.$elements[i].data("ParsleyFieldMultiple").refreshConstraints().constraints;for(var n=0;n<t.length;n++)this.addConstraint(t[n].name,t[n].requirements,t[n].priority,t[n].isDomConstraint)}else this.$elements.splice(i,1);return this},getValue:function(){if("undefined"!=typeof this.options.value)return this.options.value;if(this.$element.is("input[type=radio]"))return e("["+this.options.namespace+'multiple="'+this.options.multiple+'"]:checked').val()||"";if(this.$element.is("input[type=checkbox]")){var t=[];return e("["+this.options.namespace+'multiple="'+this.options.multiple+'"]:checked').each(function(){t.push(e(this).val())}),t.length?t:[]}return this.$element.is("select")&&null===this.$element.val()?[]:this.$element.val()},_init:function(e){return this.$elements=[this.$element],this.options.multiple=e,this}};var f=e({}),p={};e.listen=function(e){if("undefined"==typeof p[e]&&(p[e]=[]),"function"==typeof arguments[1])return p[e].push({fn:arguments[1]});if("object"==typeof arguments[1]&&"function"==typeof arguments[2])return p[e].push({fn:arguments[2],ctxt:arguments[1]});throw new Error("Wrong parameters")},e.listenTo=function(e,t,i){if("undefined"==typeof p[t]&&(p[t]=[]),!(e instanceof h||e instanceof l))throw new Error("Must give Parsley instance");if("string"!=typeof t||"function"!=typeof i)throw new Error("Wrong parameters");p[t].push({instance:e,fn:i})},e.unsubscribe=function(e,t){if("undefined"!=typeof p[e]){if("string"!=typeof e||"function"!=typeof t)throw new Error("Wrong arguments");for(var i=0;i<p[e].length;i++)if(p[e][i].fn===t)return p[e].splice(i,1)}},e.unsubscribeTo=function(e,t){if("undefined"!=typeof p[t]){if(!(e instanceof h||e instanceof l))throw new Error("Must give Parsley instance");for(var i=0;i<p[t].length;i++)if("undefined"!=typeof p[t][i].instance&&p[t][i].instance.__id__===e.__id__)return p[t].splice(i,1)}},e.unsubscribeAll=function(e){"undefined"!=typeof p[e]&&delete p[e]},e.emit=function(e,t){if("undefined"!=typeof p[e])for(var i=0;i<p[e].length;i++)if("undefined"!=typeof p[e][i].instance){if(t instanceof h||t instanceof l)if(p[e][i].instance.__id__!==t.__id__){if(p[e][i].instance instanceof l&&t instanceof h)for(var n=0;n<p[e][i].instance.fields.length;n++)if(p[e][i].instance.fields[n].__id__===t.__id__){p[e][i].fn.apply(f,Array.prototype.slice.call(arguments,1));continue}}else p[e][i].fn.apply(f,Array.prototype.slice.call(arguments,1))}else p[e][i].fn.apply("undefined"!=typeof p[e][i].ctxt?p[e][i].ctxt:f,Array.prototype.slice.call(arguments,1))},e.subscribed=function(){return p},window.ParsleyConfig=window.ParsleyConfig||{},window.ParsleyConfig.i18n=window.ParsleyConfig.i18n||{},window.ParsleyConfig.i18n.en=e.extend(window.ParsleyConfig.i18n.en||{},{defaultMessage:"This value seems to be invalid.",type:{email:"This value should be a valid email.",url:"This value should be a valid url.",number:"This value should be a valid number.",integer:"This value should be a valid integer.",digits:"This value should be digits.",alphanum:"This value should be alphanumeric."},notblank:"This value should not be blank.",required:"This value is required.",pattern:"This value seems to be invalid.",min:"This value should be greater than or equal to %s.",max:"This value should be lower than or equal to %s.",range:"This value should be between %s and %s.",minlength:"This value is too short. It should have %s characters or more.",maxlength:"This value is too long. It should have %s characters or fewer.",length:"This value length is invalid. It should be between %s and %s characters long.",mincheck:"You must select at least %s choices.",maxcheck:"You must select %s choices or fewer.",check:"You must select between %s and %s choices.",equalto:"This value should be the same."}),"undefined"!=typeof window.ParsleyValidator&&window.ParsleyValidator.addCatalog("en",window.ParsleyConfig.i18n.en,!0);var c=function(i,n,s){if(this.__class__="Parsley",this.__version__="2.0.5",this.__id__=t.hash(4),"undefined"==typeof i)throw new Error("You must give an element");if("undefined"!=typeof s&&"ParsleyForm"!==s.__class__)throw new Error("Parent instance must be a ParsleyForm instance");return this.init(e(i),n,s)};c.prototype={init:function(e,n,s){if(!e.length)throw new Error("You must bind Parsley on an existing element.");if(this.$element=e,this.$element.data("Parsley")){var r=this.$element.data("Parsley");return"undefined"!=typeof s&&(r.parent=s),r}return this.OptionsFactory=new o(i,t.get(window,"ParsleyConfig")||{},n,this.getNamespace(n)),this.options=this.OptionsFactory.get(this),this.$element.is("form")||t.attr(this.$element,this.options.namespace,"validate")&&!this.$element.is(this.options.inputs)?this.bind("parsleyForm"):this.$element.is(this.options.inputs)&&!this.$element.is(this.options.excluded)?this.isMultiple()?this.handleMultiple(s):this.bind("parsleyField",s):this},isMultiple:function(){return this.$element.is("input[type=radio], input[type=checkbox]")&&"undefined"==typeof this.options.multiple||this.$element.is("select")&&"undefined"!=typeof this.$element.attr("multiple")},handleMultiple:function(i){var n,s,r,a=this;if(this.options=e.extend(this.options,i?i.OptionsFactory.get(i):{},t.attr(this.$element,this.options.namespace)),this.options.multiple?s=this.options.multiple:"undefined"!=typeof this.$element.attr("name")&&this.$element.attr("name").length?s=n=this.$element.attr("name"):"undefined"!=typeof this.$element.attr("id")&&this.$element.attr("id").length&&(s=this.$element.attr("id")),this.$element.is("select")&&"undefined"!=typeof this.$element.attr("multiple"))return this.bind("parsleyFieldMultiple",i,s||this.__id__);if("undefined"==typeof s)return window.console&&window.console.warn&&window.console.warn("To be binded by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.",this.$element),this;if(s=s.replace(/(:|\.|\[|\]|\$)/g,""),"undefined"!=typeof n&&e('input[name="'+n+'"]').each(function(){e(this).is("input[type=radio], input[type=checkbox]")&&e(this).attr(a.options.namespace+"multiple",s)}),e("["+this.options.namespace+"multiple="+s+"]").length)for(var o=0;o<e("["+this.options.namespace+"multiple="+s+"]").length;o++)if("undefined"!=typeof e(e("["+this.options.namespace+"multiple="+s+"]").get(o)).data("Parsley")){r=e(e("["+this.options.namespace+"multiple="+s+"]").get(o)).data("Parsley"),this.$element.data("ParsleyFieldMultiple")||(r.addElement(this.$element),this.$element.attr(this.options.namespace+"id",r.__id__));break}return this.bind("parsleyField",i,s,!0),r||this.bind("parsleyFieldMultiple",i,s)},getNamespace:function(e){return"undefined"!=typeof this.$element.data("parsleyNamespace")?this.$element.data("parsleyNamespace"):"undefined"!=typeof t.get(e,"namespace")?e.namespace:"undefined"!=typeof t.get(window,"ParsleyConfig.namespace")?window.ParsleyConfig.namespace:i.namespace},bind:function(i,s,r,a){var o;switch(i){case"parsleyForm":o=e.extend(new l(this.$element,this.OptionsFactory),new n,window.ParsleyExtend)._bindFields();break;case"parsleyField":o=e.extend(new h(this.$element,this.OptionsFactory,s),new n,window.ParsleyExtend);break;case"parsleyFieldMultiple":o=e.extend(new h(this.$element,this.OptionsFactory,s),new n,new d,window.ParsleyExtend)._init(r);break;default:throw new Error(i+"is not a supported Parsley type")}return"undefined"!=typeof r&&t.setAttr(this.$element,this.options.namespace,"multiple",r),"undefined"!=typeof a?(this.$element.data("ParsleyFieldMultiple",o),o):(new RegExp("ParsleyF","i").test(o.__class__)&&(this.$element.data("Parsley",o),e.emit("parsley:"+("parsleyForm"===i?"form":"field")+":init",o)),o)}},e.fn.parsley=e.fn.psly=function(t){if(this.length>1){var i=[];return this.each(function(){i.push(e(this).parsley(t))}),i}return e(this).length?new c(this,t):void(window.console&&window.console.warn&&window.console.warn("You must bind Parsley on an existing element."))},window.ParsleyUI="function"==typeof t.get(window,"ParsleyConfig.ParsleyUI")?(new window.ParsleyConfig.ParsleyUI).listen():(new a).listen(),"undefined"==typeof window.ParsleyExtend&&(window.ParsleyExtend={}),"undefined"==typeof window.ParsleyConfig&&(window.ParsleyConfig={}),window.Parsley=window.psly=c,window.ParsleyUtils=t,window.ParsleyValidator=new r(window.ParsleyConfig.validators,window.ParsleyConfig.i18n),!1!==t.get(window,"ParsleyConfig.autoBind")&&e(document).ready(function(){e("[data-parsley-validate]").length&&e("[data-parsley-validate]").parsley()})});
jQuery(document).ready(function(){function e(e,i,n,r){$(".powermail_tabmenu li",i).removeClass("act"),e.addClass("act"),a(i,n),$(".powermail_fieldset",i).slice(r,r+1).show()}function a(e,a){e.children(a.container).hide()}function i(e,a){a.navigation&&e.children(a.container).each(function(i){var t=$("<div />").addClass("powermail_fieldwrap").addClass("powermail_tab_navigation").appendTo($(this));i>0&&t.append(n(e,a)),i<e.children(a.container).length-1&&t.append(r(e,a))})}function n(e,a){return $("<a />").prop("href","#").addClass("powermail_tab_navigation_previous").html("<").click(function(i){i.preventDefault(),l(e,a)})}function r(e,a){return $("<a />").prop("href","#").addClass("powermail_tab_navigation_next").html(">").click(function(i){i.preventDefault(),t(e,a)})}function t(e,i){var n=e.find("#powermail_tabmenu > li").index($(".act"));e.find("#powermail_tabmenu > li.act").removeClass("act").next().addClass("act"),a(e,i),e.find(".powermail_fieldset").slice(n+1,n+2).show()}function l(e,i){var n=e.find("#powermail_tabmenu > li").index($(".act"));e.find("#powermail_tabmenu > li.act").removeClass("act").prev().addClass("act"),a(e,i),e.find(".powermail_fieldset").slice(n-1,n).show()}function o(a,i){if(i.tabs){var n=$("<ul />",{id:"powermail_tabmenu","class":"powermail_tabmenu"}).insertBefore(a.children(i.container).filter(":first"));a.children(i.container).each(function(r,t){var l=$("<li/>").html($(this).children(i.header).html()).addClass(0==r?"act":"").addClass("item"+r).on("click keypress",{container:a.children(i.container),fieldset:$(t)},function(){var n=$(".powermail_tabmenu li",a).index($(this));e($(this),a,i,n)});i.tabIndex&&l.prop("tabindex",r),n.append(l)})}}$.fn.powermailTabs=function(e){"use strict";var n=jQuery(this);e=jQuery.extend({container:"fieldset",header:"legend",tabs:!0,navigation:!0,openTabOnError:!0,tabIndex:!0},e),a(n,e),n.find(e.container).first().show(),o(n,e),i(n,e),$.fn.parsley&&$('form[data-parsley-validate="data-parsley-validate"]').length&&$(".powermail_morestep").length&&$('form[data-parsley-validate="data-parsley-validate"]').parsley().subscribe("parsley:field:validated",function(){$("#powermail_tabmenu > li").removeClass("parsley-error"),$('form[data-parsley-validate="data-parsley-validate"]').parsley().isValid()||$(".parsley-error").each(function(){var e=$(".powermail_fieldset").index($(this).closest(".powermail_fieldset")),a=$("#powermail_tabmenu > li").slice(e,e+1);a.addClass("parsley-error")})}),e.openTabOnError&&$.listen("parsley:field:error",function(){setTimeout(function(){$(".powermail_tabmenu > .parsley-error:first").click()},50)})}});
function ajaxFormSubmit(){$(document).on("submit","form[data-powermail-ajax]",function(e){var a=$(this),t=a.data("powermail-form");$.ajax({type:"POST",url:a.prop("action"),data:a.serialize(),beforeSend:function(){var e=$("<div />").addClass("powermail_progressbar").html($("<div />").addClass("powermail_progress").html($("<div />").addClass("powermail_progess_inner")));$(".powermail_submit",a).parent().append(e),$(".powermail_confirmation_submit, .powermail_confirmation_form",a).closest(".powermail_confirmation").append(e)},complete:function(){$(".powermail_fieldwrap_submit",a).find(".powermail_progressbar").remove()},success:function(e){var a=$('*[data-powermail-form="'+t+'"]:first',e);$(".tx-powermail").html(a),$.fn.powermailTabs&&$(".powermail_morestep").powermailTabs(),$.fn.parsley&&$('form[data-parsley-validate="data-parsley-validate"]').parsley()}}),e.preventDefault()})}function getDatetimeForDateFields(e,a,t){var i=new Date(Date.parseDate(e,a)),r=i.getFullYear()+"-";r+=("0"+(i.getMonth()+1)).slice(-2)+"-",r+=("0"+i.getDate()).slice(-2);var o=("0"+i.getHours()).slice(-2)+":"+("0"+i.getMinutes()).slice(-2),l=r+"T"+o;return"date"===t?r:"datetime-local"===t?l:"time"===t?o:"error"}function getLocationAndWrite(){navigator.geolocation&&navigator.geolocation.getCurrentPosition(function(e){var a=e.coords.latitude,t=e.coords.longitude,i=baseurl+"/index.php?eID=powermailEidGetLocation";jQuery.ajax({url:i,data:"lat="+a+"&lng="+t,cache:!1,beforeSend:function(){jQuery("body").css("cursor","wait")},complete:function(){jQuery("body").css("cursor","default")},success:function(e){e&&jQuery(".powermail_fieldwrap_location input").val(e)}})})}function getBaseUrl(){var e;return e=jQuery("base").length>0?jQuery("base").prop("href"):"https:"!=window.location.protocol?"http://"+window.location.hostname:"https://"+window.location.hostname}var baseurl;jQuery(document).ready(function(e){function a(e){e.prop("disabled","disabled").addClass("hide")}function t(e){e.removeProp("disabled").removeClass("hide")}baseurl=getBaseUrl(),e.fn.powermailTabs&&e(".powermail_morestep").powermailTabs(),e(".powermail_fieldwrap_location input").length&&getLocationAndWrite(),e("form[data-powermail-ajax]").length&&ajaxFormSubmit(),e.fn.datetimepicker&&e(".powermail_date").each(function(){var a=e(this);if("date"===a.prop("type")||"datetime-local"===a.prop("type")||"time"===a.prop("type")){if(!a.data("datepicker-force"))return void(e(this).data("date-value")&&e(this).val(getDatetimeForDateFields(e(this).data("date-value"),e(this).data("datepicker-format"),a.prop("type"))));a.prop("type","text")}var t=!0,i=!0;"date"===a.data("datepicker-settings")?i=!1:"time"===a.data("datepicker-settings")&&(t=!1),a.datetimepicker({format:a.data("datepicker-format"),timepicker:i,datepicker:t,lang:"en",i18n:{en:{months:a.data("datepicker-months").split(","),dayOfWeek:a.data("datepicker-days").split(",")}}})}),e(".powermail_fieldwrap_file_inner").find(".deleteAllFiles").each(function(){a(e(this).closest(".powermail_fieldwrap_file_inner").find('input[type="file"]'))}),e(".deleteAllFiles").click(function(){t(e(this).closest(".powermail_fieldwrap_file_inner").find('input[type="file"]')),e(this).closest("ul").fadeOut(function(){e(this).remove()})}),e(".powermail_all_type_password.powermail_all_value").html("********")});
function isMobile(){var e=navigator.userAgent,a={iphone:e.match(/(iPhone|iPod|iPad)/),blackberry:e.match(/BlackBerry/),android:e.match(/Android/)};return a.iphone||a.blackberry||a.android?!0:!1}function getBaseUrl(){var e;return e=jQuery("base").length>0?jQuery("base").prop("href"):"https:"!=window.location.protocol?"http://"+window.location.hostname:"https://"+window.location.hostname}jQuery(document).ready(function(){var e="";e+="tx_powermail_pi1[language]="+$("#powermail_marketing_information").data("language"),e+="&tx_powermail_pi1[pid]="+$("#powermail_marketing_information").data("pid"),e+="&tx_powermail_pi1[mobileDevice]="+(isMobile()?1:0),e+="&tx_powermail_pi1[referer]="+encodeURIComponent(document.referrer),jQuery.ajax({url:getBaseUrl()+"/index.php?&eID=powermailEidMarketing",data:e,cache:!1})});