﻿// sino se coloca el carácter "/" inicial en las llamadas del api o si sucede algún otro
//error en peticiones al api, porque un URL está mal escrito el navegador mostrará
//un error relacionado a angular loading bar
(function (window) {
	'use strict';

	window.__env = window.__env || {};

	// API url
	window.__env.apiUrl = window.__env_serverside.apiUrl;
	window.__env.showRemember = __env_serverside.showRemember;
	window.__env.showWatchCount = __env_serverside.showWatchCount;
	window.__env.debugReception = __env_serverside.debugReception;

	// Token
	window.__env.tokenUrl = '/token';

	// Base url
	window.__env.baseUrl = '/';
	// Day of Week in Spanish
	window.__env.dayWeek = [{ id: 0, name: 'Seleccione' }, { id: 1, name: 'Lunes' }, { id: 2, name: 'Martes' }, { id: 3, name: 'Miércoles' }, { id: 4, name: 'Jueves' }, { id: 5, name: 'Viernes' }, { id: 6, name: 'Sábado' }, { id: 7, name: 'Domingo' }];

	window.BaseRoute = '/api/aca/';
	window.controllerSecurity = "security/";
	window.controllerUsers = "Users/";
	window.controllerAlpha = "alpha/";
	window.controllerClosing = "closing/";
	window.controllerReception = "reception/";
	window.controllerInternalPlaces = "InternalPlaces/";
	window.controllerCompany = "Company/";
	window.controllerEmployee = "Employee/";
	window.controllerGenericProcess = "generic/";
	window.controllerIncompleteRoles = "incompleteRoles/";
	window.controllerLunchCoverSchedule = "lunchCoverSchedule/";
	window.controllerVacationCoverSchedule = "vacationCoverSchedule/";
	window.controllerPersonalAction = "personalAction/";
	window.controllerRole = "roleManagement/";
	window.controllerSettings = "settings/";
	window.controllerAuditLogins = 'auditLogins/';
	window.controllerSoftlandQueries = 'SoftlandQueries/';
	window.controllerBusinessCard = 'BusinessCard/';
	window.controllerRequirementSheet = 'RequirementSheet/';
	window.controllerReports = 'Reports/';
	window.controllerUploadHours = "UploadHours/";
	window.controllerProfiles = "profile/";

	window.__env.auditLoginUrl = window.BaseRoute + window.controllerAuditLogins + 'create/logins/v1';

	//header content
	window.__env.Header = {
		octetStreamMime: 'application/octet-stream',
		name: 'X-FileName',
		content: 'content-type',
		mimeTypePDF: 'application/pdf',
		responseBuffer: 'arraybuffer'
	};

	window.__env.AppProfile = {
		GetPermissions: window.BaseRoute + window.controllerSecurity + 'permissions/v1',
		GetPermissionsTree: window.BaseRoute + window.controllerSecurity + 'permissionsTree/v1',
		GetPermissionsbyRoles: window.BaseRoute + window.controllerSecurity + "permissionsByRole/v1"
	};

	//Role Management Const
	window.__env.ReportsUrl = {
		GetAllAlphasReport: window.BaseRoute + window.controllerReports + 'GetAllAlphasReport',
		GetAllAlphasInvoiceComparisonReport: window.BaseRoute + window.controllerReports + 'GetAllAlphasInvoiceComparisonReport',
		GetAllAlphasPlaceComparisonReport: window.BaseRoute + window.controllerReports + 'GetAllAlphasPlaceComparisonReport',
		GetSalaryPerAlphaReport: window.BaseRoute + window.controllerReports + 'GetSalaryPerAlphaReport',
		GetSalaryPerCostCenterReport: window.BaseRoute + window.controllerReports + 'GetSalaryPerCostCenterReport',
		GetSalaryPerCostCenterResumeReport: window.BaseRoute + window.controllerReports + 'GetSalaryPerCostCenterResumeReport',
		GetSchedulePerAlphaReport: window.BaseRoute + window.controllerReports + 'GetSchedulePerAlphaReport',
		GetOfficersPerAlphaReport: window.BaseRoute + window.controllerReports + 'GetOfficersPerAlphaReport',
		GetOfficersPicturePerAlphaReport: window.BaseRoute + window.controllerReports + 'GetOfficersPicturePerAlphaReport',
		DownloadOfficersPicturePerAlphaReport: window.BaseRoute + window.controllerReports + 'DownloadOfficersPicturePerAlphaReport',
		GetAbsencePerOfficerReport: window.BaseRoute + window.controllerReports + 'GetAbsencePerOfficerReport',
		GetDueServicesReport: window.BaseRoute + window.controllerReports + 'GetDueServicesReport',
		GetDirective012021Report: window.BaseRoute + window.controllerReports + 'GetDirective012021Report'
	};

	//auditoria o bitácora
	window.__env.AuditUrl = {
		getAuditAll: window.BaseRoute + window.controllerSecurity + 'reads/audit/v1',
		getAuditSection: window.BaseRoute + window.controllerSecurity + 'reads/audit/section/v1',
		getTableName: window.BaseRoute + window.controllerSecurity + 'reads/audit/tablename/v1',
		getAuditComposeKey: window.BaseRoute + window.controllerSecurity + 'reads/compose/v1'
	};

	//Cargador Horas Extras
	window.__env.UploadHoursURL = {
		PostHours: window.BaseRoute + window.controllerUploadHours + 'Upload',
		GetTemplate: window.BaseRoute + window.controllerUploadHours + 'GetTemplate'
	};

	//Administración de Roles

	window.__env.AppRoles = {
		AppRolesUrl: window.BaseRoute + window.controllerProfiles + 'readsAll/v1',
		AppRolesInsert: window.BaseRoute + window.controllerProfiles + 'create/v1',
		AppRolesUpdate: window.BaseRoute + window.controllerProfiles + 'update/v1',
		AppRolesDelete: window.BaseRoute + window.controllerProfiles + 'delete/v1'
	};

	//Personal Action Const
	window.__env.PersonalActionURL = {
		getAllPersonalActions: window.BaseRoute + window.controllerPersonalAction + 'reads/v1',
		GetAllPersonalActionStatus: window.BaseRoute + window.controllerPersonalAction + 'GetAllPersonalActionStatus',
		putUpdateStatus: window.BaseRoute + window.controllerPersonalAction + 'update/v1/'
	};
	//Role Assign Const
	window.__env.Employee = {
		getEmployeesUrl: window.BaseRoute + window.controllerEmployee + 'GetEmployees',
		getEmployeesByCompanyUrl: window.BaseRoute + window.controllerEmployee + 'GetEmployeesByCompany',
		getEmployeesByCompanyAndAlphaUrl: window.BaseRoute + window.controllerEmployee + 'GetEmployeesByCompanyAndAlpha',
		getEmployeesInPendingAssignment: window.BaseRoute + window.controllerEmployee + 'GetEmployeesInPendingAssignment',
		getAllEmployesByZone: window.BaseRoute + window.controllerEmployee + 'GetAllEmployesByZone',
		ValidateEmployeesUrl: window.BaseRoute + window.controllerEmployee + 'ValidateEmployees',
		MoveEmployeeDataUrl: window.BaseRoute + window.controllerEmployee + 'MoveEmployeeData'
	};
	//incomplete Rol
	window.__env.incompleteRoleUrl = {
		getIncompleteRoleOfficers: window.BaseRoute + window.controllerIncompleteRoles + 'reads/v1',
		putEmployeeSchedule: window.BaseRoute + window.controllerIncompleteRoles + 'update/v1'

	};

	//lunch Cover Schedule
	window.__env.lunchCoverScheduleUrl = {
		getLunchCoverScheduleOfficers: window.BaseRoute + window.controllerLunchCoverSchedule + 'reads/v1',
		getAvailableAlfasToCover: window.BaseRoute + window.controllerLunchCoverSchedule + 'availableAlphasToCover/v1',
		getLunchCoverAssignmentsPerAlpha: window.BaseRoute + window.controllerLunchCoverSchedule + 'getLunchCoverAssignmentsPerAlpha/v1',
		updateLunchCoverSchedule: window.BaseRoute + window.controllerLunchCoverSchedule + 'update/v1'

	};

	// vacation cover schedule
	window.__env.vacationCoverScheduleUrl = {
		getVacationCoverScheduleOfficers: window.BaseRoute + window.controllerVacationCoverSchedule + 'reads/v1',
		getAvailableOfficersToCover: window.BaseRoute + window.controllerVacationCoverSchedule + 'availableOfficersToCover/v1',
		getVacationCoverAssignmentsPerOfficer: window.BaseRoute + window.controllerVacationCoverSchedule + 'getVacationCoverAssignmentsPerOfficer/v1',
		updateVacationCoverSchedule: window.BaseRoute + window.controllerVacationCoverSchedule + 'update/v1'
	};

	//pending assign Officer
	window.__env.pendingAssignOfficerUrl = {
		softlandGetZonesByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllZonesByCompany'
	};

	//Role Management Const
	window.__env.RolesManagerUrl = {
		getAllRoles: window.BaseRoute + window.controllerRole + 'GetAllRoles',
		postRole: window.BaseRoute + window.controllerRole + 'PostRole',
		getRoleById: window.BaseRoute + window.controllerRole + 'GetRole',
		putRole: window.BaseRoute + window.controllerRole + 'PutRole'
	};

	//Closing
	window.__env.ClosingUrl = {
		getOperations: window.BaseRoute + window.controllerClosing + 'operations/v1',
		getClosings: window.BaseRoute + window.controllerClosing + 'reads/v1',
		getClosingItem: window.BaseRoute + window.controllerClosing + 'reads/v1/item',
		getHasClosing: window.BaseRoute + window.controllerClosing + 'reads/v1/date',
		createClosing: window.BaseRoute + window.controllerClosing + 'create/v1',
		updateClosing: window.BaseRoute + window.controllerClosing + 'update/v1',
		generatePersonalActionClosing: window.BaseRoute + window.controllerClosing + 'generatePersonalActions/v1',
		getTypesIncident: window.BaseRoute + window.controllerClosing + 'incident/types',
		getIncidentDto: window.BaseRoute + window.controllerClosing + 'incident/v1',
		createReportIncident: window.BaseRoute + window.controllerClosing + 'incident/report/v1/',
		downloadReportIncident: window.BaseRoute + window.controllerClosing + 'incident/report/v1/',
		createReportTransference: window.BaseRoute + window.controllerClosing + 'transference/report/v1/',
		downloadReportTransference: window.BaseRoute + window.controllerClosing + 'transference/report/v1/',
		getListConcept: window.BaseRoute + window.controllerClosing + 'reads/concepts/v1',
		postCreateUploadConcept: window.BaseRoute + window.controllerClosing + 'create/uploadconcepts/v1',
		getLastCreatedUploadConcept: window.BaseRoute + window.controllerClosing + 'last/uploadconcepts/v1',
		getCreatedConcept: window.BaseRoute + window.controllerClosing + 'reads/concepts/created/v1',
		getDetailConcept: window.BaseRoute + window.controllerClosing + 'reads/concepts/item/v1',
		getExportUploadConcept: window.BaseRoute + window.controllerClosing + 'export/uploadconcepts/v1/',
		putApprovalUploadConcept: window.BaseRoute + window.controllerClosing + 'update/uploadconcepts/v1/',
		GetAllClosingAbsenceStatus: window.BaseRoute + window.controllerClosing + 'GetAllClosingAbsenceStatus',
		GetAllClosingAbsenceType: window.BaseRoute + window.controllerClosing + 'GetAllClosingAbsenceType'
	};
	//reception services
	window.__env.ReceptionUrl = {
		getReception: window.BaseRoute + window.controllerReception + 'reads/v1',
		getEmployeeByAlpha: window.BaseRoute + window.controllerReception + 'reads/alpha/v1',
		getEmployeeByInternalPlace: window.BaseRoute + window.controllerReception + 'reads/internalPlace/v1',
		getEmployeeByFreeDay: window.BaseRoute + window.controllerReception + 'reads/freeday/v1',
		getGuardService: window.BaseRoute + window.controllerReception + 'reads/guard/v1',
		getMotorService: window.BaseRoute + window.controllerReception + 'reads/motor/v1',
		getOverTimeService: window.BaseRoute + window.controllerReception + 'reads/overtime/v1',
		updateReceptionPhone: window.BaseRoute + window.controllerReception + 'update/phone/v1',
		saveOperation: window.BaseRoute + window.controllerReception + 'save/operation/v1',
		postSaveAllOperation: window.BaseRoute + window.controllerReception + 'save/alloperation/v1',
		postDeleteCover: window.BaseRoute + window.controllerReception + 'delete/cover/v1',
		getCovered: window.BaseRoute + window.controllerReception + 'reads/cover/v1',
		putIntegrationERP: window.BaseRoute + window.controllerReception + 'update/erpemployee/v1',
		softlandGetZonesByActiveCompaniesUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllZonesByActiveCompanies'
	};

	//Generic Process
	window.__env.GenericUrl = {
		postExportData: window.BaseRoute + window.controllerGenericProcess + 'reads/data/v1',
		postExportDataPdf: window.BaseRoute + window.controllerGenericProcess + 'reads/data/pdf/v1',
	};

	window.__env.User = {
		usersUrl: window.BaseRoute + window.controllerUsers + 'readsAll/v1',
		usersMenusUrl: window.BaseRoute + window.controllerUsers + 'reads/menu/v1',
		usersAccountMgrsUrl: window.BaseRoute + window.controllerUsers + 'reads/AccountMgrs/v1',
		usersDeleteUrl: window.BaseRoute + window.controllerUsers + 'delete/v1',
		usersCreateUrl: window.BaseRoute + window.controllerUsers + 'create/v1',
		usersUpdateUrl: window.BaseRoute + window.controllerUsers + 'update/v1',
		usersNotificationGroupUrl: window.BaseRoute + window.controllerUsers + 'reads/notifications/v1',
		softlandUsersUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetSoftlandUsers',
		alphasByAccountMgr: window.BaseRoute + window.controllerSecurity + 'read/alphasAccountMgr/v1',
		rolesUrl: window.BaseRoute + window.controllerProfiles + 'readsType/v1',
		accountMgrUrl: window.BaseRoute + window.controllerSecurity + 'GetAllAccountMgr',
		allowedAccountMgrUrl: window.BaseRoute + window.controllerSecurity + 'GetAllowedAccountMgr',
		allowedAccountMgrByCompanyUrl: window.BaseRoute + window.controllerSecurity + 'GetAllowedAccountMgrByCompany',
		allowedSupervisorByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllSupervisorSoftland',
		clientsByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllClientsByCompanyList',
		alphasByClientsURL: window.BaseRoute + window.controllerSecurity + 'read/alphasClients/v1',
		commonAlphasURL: window.BaseRoute + window.controllerSecurity + 'read/commonAlphas/v1',
		GetMenusByUser: window.BaseRoute + window.controllerSecurity + "menus/v1",
		GetPagePermissionsURL: window.BaseRoute + window.controllerSecurity + "permissionsByPage/v1"
	};

	window.__env.InternalPlaces = {
		internalPlacesUrl: window.BaseRoute + window.controllerInternalPlaces + 'reads/v1',
		getInternalPlacesActiveUrl: window.BaseRoute + window.controllerInternalPlaces + 'reads/active/v1',
		updateInternalPlacesUrl: window.BaseRoute + window.controllerInternalPlaces + 'update/v1',
		createInternalPlacesUrl: window.BaseRoute + window.controllerInternalPlaces + 'create/v1'
	};

	window.__env.Company = {
		getCompaniesUrl: window.BaseRoute + window.controllerCompany + 'reads/v1',
		getAllowedCompaniesUrl: window.BaseRoute + window.controllerCompany + 'reads/allowed/v1',
		getAllowedCompanyGroupsUrl: window.BaseRoute + window.controllerCompany + 'reads/allowedGroups/v1',
		getActiveCompaniesUrl: window.BaseRoute + window.controllerCompany + 'reads/active/v1',
		getSingleCompanyUrl: window.BaseRoute + window.controllerCompany + 'reads/v1/{company}',
		updateCompanyUrl: window.BaseRoute + window.controllerCompany + 'update/v1',
		createCompanyUrl: window.BaseRoute + window.controllerCompany + 'create/v1',
		getCompanyGroupUrl: window.BaseRoute + window.controllerCompany + 'readGroups/v1'
	};

	window.__env.RequirementSheet = {
		requirementSheetUrl: window.BaseRoute + window.controllerRequirementSheet + 'reads/v1'
	};

	window.__env.Form = {
		CREATE: 'formCreate',
		EDIT: 'formEdit',
		INFO: 'formInfo',
		DELETE: 'formDelete',
		COPY: 'formCopy',
		CAPTION: 'formCaption',
		MESSAGE: 'formMessage',
		CONTROL: 'formControl'
	};

	window.__env.Days = {
		MONDAY: 'L',
		TUESDAY: 'K',
		WEDNESDAY: 'M',
		THURSDAY: 'J',
		FRIDAY: 'V',
		SATURDAY: 'S',
		SUNDAY: 'D'
	};

	window.__env.DaysLong = {
		MONDAY: "Lunes",
		TUESDAY: "Martes",
		WEDNESDAY: "Miércoles",
		THURSDAY: "Jueves",
		FRIDAY: "Viernes",
		SATURDAY: "Sábado",
		SUNDAY: "Domingo"
	};

	window.__env.TranslateDaysLongToEnglish = function (day) {
		for (let prop in __env.DaysLong) {
			if (__env.DaysLong[prop].toLowerCase() === day.toLowerCase()) {
				return prop;
			}
		}
		return undefined;
	};

	window.__env.GetDayShortName = function (day) {
		for (let prop in __env.DaysLong) {
			if (__env.DaysLong[prop].toLowerCase() === day.toLowerCase()) {
				return __env.Days[prop];
			}
		}
		return undefined;
	};

	window.__env.GetDayShortNameByNumber = function (day) {
		let count = 1;
		for (let prop in __env.Days) {
			if (count === day) {
				return __env.Days[prop];
			}
			count++;
		}
		return undefined;
	};

	window.__env.AssignOfficerType = {
		EXCHANGE: "IN",
		REPLACEMENT: "RP",
		TRANSFER: "TS",
		REMOVE: "RM"

	};

	window.__env.GetAssignOfficerTypeName = function (type) {
		switch (type) {
			case __env.AssignOfficerType.EXCHANGE: return 'Intercambio';
			case __env.AssignOfficerType.REPLACEMENT: return 'Reemplazo';
			case __env.AssignOfficerType.TRANSFER: return 'Traslado';
			case __env.AssignOfficerType.REMOVE: return 'Removido';
			default: return '';
		}
	};

	window.__env.DayType = {
		DAY: 'D',
		MIXED: 'M',
		NIGHT: 'N',
		INACTIVE: 'I',
		FREE: 'L'
	};

	window.__env.GetDayClass = function (type) {
		switch (type) {
			case __env.DayType.DAY: return 'day';
			case __env.DayType.MIXED: return 'mixed';
			case __env.DayType.NIGHT: return 'night';
			case __env.DayType.INACTIVE: return 'inactive';
			default: return 'free';
		}
	};

	window.__env.GetDayName = function (type) {
		switch (type) {
			case __env.DayType.DAY: return 'Diurno';
			case __env.DayType.MIXED: return 'Mixto';
			case __env.DayType.NIGHT: return 'Nocturno';
			case __env.DayType.INACTIVE: return 'Inactivo';
			default: return 'Libre';
		}
	};

	window.__env.ApplyStatusClass = function (item) {
		if (item) {
			switch (item.status) {
				case __env.Status.NOTAPPROVED:
				case __env.Status.UPDOWN:
					return 'label label-danger';
				case __env.Status.EDITED:
					return 'label label-warning';
				case __env.Status.NEW:
					return 'label label-primary';
				case __env.Status.SUSPENDED:
					return 'label label-danger';
				default:
					return '';
			}
		}
	};

	window.__env.WorkingDaySettings = [];

	window.__env.WorkingDaySettingsConstants = {
		FACTOR_DAY: "FactorDiurno",
		FACTOR_MIXED: "FactorMixto",
		FACTOR_NIGHT: "FactorNocturno",
		HOURS_DAY: "HorasDiurno",
		HOURS_MIXED: "HorasMixto",
		HOURS_NIGHT: "HorasNocturno",
		START_DAY: "InicioDiurno",
		START_MIXED: "InicioMixto",
		START_NIGHT: "InicioNocturno",
		WORKED_PER_MONTH: "DiasLaboradosXMes",
		BASE_SALARY: "MontoSalarioBase"
	};

	window.__env.RoleAssignSettings = [];
	window.__env.PersonalActionSettingsConstants = {
		DIRECT: "AccionDirecta",
		NO_ACTION: "NoGenerarAccion",
		DISTRIBUTION: "GenerarDistribucion"
	};

	window.__env.ReceptionSettings = [];
	window.__env.ReceptionSettingsConstants = {
		RECEPTION_PREVIUS_DAYS: "RecibeEnDiasAnteriores"
	};

	window.__env.GetSettingFromArray = GetSetting;
	function GetSetting(array, name, companyGroup) {
		if (array[companyGroup] && array[companyGroup].length > 0) {
			var found = array[companyGroup].find(item => item.key === name);
			if (found) {
				if (!isNaN(parseInt(found.value))) {
					found.value = RemoveCommasFromNumber(found.value);
					if (found.value.indexOf('.') === -1) {
						return parseInt(found.value);
					}
					else {
						return parseFloat(found.value);
					}
				}
				else {
					return found.value;
				}
			}
		}
	}

	window.__env.GetValueFromSetting = GetValueFromSetting;
	function GetValueFromSetting(setting) {
		if (setting) {
			if (!isNaN(parseInt(setting.value))) {
				setting.value = RemoveCommasFromNumber(setting.value);
				if (setting.value.indexOf('.') === -1) {
					return parseInt(setting.value);
				}
				else {
					return parseFloat(setting.value);
				}
			}
			else {
				return setting.value;
			}
		}
	}

	function RemoveCommasFromNumber(value) {
		let pos = 0;
		let commaCount = -1;
		let i = -1;
		while (pos !== -1) {
			pos = value.indexOf(",", i + 1);
			commaCount += 1;
			i = pos;
		}

		pos = 0;
		let dotCount = -1;
		i = -1;
		while (pos !== -1) {
			pos = value.indexOf(".", i + 1);
			dotCount += 1;
			i = pos;
		}

		if ((commaCount === 0 && dotCount === 0) || (commaCount === 0 && dotCount === 1)) return value; //is int or right decimal separator
		if (commaCount === 1 && dotCount === 0) return value.replace(',', '.'); //comma is decimal separator
		if (commaCount === 1 && dotCount === 1) {
			// 3,450.23 or 3.450,23
			let commaPos = value.indexOf(",");
			let dotPos = value.indexOf(".");
			if (commaPos < dotPos) {
				//3,450.23
				return value.replace(',', '');
			}
			else {
				// 3.450,23
				value = value.replace('.', '');
				return value.replace(',', '.'); //comma is decimal separator
			}
		}
		if (commaCount > 1 && (dotCount === 1 || dotCount === 0)) {
			// 3,400,450.23 or 3,400,450
			return value.replaceAll(',', ''); //comma is decimal separator
		}
		if (dotCount > 1 && (commaCount === 1 || commaCount === 0)) {
			// 3.400.450,23 or 3.400.450
			value = value.replace(/\./g, '');
			return value.replace(',', '.'); //comma is decimal separator
		}
	}

	//function GetSetting(array, name) {
	//	if (array && array.length > 0) {
	//		var found = array.find(item => item.key === name);
	//		if (found) {
	//               if (parseInt(found.value) !== NaN) {
	//                   //let decimalSeparator = __env.GetDecimalSeparator();
	//                   let isParseFloatValid = found.value.indexOf('.') >= 0;
	//                   if (!isParseFloatValid && decimalSeparator !== __env.ServerDecimalSeparator) {
	//                       isParseFloatValid = found.value.indexOf(__env.ServerDecimalSeparator) >= 0;
	//                       if (isParseFloatValid) {
	//                           found.value = found.value.replace(__env.ServerDecimalSeparator, decimalSeparator);
	//                       }
	//                   }
	//                   if (isParseFloatValid) {
	//                       return parseFloat(found.value);
	//				}
	//				else {
	//                       return parseInt(found.value);
	//				}
	//			}
	//			else {
	//				return found.value;
	//			}
	//		}
	//	}
	//}

	window.__env.BusinessCard = {
		softlandGetClientsUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllClients',
		softlandGetClientsByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllClientsByCompany',
		softlandGetContractTypeByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllContractTypeByCompany',
		softlandGetFrequencyByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllFrequencyByCompany',

		acaGetAllSectorsUrl: window.BaseRoute + window.controllerBusinessCard + 'GetAllSectors',
		acaGetBusinessCardsUrl: window.BaseRoute + window.controllerBusinessCard + 'reads/v1',
		acaPostBusinessCardUrl: window.BaseRoute + window.controllerBusinessCard + 'create/v1',
		acaPutBusinessCardUrl: window.BaseRoute + window.controllerBusinessCard + 'update/v1',
		acaApproveBusinessCardUrl: window.BaseRoute + window.controllerBusinessCard + 'approved/v1',
		acaDeleteBusinessCardUrl: window.BaseRoute + window.controllerBusinessCard + 'delete/v1',
		acaGetApprovedBusinessCardsByCompanyUrl: window.BaseRoute + window.controllerBusinessCard + 'reads/approved',
		alpha: {
			softlandGetCostCenterByCompany: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllCostCenterByCompany',
			softlandGetSubSectorByCompany: window.BaseRoute + window.controllerSoftlandQueries + 'GetSubSectorByCompany',
			concept: {
				softlandGetConceptsByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllConceptsByCompany'
			},
			supply: {
				softlandGetSuppliesByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllSuppliesByCompany'
			},
			service: {
				softlandGetServicesByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllServicesByCompany',
				softlandGetZonesByCompanyUrl: window.BaseRoute + window.controllerSoftlandQueries + 'GetAllZonesByCompany',
				softlandGetContractsByCompanyByClientUrl: window.BaseRoute + window.controllerSoftlandQueries + 'reads/contracts',
				GetServiceType: window.BaseRoute + window.controllerAlpha + 'reads/servicetype/v1',
				alpha_DelService: window.BaseRoute + window.controllerAlpha + 'delete/service/v1'
			},
			preassignment: {
				acaPutPreassignmentUrl: window.BaseRoute + window.controllerAlpha + 'PutPreassignment',
				processCompanychange: window.BaseRoute + window.controllerAlpha + 'ProcessCompanyChange'
			},
			assignment: {
				DeleteAassignmentUrl: window.BaseRoute + window.controllerAlpha + 'delete/Assignment/v1',
				CancelRemoveUrl: window.BaseRoute + window.controllerAlpha + 'Cancel/Remove/v1'
			},
			acaAllGetAlphasUrl: window.BaseRoute + window.controllerAlpha + 'GetAllAlphasByBusinessCard',
			acaAllGetAlphasManagerUrl: window.BaseRoute + window.controllerAlpha + 'GetAllAlphasByBusinessCardAndManager',
			acaAllGetAlphasCompleteUrl: window.BaseRoute + window.controllerAlpha + 'GetAllAlphasByBusinessCardComplete',
			acaAllGetNotApprovedAlphasCompleteUrl: window.BaseRoute + window.controllerAlpha + 'GetAllNotApprovedAlphasByBusinessCardComplete',
			acaGetApprovedAlphasUrl: window.BaseRoute + window.controllerAlpha + 'GetAllApprovedAlphasByBusinessCard',
			acaAllGetAlphasReport: window.BaseRoute + window.controllerAlpha + 'GetAllAlphasReport',
			acaGetAlphaUrl: window.BaseRoute + window.controllerAlpha + 'GetAlpha',
			acaPostAlphaUrl: window.BaseRoute + window.controllerAlpha + 'PostAlpha',
			acaPutAlphaUrl: window.BaseRoute + window.controllerAlpha + 'PutAlpha',
			acaUpDownAlpha: window.BaseRoute + window.controllerAlpha + 'UpDownAlpha',
			acaDelAlpha: window.BaseRoute + window.controllerAlpha + 'delete/alpha/v1',
			acaApproveAlpha: window.BaseRoute + window.controllerAlpha + 'approve/alpha/v1',
			acaActivateAlpha: window.BaseRoute + window.controllerAlpha + 'activate/alpha/v1',
			acaGetAlphaStatusUrl: window.BaseRoute + window.controllerAlpha + 'GeAllAlphaStatus',
			acaPrintAlphaUrl: window.BaseRoute + window.controllerAlpha + 'PrintAlpha'
		}
	};

	window.__env.Settings = {
		CONCEPT_BASESALARY: "ConceptoSalarioBase",
		CATEGORY_WORKINGDAY: "Jornada",
		CATEGORY_CONSECUTIVE_ORDER: "TemporalPedido",
		CATEGORY_CONSECUTIVE_CONTRACT: "TemporalContrato",
		CATEGORY_RECEPTION: "Recepción",
		GENERAL_ALPHAVMA: "AlfaVMA",
		LUNCHCOVER_PROGRAM_TIME_RANGE: 'TiempoProgramacionCubreAlmuerzo',
		LUNCHCOVER_TIME_TO_COVER: 'HorasACubrir',
		VACATION_PROGRAM_TIME_RANGE: 'TiempoProgramacionCubreVacacion',
		GetAppSettingsByName: window.BaseRoute + window.controllerSettings + 'GetAppSettingsByName',
		GetAppSettingsByCategory: window.BaseRoute + window.controllerSettings + 'GetAppSettingsByCategory',
		GetNextTempCode: window.BaseRoute + window.controllerSettings + 'reads/tmpcode',
		GetAppSettingsActions: window.BaseRoute + window.controllerSettings + 'GetAppSettingsActions',
		GetAppSettingsCheckActions: window.BaseRoute + window.controllerSettings + 'GetAppSettingsCheckActions'
	};

	window.__env.Status = {
		NEW: 'Nuevo',
		APPROVED: 'Aprobado',
		NOTAPPROVED: 'No Aprobado',
		SUSPENDED: 'Suspendido',
		CANCELLED: 'Anulado',
		EDITED: 'Modificado',
		UPDOWN: 'Alta/Baja',
		ACTIVE: 'Activo',
		INACTIVE: 'Inactivo'
	};

	window.__env.FormMode = {
		CREATEALPHA: 'CreateAlpha',
		EDITCARD: 'EditCard',
		CREATECARD: 'CreateCard',
		EDITALPHA: 'EditAlpha',
		SHOWCARD: 'ShowCard',
		ACTIVATE: 'activate',
		APPROVE: 'approve',
		ERROR: 'error',
		UPDOWN: 'UpDown',
		NONE: 'None',
		CREATE: 'CREATE',
		UPDATE: 'UPDATE',
		READONLY: 'READONLY',
		CONTENT: 'CONTENT'
	};

	window.__env.ModalSize = {
		LARGE: 'lg',
		SMALL: 'sm',
		MEDIUM: 'md'
	};

	window.__env.ConceptType = {
		BusinessCard: 'F',
		Closing: 'C',
		LateArriving: 'T'
	};

	//window.__env.Company = {
	//	VMACOMER: 'VMACOMER',
	//	VMACOND: 'VMACOND',
	//	VMAELECTRO: 'VMAELECTRO',
	//	VMASERV: 'VMASERV',
	//	VMATOTAL: 'VMATOTAL',
	//	VMAUNO: 'VMAUNO',
	//	VMACompanyList: function () {
	//		var companyList = [];
	//		companyList.push(window.__env.Company.VMACOMER);
	//		companyList.push(window.__env.Company.VMACOND);
	//		companyList.push(window.__env.Company.VMAELECTRO);
	//		companyList.push(window.__env.Company.VMASERV);
	//		companyList.push(window.__env.Company.VMATOTAL);
	//		companyList.push(window.__env.Company.VMAUNO);
	//		return companyList;
	//	}
	//};

	window.__env.dateFormat = 'dd/MM/yyyy';
	window.__env.holder = 'DD/MM/YYYY';
	window.__env.mask = '99/99/9999';
	window.__env.format = 'ddMMyyyy';

	window.__env.ServerDecimalSeparator = '.';
	window.__env.CurrencySymbol = '₡ ';
	window.__env.CurrencyDecimals = 2;

	window.__env.timeFormat = window.__env.dateFormat + ' h:mm:ss a';

	window.__env.pickListSize = 6;

	window.__env.gridItemsByPage = 20;

	window.__env.updateMainTitle = 'UpdateMainTitle';
	window.__env.modalMessage = 'ModalMainMessage';
	//drop down
	window.__env.automaticDropDownSearch = 16;

	window.__env.timePicker = {
		format: 'hh:mm a',
		size: 5,
		minuteSteps: 5
	};

	// Whether or not to enable debug mode
	// Setting this to false will disable console output
	window.__env.enableDebug = false;

	window.__env.RemoveUsedValuesFromArray = filter;

	function filter(availableArray, selectedArray) {
		var temporalRoles = [];
		availableArray.forEach(function (available) {
			var exists = false;
			selectedArray.forEach(function (user) {
				if (available.id === user.id) {
					exists = true;
				}
			});

			if (!exists) {
				temporalRoles.push(available);
			}
		});
		return temporalRoles;
	}
	window.__env.createNewLettersArray = filter2;

	function filter2(originalLetters, selectedLetters, controlLetters, matrix, rowIndex, columnIndex) {
		var excessQty = false;
		var newArray = [];

		originalLetters.forEach(function (originalLetter) {
			var letterExist = false;
			if (selectedLetters !== undefined && selectedLetters.length > 0) {
				selectedLetters.forEach(function (selectedLetter) {
					if (originalLetter.letter === selectedLetter.letter) {
						letterExist = true;
						return;
					}
				});
			} else {
				letterExist = false;
			}

			if (originalLetter.directOfficer) {
				controlLetters.forEach(function (controlLetter) {
					if (originalLetter.letter === controlLetter.letter) {

						if (controlLetter.qtyUsed <= controlLetter.workedDays) {
							if (controlLetter.qtyUsed === controlLetter.workedDays) {
								return;
							}

							var previewsSelected = false;
							for (var i = 0; i < matrix.length; i++) {
								if (i === rowIndex) {
									continue;
								}
								var rowCell = matrix[i][columnIndex];
								if (rowCell) {
									for (var j = 0; j < rowCell.length; j++) {
										var letterCell = rowCell[j];
										if (letterCell.letter === originalLetter.letter) {
											previewsSelected = true;
											break;
										}
									}
								}
								if (previewsSelected) {
									break;
								}
							}

							if (!previewsSelected) {
								newArray.push(originalLetter);
							}
						}
						if (letterExist) {
							controlLetter.qtyUsed++;
						}
						return;
					}
				});
			} else {
				newArray.push(originalLetter);
			}

		});
		return newArray;
	}
	window.__env.RemoveUsedSoftlandValuesFromArray = filterSoftlandId;

	function filterSoftlandId(availableArray, selectedArray) {
		var temporalRoles = [];
		availableArray.forEach(function (available) {
			var exists = false;
			selectedArray.forEach(function (user) {
				if (available.id === user.softlandId) {
					exists = true;
				}
			});

			if (!exists) {
				temporalRoles.push(available);
			}
		});
		return temporalRoles;
	}

	window.__env.RemoveError = RemoveError;

	function RemoveError(errorlist, ERROR) {
		if (errorlist.length > 0) {
			errorlist.splice(errorlist.indexOf(ERROR), 1);
		}
	}

	window.__env.FilterNumberInput = FilterNumberInput;

	function FilterNumberInput(e) {
		// Allow: backspace, delete, tab, escape, enter and .
		if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1)
			return;

		if (e.ctrlKey === true || e.metaKey === true) {
			// Allow: Ctrl/cmd+A
			if (e.keyCode === 65)
				return;
			// Allow: Ctrl/cmd+C
			if (e.keyCode === 67)
				return;
			// Allow: Ctrl/cmd+X
			if (e.keyCode === 88)
				return;
		}

		// Allow: home, end, left, right
		if (e.keyCode >= 35 && e.keyCode <= 39) {
			// let it happen, don't do anything
			return;
		}

		//if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
		//	// Allow: Ctrl/cmd+A
		//    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
		//	// Allow: Ctrl/cmd+C
		//    (e.keyCode === 67 && (e.ctrlKey === true || e.metaKey === true)) ||
		//	// Allow: Ctrl/cmd+X
		//    (e.keyCode === 88 && (e.ctrlKey === true || e.metaKey === true)) ||
		//	// Allow: home, end, left, right
		//(e.keyCode >= 35 && e.keyCode <= 39)) {
		//	// let it happen, don't do anything
		//	return;
		//}
		// Ensure that it is a number and stop the key press
		if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
			e.preventDefault();
		}
	}

	window.__env.HandlePasteInputNumber = HandlePasteInputNumber;

	function HandlePasteInputNumber(e) {
		var clipboardData, pastedData;

		// Get pasted data via clipboard API
		clipboardData = e.clipboardData || window.clipboardData;
		pastedData = clipboardData.getData('Text').toUpperCase();

		if (pastedData.indexOf('E') > -1) {
			//alert('found an E');
			e.stopPropagation();
			e.preventDefault();
		}
	}

	window.__env.DateToAPI = DateToAPI;
	function DateToAPI(date) {
		if (date) {
			if (moment.isDate(date)) {
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);
				date.setMilliseconds(0);
			}

			return date.toISOString();
		}
		return date;
	}

	window.__env.DateFromAPI = DateFromAPI;
	function DateFromAPI(date) {
		if (date !== undefined && date !== null) {
			let b = date.split(/\D+/);
			// b[5], b[6] were removed to avoid seconds and milliseconds to be displayed in the hours
			//return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4]), b[5], b[6]));
			return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4]));
		}
		return undefined;
	}

	window.__env.DateFromAPISoftland = DateFromAPISoftland;
	function DateFromAPISoftland(date) {
		if (date !== undefined && date !== null) {
			let b = date.split(/\D+/);
			// b[5], b[6] were removed to avoid seconds and milliseconds to be displayed in the hours
			//return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4]), b[5], b[6]));
			return new Date(b[0], --b[1], b[2], b[3], b[4]);
		}
		return undefined;
	}

	window.__env.TimeToAPIKeepDay = TimeToAPIKeepDay;
	function TimeToAPIKeepDay(date) {
		if (date) {
			if (moment.isDate(date)) {
				var today = new Date();
				today.setHours(date.getHours());
				today.setMinutes(date.getMinutes());
				today.setSeconds(date.getSeconds());
				today.setMilliseconds(0);
				let day = date.getDate();
				if (day === 1 || day === 2) {
					today.setDate(day);
				}
				else {
					today.setDate(1);
				}
				today.setMonth(0);
				today.setFullYear(2017);
				return today.toISOString();
			}
		}
		return date;
	}

	window.__env.TimeToAPI = TimeToAPI;
	function TimeToAPI(date) {
			if (date) {
				if (moment.isDate(date)) {
					var today = new Date();
					today.setHours(date.getHours());
					today.setMinutes(date.getMinutes());
					today.setSeconds(date.getSeconds());
					today.setMilliseconds(0);
					today.setDate(1);
					today.setMonth(0);
					today.setFullYear(2017);
					return today.toISOString();
				}
			}
			return date;
		}

	window.__env.GetStringApiTime = GetStringApiTime;
	function GetStringApiTime(date, format) {
		if (moment.isDate(date)) {
			var today = "";
			today = moment(date).format("hh:mm a");
			if (format !== undefined) {
				today = moment(date).format(format);
			}
			return today;
		}
		return "Error de fecha";
	}

	window.__env.GetTimeWithOutGTM = GetTimeWithOutGTM;
	function GetTimeWithOutGTM(value, format) {
		if (!moment.isDate(value)) {
			value = window.__env.DateFromAPI(value);
		}
		return window.__env.GetStringApiTime(value, format);
	}

	window.__env.Guid = Guid;
	function Guid() {
		function s4() {
			return Math.floor((1 + Math.random()) * 0x10000)
				.toString(16)
				.substring(1);
		}
		return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
	}

	window.__env.CheckIsNumber = CheckIsNumber;
	function CheckIsNumber(value) {
		if (value !== undefined && !isNaN(value) && value !== null && value !== "") {
			if (angular.isNumber(value)) {
				return true;
			}
		}
		return false;
	}

	window.__env.Round = Round;
	function Round(value) {
		return Math.abs(Math.round(value * 100) / 100);
	}

	window.__env.GetDecimalSeparator = GetDecimalSeparator;
	function GetDecimalSeparator() {
		//fall back
		let decSep = ".";

		try {
			// this works in FF, Chrome, IE, Safari and Opera
			var sep = parseFloat(3 / 2).toLocaleString().substring(1, 2);
			if (sep === '.' || sep === ',') {
				decSep = sep;
			}
		} catch (e) { decSep = "."; }

		return decSep;
	}

	//prototypes
	Array.prototype.removeAtIndex = function (array, index) {
		var len = array.length;
		if (!len) { return; }
		while (index < len) {
			array[index] = array[index + 1];
			index++;
		}
		array.length--;
	};
	// check if an element exists in array using a comparer function
	// comparer : function(currentElement)
	Array.prototype.inArray = function (comparer) {
		for (var i = 0; i < this.length; i++) {
			if (comparer(this[i])) return true;
		}
		return false;
	};
	// adds an element to the array if it does not already exist using a comparer
	// function
	Array.prototype.pushIfNotExist = function (element, comparer) {
		if (!this.inArray(comparer)) {
			this.push(element);
		}
	};

	//return an description about personal action state
	window.__env.pActionStateName = pActionStateName;
	function pActionStateName(value) {
		switch (value) {
			case "A":
				return "Aprobada";
			case "H":
				return "Anulada";
			case "N":
				return "No Aprobada";
			case "S":
				return "Aplicada";
			case "V":
				return "Vigente";
			case "P":
				return "Pendiente";
		}
	}

	//return an description about personal action state
	window.__env.receptionTypeName = receptionTypeName;
	function receptionTypeName(value) {
		switch (value) {
			case window.__env.closingState.stateP:
				return "Presente";
			case window.__env.closingState.stateA:
				return "Ausente";
			case window.__env.closingState.stateS:
				return "Ausente";
			case window.__env.closingState.stateT:
				return "Tardía";
			case window.__env.closingState.stateNA:
				return "No Asignado";
		}
	}

	//return an description about personal action state
	window.__env.personalActionTypeName = personalActionTypeName;
	function personalActionTypeName(value) {
		switch (value) {
			case window.__env.pActionStateConst.stateA:
				return "Aprobado";
			case window.__env.pActionStateConst.stateH:
				return "Anulado";
			case window.__env.pActionStateConst.stateN:
				return "No Aprobado";
			case window.__env.pActionStateConst.stateS:
				return "Aplicado";
			case window.__env.pActionStateConst.stateP:
				return "Pendiente";
			case window.__env.pActionStateConst.stateC:
				return "";
			case window.__env.pActionStateConst.stateU:
				return "";
			case window.__env.pActionStateConst.stateD:
				return "";
		}
	}


	//return an description about personal action state
	window.__env.closingStatusRevision_GetName = closingStatusRevision_GetName;
	function closingStatusRevision_GetName(value) {
		switch (value) {
			case window.__env.closingState.stateP:
				return window.__env.closingState.statePendding;
			case window.__env.closingState.stateA:
				return window.__env.closingState.stateApproved;
			case window.__env.closingState.stateS:
				return window.__env.closingState.stateApplied;
		}
	}

	//return an description about personal action state
	window.__env.pActionStateConst = {
		stateA: "A",
		stateH: "H",
		stateN: "N",
		stateS: "S",
		stateV: "V",
		stateP: "P",
		stateC: "C",
		stateU: "U",
		stateD: "D"
	};

	window.__env.Place = {
		freeCover: "08",
		launchCover: "09",
		incapacitated: "49"
	};

	window.__env.closingState = {
		stateA: "A",
		stateS: "S",
		stateN: "N",
		stateNA: "NA",
		stateP: "P",
		stateT: "T",
		statePendding: "Pendiente",
		stateNotApproved: "No Aprobado",
		stateApproved: "Aprobado",
		stateApplied: "Aplicado",
		operationR: "R",
		operationP: "P",
		operationReception: "Recibimiento",
		operationPlaceTo: "Puesto por Cubrir",
		statePresent: "Presente",
		stateAbsence: "Ausente",
		stateLate: "Tarde",
		stateAbsenceUnjustifiedType: "Injustificada",
		stateAbsenceUnjustified: "INJ",
		stateAbsenceType: "Ausencia",
		stateNotAssignedType: "No Asignado"
	};

	window.__env.typeMessage = {
		typeW: "Warning",
		typeD: "Danger",
		typeS: "Success"
	};

	window.__env.Has = {
		Yes: "YES",
		No: "NO"
	};

	window.__env.AssignStatus = {
		Complete: "Completa",
		Vacancy: "Vacante",
		Shared: "Compartido",
		NotPerformed: "No realizada",
		Pending: "Acciones Pendientes",
		Partial: "Parcial"
	};

	window.__env.AssignScheduleStatus = {
		Complete: "Completo",
		incomplete: "Incompleto"
	};

	window.__env.StatusCode = {
		//Information responses
		Continue: 100,
		SwitchingProtocols: 101,
		//Successful responses
		OK: 200,
		Created: 201,
		Accepted: 202,
		NonAuthoritativeInformation: 203,
		NoContent: 204,
		ResetContent: 205,
		PartialContent: 206,
		//Redirection messages
		MultipleChoices: 300,
		Ambiguous: 300,
		MovedPermanently: 301,
		Moved: 301,
		Found: 302,
		Redirect: 302,
		SeeOther: 303,
		RedirectMethod: 303,
		NotModified: 304,
		UseProxy: 305,
		Unused: 306,
		TemporaryRedirect: 307,
		RedirectKeepVerb: 307,
		//Client error responses
		BadRequest: 400,
		Unauthorized: 401,
		PaymentRequired: 402,
		Forbidden: 403,
		NotFound: 404,
		MethodNotAllowed: 405,
		NotAcceptable: 406,
		ProxyAuthenticationRequired: 407,
		RequestTimeout: 408,
		Conflict: 409,
		Gone: 410,
		LengthRequired: 411,
		PreconditionFailed: 412,
		RequestEntityTooLarge: 413,
		RequestUriTooLong: 414,
		UnsupportedMediaType: 415,
		RequestedRangeNotSatisfiable: 416,
		ExpectationFailed: 417,
		UpgradeRequired: 426,
		//Server error responses
		InternalServerError: 500,
		NotImplemented: 501,
		BadGateway: 502,
		ServiceUnavailable: 503,
		GatewayTimeout: 504,
		HttpVersionNotSupported: 505
	};

	//function to get true or false in constants
	window.__env.StateEval = StateEval;
	function StateEval(pConst, value) {
		if (pConst === value)
			return true;
		else
			return false;
	}

	//function to get true or false in array constants
	window.__env.Contains = Contains;
	function Contains(constant, value) {
		var result = false;
		value.forEach(function (item) {
			if (constant === item) {
				result = true;
			}
		});
		return result;
	}

	window.__env.Message = Message;
	function Message($rootScope, _args) {
		$rootScope.$broadcast(__env.modalMessage, {
			data: _args
		});
	}

	window.__env.OnSucess = OnSucess;
	function OnSucess($rootScope, message) {
		var params = __env.eventResponse();
		params.text = message;
		params.eventSuccess = true;
		__env.Message($rootScope, params);
	}

	window.__env.OnError = OnError;
	function OnError($rootScope, message) {
		var params = __env.eventResponse();
		params.value = message;
		params.eventError = true;
		__env.Message($rootScope, params);
	}

	window.__env.OnWarning = OnWarning;
	function OnWarning($rootScope, message) {
		var params = __env.eventResponse();
		params.text = message;
		params.eventWarning = true;
		__env.Message($rootScope, params);
	}

	window.__env.eventResponse = function () {
		return new Object({ value: undefined, eventSuccess: undefined, eventError: undefined, eventWarning: undefined, text: undefined });
	};

	window.__env.requestDto = function () {
		this.from = null;
		this.to = null;
		this.identifier = null;
		this.today = null;
		this.date = null;
		this.zoneVMA = null;
		this.placesVMA = null;
		this.sections = null;
		this.tables = null;
		this.company = null;
		this.clientId = null;
		this.idCard = null;
		this.centerCost = null;
		this.companyGroup = null;
	};

	window.__env.NewModal = NewModal;
	function NewModal(name) {
		return new Modal(name);
	}

	function Modal(name) {
		let modal = Object.create(this);
		modal.name = name;

		modal.Show = Show;
		modal.Hide = Hide;
		modal.Refresh = Refresh;
		Initialize();

		return modal;

		function Show(title, size) {
			modal.title = title;
			modal.size = size;
			modal.showModalContent = true;
			if (modal.ShowCustom) {
				modal.ShowCustom(arguments);
			}
			$('#' + this.name).modal('show');
		}

		function Hide() {
			Initialize();
			if (modal.HideCustom) {
				modal.HideCustom(arguments);
			}
			$('#' + this.name).modal('hide');
		}

		function Refresh(blockUI) {
			blockUI.start();
			let form = $('#' + this.name);
			form.modal('hide');
			$timeout(function () {
				form.modal('show');
				blockUI.stop();
			}, 2000);
			//$('#' + this.name).modal('show');
		}

		function Initialize() {
			modal.size = __env.ModalSize.MEDIUM;
			modal.title = '';
			modal.showModalContent = false;
			modal.caption = '';
			modal.buttonCaption = '';
			if (modal.InitializeCustom) {
				modal.InitializeCustom(arguments);
			}
		}
	}

	window.__env.sortByMultipleKey = sortByMultipleKey;
	function sortByMultipleKey(keys) {
		return function (a, b) {
			if (keys.length === 0) return 0; // force to equal if keys run out
			let key = keys[0]; // take out the first key
			if (a[key] !== undefined || b[key] !== undefined) {
				if (typeof a[key] === "boolean") {
					// variable is a boolean
					if (a[key] < b[key]) return 1; // will be 1 if DESC
					else if (a[key] > b[key]) return -1; // will be -1 if DESC
					else return sortByMultipleKey(keys.slice(1))(a, b);
				}
				else {
					if (a[key] < b[key]) return -1; // will be 1 if DESC
					else if (a[key] > b[key]) return 1; // will be -1 if DESC
					else return sortByMultipleKey(keys.slice(1))(a, b);
				}
			}
			else {
				return sortByMultipleKey(keys.slice(1))(a, b);
			}
		};
	}

	window.__env.modalForm = function () {
		this.name = undefined,
			this.title = 'Formulario',
			this.show = false,
			this.readonly = false,
			this.size = __env.ModalSize.LARGE;
		this.save = undefined;
		this.cancel = undefined;
	};

	window.__env.Subscription = Subscription;
	function Subscription(List) {
		let subscriptionList = [];
		let internal = {};

		internal.Subscribe = Subscribe;
		internal.Unsubscribe = Unsubscribe;
		internal.TriggerCallbacks = TriggerCallbacks;

		for (let prop in List) {
			CreatePool(List[prop]);
		}

		return internal;

		//objects
		function SubscriptionItem(poolName) {
			this.poolName = poolName;
			this.poolList = [];
		}

		function CallBackItem(caller, callback) {
			this.caller = caller;
			this.callback = callback;
		}

		//private methods
		function RegisterCallback(array, callBackItem) {
			if (array.indexOf(callBackItem) === -1) {
				array.push(callBackItem);
			}
			//let item = array.find(x => x.caller === callBackItem.caller);
			//if (!item) {
			//	array.push(callBackItem);
			//}
		}

		function RemoveCallback(array, caller) {
			let item = array.find(x => x.caller === caller);
			if (item) {
				var index = array.indexOf(item);
				if (index > -1) {
					array.splice(index, 1);
				}
			}
		}

		//public methods
		function CreatePool(poolName) {
			subscriptionList.push(new SubscriptionItem(poolName));
		}

		function Subscribe(caller, poolName, callback, executeCallback = false) {
			let callbackItem = new CallBackItem(caller, callback);
			if (subscriptionList) {
				let item = subscriptionList.find(subscriptionItem => subscriptionItem.poolName === poolName);
				if (item) {
					RegisterCallback(item.poolList, callbackItem);
					if (executeCallback !== undefined && executeCallback) {
						callback();
					}
				}
			}
		}

		function Unsubscribe(caller, poolName) {
			if (subscriptionList) {
				let item = subscriptionList.find(subscriptionItem => subscriptionItem.poolName === poolName);
				if (item) {
					RemoveCallback(item.poolList, caller);
				}
			}
		}

		function TriggerCallbacks(poolName, params) {
			let subscriptionItem = subscriptionList.find(subscriptionItem => subscriptionItem.poolName === poolName);
			if (subscriptionItem) {
				subscriptionItem.poolList.forEach(callback => {
					if (params) {
						callback.callback(params);
					}
					else {
						callback.callback();
					}
				});
			}
		}
	}

	window.__env.selectTranslation = function () {
		this.checkAll = "Todos";
		this.uncheckAll = "Quitar";
		this.buttonDefaultText = "------Seleccionar -------";
		this.dynamicButtonTextSuffix = "----Seleccionados----";
	};

	window.__env.selectSettings = function () {
		this.buttonClasses = "form-control input-sm";
		this.scrollableHeight = '200px';
		this.scrollable = true;
	};

	window.__env.scheduleDetail = function () {
		this.show = false;
		this.mon_text = "Lunes";
		this.dayId_1 = 1;
		this.rows_day_1 = [];
		//
		this.tue_text = "Martes";
		this.dayId_2 = 2;
		this.rows_day_2 = [];
		//
		this.wed_text = "Miércoles";
		this.dayId_3 = 3;
		this.rows_day_3 = [];
		//
		this.thu_text = "Jueves";
		this.dayId_4 = 4;
		this.rows_day_4 = [];
		//
		this.fri_text = "Viernes";
		this.dayId_5 = 5;
		this.rows_day_5 = [];
		//
		this.sat_text = "Sábado";
		this.dayId_6 = 6;
		this.rows_day_6 = [];
		//
		this.sun_text = "Domingo";
		this.dayId_7 = 7;
		this.rows_day_7 = [];
	};

	window.__env.timeRange = timeRange;
	function timeRange(start, end, compareStart, CompareEnd) {
		let result = false;
		// time of first timespan
		let x = start.getTime();
		let y = end.getTime();
		// time of second timespan
		let a = compareStart.getTime();
		let b = CompareEnd.getTime();

		if (Math.min(x, y) <= Math.max(a, b) && Math.max(x, y) >= Math.min(a, b)) {
			result = true;
		}
		return result;
	}

	window.__env.GetACADayOfWeek = GetACADayOfWeek
	function GetACADayOfWeek(date)
	{
		if (date.getDay() === 0) {
			return 7;
		}
		return date.getDay();
	}

	window.__env.concetps = {
		BQ07: "BQ07",
		BQ08: "BQ08",
		BQ09: "BQ09"
	};

	window.__env.ModeControl = {
		CREATE: "CREATE",
		PARTIALEDIT: "PARTIALEDIT",
		TOTALEDIT: "TOTALEDIT",
		READONLY: "READONLY",
		UPDOWN: "UPDOWN"
	};

	window.__env.ServiceType = {
		REGULAR: "SR0001",
		ESPECIAL: "SR0002"
	};

	window.__env.rolesType = {
		approveOverTime: "A_OvertTime"
	};

	String.prototype.format = function (args) {
		var str = this;
		return str.replace(String.prototype.format.regex, function (item) {
			var intVal = parseInt(item.substring(1, item.length - 1));
			var replace;
			if (intVal >= 0) {
				replace = args[intVal];
			} else if (intVal === -1) {
				replace = "{";
			} else if (intVal === -2) {
				replace = "}";
			} else {
				replace = "";
			}
			return replace;
		});
	};
	String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");

	String.prototype.replaceAll = function (search, replacement) {
		var target = this;
		return target.replace(new RegExp(search, 'g'), replacement);
	};

	window.__env.GridHeaderItem = function GridHeaderItem(field, caption, width, options = {}) {
		this.field = field;
		this.caption = caption;
		this.width = width;

		this.sort = options.sort || false;
		this.additionalField = options.additionalField || undefined;
		this.filterType = options.filterType || undefined;
		this.fieldFormat = options.format || undefined;
		this.arrayField = options.arrayField || undefined;
		this.arrayPosition = (options.arrayPosition !== null && options.arrayPosition !== undefined) ? options.arrayPosition : undefined;
		this.arrayKey = options.arrayKey || undefined;
		this.arrayKeyValue = options.arrayKeyValue || undefined;
		this.exportField = options.exportField || undefined;
		this.objectProperty = options.objectProperty || undefined;
		this.class = options.class || "text-center";
		this.style = `width:${this.width}%; ${options.style}`;
	};

	window.__env.PrepareToExcel = function PrepareToExport(dataArray, headerArray, $filter) {
		let data = [];
		if (dataArray.length > 0 && headerArray.length > 0 && $filter) {

			let getField = function getField(item, header, subProperty) {
				let searchField = header.field;

				if (header.exportField) {
					searchField = header.exportField;
				}

				if (subProperty) {
					searchField = header.objectProperty;
                }

				if (item.hasOwnProperty(searchField)) {
					if (typeof item[searchField] === "number") {
						if (header.filterType) {
							return $filter(header.filterType)(item[searchField], __env.CurrencySymbol, __env.CurrencyDecimals);
						}
						else {
							return item[searchField];
						}
					}
					else {
						//if (typeof item[searchField] === "array") {
						//	if (header.arrayField && header.arrayPosition) {
						//		if (item[searchField][header.arrayPosition]) {
						//			if (item[searchField][header.arrayPosition][searchField]) {
						//				return item[searchField][header.arrayPosition][searchField];
						//			}
						//		}
						//	}
						//	return "";
						//}
						//else {
						if (typeof item[searchField] !== "object") {
							return item[searchField];
						}
						else {
							if (Object.prototype.toString.call(item[searchField]) === "[object Date]") {
								var day = item[searchField].getDate();
								var monthIndex = item[searchField].getMonth();
								var year = item[searchField].getFullYear();

								if (header.fieldFormat === "Hour") {
									return $filter('date')(item[searchField], window.__env.timePicker.format);
								}
								//return day + '/' + monthIndex + '/' + year;
								return $filter('date')(item[searchField], window.__env.dateFormat);
							}
							else if (Object.prototype.toString.call(item[searchField]) === "[object Array]") {
								let array = item[searchField];

								if (header.arrayPosition !== undefined && header.arrayPosition !== null) {
									return array[header.arrayPosition][header.arrayField];
								}
								else if (header.arrayKey) {
									let value = array.filter(x => x[header.arrayKey] === header.arrayKeyValue);
									if (value.length > 0) {
										return value[0][header.arrayField];
									}
								}
							}
							else if (Object.prototype.toString.call(item[searchField]) === "[object Object]") {
								return getField(item[searchField], header, true);
							}
						}
						//}
					}
				}
			};

			dataArray.forEach(item => {
				var itemToExcel = {};
				headerArray.forEach(header => {
					if (header.constructor.name === "GridHeaderItem") {
						if (header.field !== '') {
							let value = getField(item, header);
							if (header.additionalField) {
								if (header.fieldFormat) {
									value = header.fieldFormat.format([value, getField(item, header)]);
								}
								else {
									value = `${value}-${getField(item, header.additionalField)}`;
								}
							}
							itemToExcel[header.caption.split(' ').join('')] = value;
						}
					}
				});
				data.push(itemToExcel);
			});
		}
		return data;
	};

	window.__env.GetNextLetter = GetNextLetter;
	function GetNextLetter(key) {
		if (key) {
			if (key === 'Z' || key === 'z') {
				return String.fromCharCode(key.charCodeAt() - 25) + String.fromCharCode(key.charCodeAt() - 25); // AA or aa
			} else {
				let lastChar = key.slice(-1);
				let sub = key.slice(0, -1);
				if (lastChar === 'Z' || lastChar === 'z') {
					// If a string of length > 1 ends in Z/z,
					// increment the string (excluding the last Z/z) recursively,
					// and append A/a (depending on casing) to it
					return GetNextLetter(sub) + String.fromCharCode(lastChar.charCodeAt() - 25);
				} else {
					// (take till last char) append with (increment last char)
					return sub + String.fromCharCode(lastChar.charCodeAt() + 1);
				}
			}
		}
		else {
			return 'A';
		}
	}

	window.__env.ReportFilterObj = ReportFilterModel;
	function ReportFilterModel() {
		this.from = null;
		this.to = null;
		this.group = null;
		this.company = null;
		this.alpha = null;
		this.clientId = null;
		this.zone = null;
		this.sector = null;
		this.subSector = null;
		this.status = null;
		this.employee = null;
		this.concept = null;
		this.accountMgr = null;
		this.absenceType = null;
		this.vacationType = null;
		this.export = null;
	}

	Number.prototype.round = function (places) {
		return +(Math.round(this + "e+" + places) + "e-" + places);
	}

}(this));
