let pf = {
	const: {
		webserviceURL: 'https://stcmbackend.sociallabs.biz/API/API.php',
		serverURL: 'https://stcmbackend.sociallabs.biz/',
		version_suffix: ' QA',
		language: null,
		language_table: ''
	},

	countryOptions: [],

	rsc: {
		translateByTag(type) {
			let self = this;
			let callback;

			switch(type) {
				case 'html':
					callback = function(elem, id) {
						self.callbackHtml(elem, id);
					}
					break;
				case 'text':
					callback = function(elem, id) {
						self.callbackText(elem, id);
					}
					break;
				case 'placeholder':
					callback = function(elem, id) {
						self.callbackPlaceholder(elem, id);
					}
					break;
				case 'title':
					callback = function(elem, id) {
						id = id.replace('Title', '');
						self.callbackTitle(elem, id);
					}
					break;
				default:
					callback = '';
					break;
			}

			if(callback != '') {
				$('[idrsc]').each(function() {
					let id = $(this).attr('idrsc');
					callback(this, id);
				});

				if(type == 'title') {
					$('[idrscTitle]').each(function() {
						let id = $(this).attr('idrscTitle');
						callback(this, id);
					});
				}
			}
		},

		translateByTagHTMLFormat(type, arrObj) {
			let text = '';

			switch(type) {
				case 'strong-danger':
					text = '<strong>[SLELEM]</strong><span class="text-danger">*</span>';
					break;
				case 'strong':
					text = '<strong>[SLELEM]</strong>';
					break;
				case 'percent':
					text = '[SLELEM] (%)';
					break;
				case 'id':
					text = '[SLELEM] (ID)';
					break;
				case ':':
					text = '[SLELEM]:';
					break;
				case 'simple':
					text = '[SLELEM]';
					break;
			}

			arrObj.forEach(element => {
				if(pf.const.language[element]) {
					text = text.replace('[SLELEM]', pf.const.language[element]);
					$('[idRSC=' + element + ']').html(text);
				} else {
					text = text.replace('[SLELEM]', element);
					$('[idRSC=' + element + ']').html(text);
				}
			});
		},

		callbackHtml(elem, id) {
			if(pf.const.language[id]) {
				$(elem).html(pf.const.language[id]);
			} else {
				$(elem).html(id);
			}
		},

		callbackText(elem, id) {
			if(pf.const.language[id]) {
				$(elem).text(pf.const.language[id]);
			} else {
				$(elem).text(id);
			}
		},

		callbackPlaceholder(elem, id) {
			if($(elem).attr('placeholder') == id) {
				if(pf.const.language[id]) {
					$(elem).attr('placeholder', pf.const.language[id]);
				} else {
					$(elem).attr('placeholder', id);
				}
			}
		},

		callbackTitle(elem, id) {
			if($(elem).attr('title') == id) {
				if(pf.const.language[id]) {
					$(elem).attr('title', pf.const.language[id]);
				} else {
					$(elem).attr('title', id);
				}
			}
		},

		addPlaceholder(arrObj, char) {
			arrObj.forEach(element => {
				if(pf.const.language[element]) {
					$('[idRSC=' + element + ']').attr('placeholder', pf.const.language[element] + char);
				} else {
					$('[idRSC=' + element + ']').attr('placeholder', id + char);
				}
			});
		}
	},

	utils: {
		validateEmail(email) {
			let re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			return re.test(email);
		},

		removeAccents(strAccents) {
			strAccents = strAccents.split('');
			let strAccentsOut = new Array();
			let strAccentsLen = strAccents.length;
			let accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
			let accentsOut = 'AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz';
			for(let y = 0; y < strAccentsLen; y++) {
				if(accents.indexOf(strAccents[y]) != -1) {
					strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
				} else {
					strAccentsOut[y] = strAccents[y];
				}
			}
			strAccentsOut = strAccentsOut.join('');
			return strAccentsOut;
		},

		removeSpaces(str) {
			str = str.replace(/ +(?= )/g, '');
			return str.trim();
		},

		showInfoDialog(errorTitle, errorContent, customText = pf.const.language.RSC132, callback) {
			$.alert({
				boxWidth: '500px',
				title: `<h3 style="margin: 0 0 10px;">${errorTitle}</h3>`,
				content: errorContent,
				useBootstrap: false,
				bgOpacity: null,
				theme: 'new-style',
				buttons: {
					accept: {
						text: customText, // Regresar by default
						btnClass: 'new-style-accept',
						action() {
							if(callback) {
								callback();
							}
							removeLoader();
						}
					}
				}
			});
		},

		showInfoDialogAcceptCancel(errorTitle, errorContent, objInfo, callbackaccept, callbackCancel) {
			$.alert({
				boxWidth: '500px',
				title: `<h3 class="ma-bo-20">${errorTitle}</h3>`,
				content: errorContent,
				useBootstrap: false,
				bgOpacity: null,
				theme: 'new-style',
				buttons: {
					accept: {
						text: objInfo.cancel.text, // Cancelar
						btnClass: 'new-style-cancel',
						action() {
							if(callbackCancel) {
								callbackCancel();
							}
						}
					},
					cancel: {
						text: objInfo.accept.text, // Aceptar
						btnClass: 'new-style-accept',
						action() {
							if(callbackaccept) {
								callbackaccept();
							}
						}
					},
				}
			});
		},

		showInfoDialogCustomWidth(errorTitle, errorContent, customText, customWidth, callback) {
			$.alert({
				boxWidth: customWidth,
				title: errorTitle,
				content: errorContent,
				useBootstrap: false,
				bgOpacity: null,
				theme: 'new-style',
				buttons: {
					accept: {
						text: customText, // Regresar
						btnClass: 'new-style-accept',
						action() {
							if(callback) {
								callback();
							}
							removeLoader();
						}
					}
				}
			});
		},

		showInfoDialogCustomWidthAcceptCancelNewStyle(title, content, objInfo, customWidth, callbackAccept, callbackCancel) {
			$.confirm({
				boxWidth: customWidth,
				useBootstrap: false,
				bgOpacity: null,
				theme: 'new-style',
				title: `<h3 class="ma-bo-20">${title}</h3>`,
				content: content,
				buttons: {
					accept: {
						text: objInfo.cancel.text, // Cancelar
						btnClass: 'new-style-cancel',
						action() {
							if(callbackCancel) {
								callbackCancel();
							}
						}
					},
					cancel: {
						text: objInfo.accept.text, // Generar
						btnClass: 'new-style-accept',
						action() {
							if(callbackAccept) {
								callbackAccept();
							}
							removeLoader();
						}
					}
				}
			});
		},

		getFileSrc(evt) {
			let file = evt.target.files[0];
			if(file.size > self.maxSize) {
				pf.utils.alerts.showInfoDialogFilesSize();
			} else {
				let src = URL.createObjectURL(evt.target.files[0]);
				return {file: file, src: src};
			}
		},

		alerts: {
			showInfoDialogFilesSize() {
				let alertTitle = pf.const.language.RSC566;
				let alertText = pf.const.language.RSC1337;
				pf.utils.showInfoDialog(alertTitle, alertText);
			},
			showCompleteAllFields() {
				let alertTitle = pf.const.language.RSC78;
				let alertText = pf.const.language.RSC101;
				pf.utils.showInfoDialog(alertTitle, alertText);
			}
		},

		showLoginDialog(errorTitle, errorContent) {
			let lightbox = $('.lightbox.login_error').clone(true, true);
			lightbox.find('h1').text(errorTitle);
			lightbox.find('p').text(errorContent);
			lightbox.lightbox_me({
				centered: true,
				lightboxSpeed: 600,
				showOverlay: true,
				closeClick: false,
				closeSelector: '.close',
				destroyOnClose: true,
				overlayCSS: {background: '#000', opacity: 0.7},
				onLoad() {},
				onClose() {}
			});
		},

		isValidDate(d) {
			return d instanceof Date && !isNaN(d);
		},

		stringToDate(string) {
			let t = string.split(/[- :]/);
			return new Date(Date.UTC(t[0], t[1] - 1, t[2], t[3], t[4], t[5]));
		},

		dateToHour(date) {
			let minutes = date.getMinutes();
			if(minutes < 10) {
				minutes = '0' + minutes;
			}

			return date.getHours() + ':' + minutes;
		},

		dateToDay(date) {
			return date.getDate() + ' ' + pf.utils.numberToMonth(date.getMonth()) + ' ' + date.getFullYear();
		},

		numberToMonth(n) {
			switch(n) {
				case 0:
					return 'Enero';
				case 1:
					return 'Febrero';
				case 2:
					return 'Marzo';
				case 3:
					return 'Abril';
				case 4:
					return 'Mayo';
				case 5:
					return 'Junio';
				case 6:
					return 'Julio';
				case 7:
					return 'Agosto';
				case 8:
					return 'Septiembre';
				case 9:
					return 'Octubre';
				case 10:
					return 'Noviembre';
				case 11:
					return 'Diciembre';
				default:
					return '';
			}
		},

		formatHour(stamp) {
			let date = pf.utils.stringToDate(stamp);
			return pf.utils.dateToDay(date) + ' ' + pf.utils.dateToHour(date);
		}
	},

	ajax: {
		requests: [],
		valueArray: [],
		value: null,

		abort() {
			pf.ajax.valueArray.forEach(value => {
				value.abort();
			});
		},

		abortRequest(reqName) {
			if(pf.ajax.valueArray[reqName]) {
				pf.ajax.valueArray[reqName].abort();
			}
		},

		request(reqName, reqData, repeat) {
			let self = pf;

			if(!repeat) {
				repeat = false;
			}

			if(!self.ajax.requests[reqName]) {
				let reqTimedOut = false;

				let toTime = reqData.timeout - 10;
				let reqTimeout = setTimeout(function() {
					reqTimedOut = true;
				}, toTime);

				if(!reqData.data.client) {
					reqData.data.client = {};
				}
				reqData.data.client.platform = 'web';
				self.ajax.requests[reqName] = true;
				self.ajax.valueArray[reqName] = $.ajax(reqData)
				.done(function(json) {
					delete self.ajax.requests[reqName];
					delete self.ajax.valueArray[reqName];

					let response = json;

					if(response.status == 'KO') {
						if(response.response.error == '1400') {
							self.ajax.expireSession();
						} else if(response.response.error == '1403') {
							self.ajax.deniedPermission();
						} else {
							$(document).trigger(reqName, {status: 'OK', resData: {response: response, status: '200', headers: '', config: ''}});
						}
					} else {
						$(document).trigger(reqName, {status: 'OK', resData: {response: response, status: '200', headers: '', config: ''}});
					}
				})
				.fail(function(ex) {
					delete self.ajax.requests[reqName];
					delete self.ajax.valueArray[reqName];

					if(reqTimedOut) {
						ex = 'ERR_REQ_TIMED_OUT';
					}
					$(document).trigger(reqName, {status: 'KO', resData: {error: ex, status: '0', headers: '', config: ''}});
				});
			}
		},

		expireSession() {
			let self = this;

			removeAllLoaders();
			let alertTitle = 'Sesión expirada';
			let alertText = 'Su sesión ha expirado por límite de tiempo o por acceso en el sistema con el mismo usuario desde otro dispositivo. Para seguir utilizando la aplicación, por favor ingrese de nuevo.';
			let alertBtn = 'Acceder';
			pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
				self.setWindowLocationIndex();
			});
		},

		setWindowLocation(location) {
			window.location.href = location;
		},

		setWindowLocationIndex() {
			let self = this;

			self.setWindowLocation('index.html');
		}
	}
};