var DDS = {};
//Objeto de Formatação de Valores para a tela em string
DDS.Data = function (data, formato) {//o parametro data é uma datetime vindo do mvc como json, e o parametro formato tem que ser uma das listadas no Switch abaixo.
if (data === "/Date(-6847797600000)/" || data === "/Date(-62135589600000)/" || data === null || data === undefined) {// Se a data for menor que 1753 = null
formato = "";
} else {
var myDate = new Date(parseInt(data.substr(6)));
var semana = ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"];//objeto de uso interno
var semanaLongos = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];
var mesCurtos = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"];//objeto de uso interno
var mesLongos = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];//objeto de uso interno
var mesIngles = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];//objeto de uso interno
var _hor = (myDate.getHours() < 10 ? "0" : "") + myDate.getHours().toString();
var _min = (myDate.getMinutes() < 10 ? "0" : "") + myDate.getMinutes().toString();
var _seg = (myDate.getSeconds() < 10 ? "0" : "") + myDate.getSeconds().toString();
var _dia = (myDate.getDate() < 10 ? "0" : "") + myDate.getDate().toString();
var _mes = (myDate.getMonth() + 1 < 10 ? "0" : "") + (myDate.getMonth() + 1).toString();
var _ano = myDate.getFullYear().toString();
var indiceSem = myDate.getDay();
formato = formato.replace('dddd', semanaLongos[indiceSem]);
formato = formato.replace('ddd', semana[indiceSem]);
formato = formato.replace('dd', _dia);
formato = formato.replace('yyyy', _ano);
formato = formato.replace('yy', _ano.substring(2, 4));
var indiceMes = myDate.getMonth();
formato = formato.replace('MMMM', mesLongos[indiceMes]);
formato = formato.replace('MMM', mesCurtos[indiceMes]);
formato = formato.replace('MONTH', mesIngles[indiceMes]);
formato = formato.replace('MM', _mes);
formato = formato.replace('HH', _hor);
formato = formato.replace('hh', _hor);
formato = formato.replace('mm', _min);
formato = formato.replace('ss', _seg);
}
return formato;
};
DDS.Agora = function () {
var _curdate = new Date();
var d = _curdate.getDate();
if (d < 10) d = "0" + d;
var m = _curdate.getMonth() + 1;
if (m < 10) m = "0" + m;
var y = _curdate.getFullYear();
var hour = _curdate.getHours();
if (hour < 10) hour = "0" + hour;
var min = _curdate.getMinutes();
if (min < 10) min = "0" + min;
var sec = _curdate.getSeconds();
if (sec < 10) sec = "0" + sec;
return y + '-' + m + '-' + d + ' ' + hour + ':' + min + ':' + sec;
};
DDS.AgoraMask = function (mask) {
var _curdate = new Date();
var d = _curdate.getDate();
if (d < 10) d = "0" + d;
var m = _curdate.getMonth() + 1;
if (m < 10) m = "0" + m;
var y = _curdate.getFullYear();
var hour = _curdate.getHours();
if (hour < 10) hour = "0" + hour;
var min = _curdate.getMinutes();
if (min < 10) min = "0" + min;
var sec = _curdate.getSeconds();
if (sec < 10) sec = "0" + sec;
mask = mask.replace("y", y).replace("m", m).replace("d", d).replace("hour", hour).replace("min", min).replace("sec", sec);
return mask;
};
DDS.Numero = function (objeto, Decimais) {
try {
if (objeto === null || objeto=== undefined) objeto = "0";
return objeto.FormatMoney(Decimais, ',', '.');
}
catch (err) {
objeto = "0";
return objeto.FormatMoney(Decimais, ',', '.');
}
};
//Protótipo de máscara para valores financeiros
Number.prototype.FormatMoney = function (c, d, t) {
c = isNaN(c = Math.abs(c)) ? 2 : c;
d = d === undefined ? "." : d;
t = t === undefined ? "," : t;
var n = this,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
DDS.LimpaJson = function (entrada) {
if (entrada === undefined) entrada = "";
return entrada.replace('{', '').replace('}', '').replace('[', '').replace(']', '').replace('"', '').replace("'", "");
};
//Plugin para o Jquery
jQuery.fn.SoNumero = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key === 8 ||
key === 9 ||
key === 13 ||
key === 46 ||
key === 110 ||
key === 190 ||
key >= 35 && key <= 40 ||
key >= 48 && key <= 57 ||
key >= 96 && key <= 105);
});
});
};
jQuery.fn.SoNumeroSemPonto = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key === 8 ||
key === 9 ||
key === 13 ||
key === 46 ||
key >= 35 && key <= 40 ||
key >= 48 && key <= 57 ||
key >= 96 && key <= 105);
});
});
};
jQuery.fn.SoNumeroComPonto = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
if (key === 110)
return false;
return (
key === 8 ||
key === 9 ||
key === 13 ||
key === 46 ||
key === 110 ||
key === 190 ||
key === 194 ||
key >= 35 && key <= 40 ||
key >= 48 && key <= 57 ||
key >= 96 && key <= 105);
});
});
};
DDS.EhPar = function(x) { return (x % 2) === 0; };
DDS.ValEmail = function (valor) {
var x = valor;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
return false;
}
return true;
};
DDS.ValCNPJ = function (cnpj) {
cnpj = cnpj.replace(/[^\d]+/g, '');
if (cnpj === '') return false;
if (cnpj.length !== 14)
return false;
// Elimina CNPJs invalidos conhecidos
if (cnpj === "00000000000000" ||
cnpj === "11111111111111" ||
cnpj === "22222222222222" ||
cnpj === "33333333333333" ||
cnpj === "44444444444444" ||
cnpj === "55555555555555" ||
cnpj === "66666666666666" ||
cnpj === "77777777777777" ||
cnpj === "88888888888888" ||
cnpj === "99999999999999")
return false;
// Valida DVs
tamanho = cnpj.length - 2;
numeros = cnpj.substring(0, tamanho);
digitos = cnpj.substring(tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros.charAt(tamanho - i) * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado.toString() !== digitos.charAt(0))
return false;
tamanho = tamanho + 1;
numeros = cnpj.substring(0, tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros.charAt(tamanho - i) * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado.toString() !== digitos.charAt(1))
return false;
return true;
};
DDS.ValCPF = function (strCPF) {
strCPF = strCPF.replace(".", "").replace("-", "").replace(".", "");
var Soma;
var Resto;
Soma = 0;
if (strCPF === "00000000000")
return false;
for (i=1; i<=9; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i); Resto = (Soma * 10) % 11;
if ((Resto === 10) || (Resto === 11)) Resto = 0; if (Resto !== parseInt(strCPF.substring(9, 10)) )
return false;
Soma = 0; for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i); Resto = (Soma * 10) % 11;
if ((Resto === 10) || (Resto === 11)) Resto = 0; if (Resto !== parseInt(strCPF.substring(10, 11) ) )
return false;
return true;
};
DDS.isDate = function (strDate) {
var _cp = 1;
var _d = '';
var _m = '';
var _y = '';
for (x = 0; x < strDate.length; x++) {
if ('0123456789'.indexOf(strDate.substr(x, 1)) > -1) {
if (_cp === 1) _d = _d + strDate.substr(x, 1);
if (_cp === 2) _m = _m + strDate.substr(x, 1);
if (_cp === 3) _y = _y + strDate.substr(x, 1);
} else {
_cp = _cp + 1;
}
}
if (_d.length === 1) _d = '0' + _d;
if (_m.length === 1) _m = '0' + _m;
if (_y.length === 3) _y = '0' + _y;
if (_y.length === 2) _y = '00' + _y;
if (_y.length === 1) _y = '000' + _y;
var _data = new Date(_y, _m - 1, _d);
// subtract 1 from the month since .getMonth() is zero-indexed.
if (parseInt(_y) > 1800 && parseInt(_y) > 1800 &&_data.getFullYear() === parseInt(_y) && _data.getMonth() === parseInt(_m) - 1 && _data.getDate() === parseInt(_d)) {
return _d + "/" + _m + "/" + _y;
} else {
return '';
}
};
//Objeto usuario ajuda o javascript a se comunicar com nosso usuario logado no c#
DDS.Logado = function () {
var Logado = false;//Valor autenticado por padrão é false
$.ajax({//aqui a chamada é sincrona ou seja, ele espera o ajax voltar para continuar na linha de baixo.
url: '/Home/Logado',
datatype: 'json',
type: 'POST',
async: false,
success: function (response) {
Logado = response;
}
});
return Logado;
};
DDS.Online = function () {
$.post('/Home/Online',function (data) {
return data;
}).fail(function () {
return false;
});
//$.ajax({
// url: '/Home/Online',
// datatype: 'json',
// type: 'POST',
// async: false,
// success: function (response) {
// Online = response;
// }
//});
};
DDS.GetParam = function (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
DDS.Cookie = function (name, value) {
if (value !== undefined) {
var expires = "";
var days = 3650;
if (value !== "") {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
return value;
} else {
try {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
} catch (err) {
return "";
}
return "";
}
};
DDS.CookieDeleteTodos = function () {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var equals = cookies[i].indexOf("=");
var name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
};
DDS.LimpaUrl = function (url) {
if (url !== undefined) {
url = url.trim().toLowerCase();
url = url.replace(/á/g, "a");
url = url.replace(/à/g, "a");
url = url.replace(/â/g, "a");
url = url.replace(/ã/g, "a");
url = url.replace(/ä/g, "a");
url = url.replace(/é/g, "e");
url = url.replace(/è/g, "e");
url = url.replace(/ê/g, "e");
url = url.replace(/ë/g, "e");
url = url.replace(/í/g, "i");
url = url.replace(/ì/g, "i");
url = url.replace(/î/g, "i");
url = url.replace(/ï/g, "i");
url = url.replace(/ó/g, "o");
url = url.replace(/ò/g, "o");
url = url.replace(/ô/g, "o");
url = url.replace(/õ/g, "o");
url = url.replace(/ö/g, "o");
url = url.replace(/ú/g, "u");
url = url.replace(/ù/g, "u");
url = url.replace(/û/g, "u");
url = url.replace(/ü/g, "u");
url = url.replace(/ç/g, "c");
url = url.replace(/ñ/g, "n");
var url_ok = "";
var i;
for (i = 0, l = url.length, url_ok = ""; i < l; i++) {
var _c = url[i].charCodeAt();
if (_c >= 48 && _c <= 57 || _c >= 97 && _c <= 122) {
url_ok = url_ok + url[i];
}
else {
url_ok = url_ok + ' ';
}
}
url = url_ok.replace(/ /g, " ");
url = url.replace(/ /g, " ");
url = url.replace(/ /g, " ");
url = url.trim();
url = url.replace(/ /g, "-");
} else {
url = "";
}
return url;
};
DDS.Executa = function (_url, _dto, _func_sucesso, _func_cancel) {
$('body').css("cursor", "progress");
if (_url.indexOf('http') === -1) _url = location.origin + _url;
DDS._url = _url;
DDS._dto = _dto;
DDS._func_cancel = _func_cancel;
DDS._func_sucesso = _func_sucesso;
if (navigator.onLine === false) {
if (typeof DDS.Mensagem === 'function') {
DDS.Mensagem("Sua Conexão Caiu, Tente Novamente.");
} else {
alert("Sua Conexão Caiu, Tente Novamente.");
}
$('body').css("cursor", "default");
} else {
$.post(_url, _dto, function (data, status) {
if (_func_sucesso !== undefined) _func_sucesso(data);
$('body').css("cursor", "default");
}).fail(function (xhr, status, error) {
var _mensagem = '';
try {
$.each(xhr, function (index, value) {
_mensagem += '\n' + index + ': ' + value;
});
alert('Erro no DDS.Executa (parte A) ' + '\nurl: ' + _url
+ '\n' + error
+ '\n' + _mensagem);
} catch (error2) {
_mensagem = _mensagem;
}
if (_mensagem === undefined) _mensagem = "";
if (status === "timeout") {
DDS.Mensagem("Tempo Excedido - Desculpe a Falha na Conexão com o Site, Tente Novamente.");
} else if (_func_cancel !== undefined) {
_func_cancel();
} else if (_mensagem.indexOf("Maximum request length exceeded") !== -1) {
DDS.Mensagem("Tamanho máximo excedido.");
} else {
$('#ddstibase_conteudo').html("Site com problemas temporariamente
Desculpe o transtorno!
Volte mais tarde.");
}
$('body').css("cursor", "default");
});
}
};
DDS.ExecutaAnt = function (_url, _dto, _func_sucesso, _func_cancel, _async) {
if (DDS.Online() === false) {
if (typeof DDS.Mensagem === 'function') DDS.Mensagem("Sua Conexão Caiu, Tente Novamente.");
if (_func_cancel !== undefined) _func_cancel();
} else {
if (_async === undefined) _async = true;
$('body').css("cursor", "progress");
//parametros passados pelo usuário
if (_url.indexOf('http') === -1) {
_url = location.origin + _url;
}
DDS._url = _url;
DDS._dto = _dto;
DDS._func_cancel = _func_cancel;
DDS._func_sucesso = _func_sucesso;
//Se o dto não for passado então executa uma chamada sem dto
if (_dto === undefined) {
$.ajax({
async: _async,
type: 'POST', datatype: 'json', url: _url, success: function (response) {
_func_sucesso(response);
$('body').css("cursor", "default");
}, error: function (xhr, status, error) {
var _mensagem = '';
try {
$.each(xhr, function (index, value) {
_mensagem += '\n' + index + ': ' + value;
});
alert('Erro no DDS.Executa (parte A) ' + '\nurl: ' + _url
+ '\n' + error
+ '\n' + _mensagem);
} catch (error) {
_mensagem = _mensagem;
}
if (_mensagem === undefined) _mensagem = "";
if (status === "timeout") {
DDS.Mensagem("Tempo Excedido - Desculpe a Falha na Conexão com o Site, Tente Novamente.");
} else if (_func_cancel !== undefined) {
_func_cancel();
} else if (_mensagem.indexOf("Maximum request length exceeded") !== -1) {
DDS.Mensagem("Tamanho máximo excedido.");
} else {
$('#ddstibase_conteudo').html("Site com problemas temporariamente
Desculpe o transtorno!
Volte mais tarde.");
}
$('body').css("cursor", "default");
}
});
} else {//se não executa uma chamada com o dto
$.ajax({
async: _async,
type: 'POST', datatype: 'json', url: _url, data: _dto, success: function (response) {
_func_sucesso(response);
$('body').css("cursor", "default");
}, error: function (xhr, status, error) {
var _mensagem = '';
if (location.host.indexOf('localhost:') > -1) {
try {
$.each(xhr, function (index, value) {
_mensagem += '\n' + index + ': ' + value;
});
alert('Erro no DDS.Executa (parte B) ' + '\nurl: ' + _url
+ '\n' + error
+ '\n' + _mensagem);
} catch (error) {
_mensagem = _mensagem;
}
}
if (_mensagem === undefined) _mensagem = "";
if (status === "timeout") {
DDS.Mensagem("Tempo Excedido - Desculpe a Falha na Conexão com o Site, Tente Novamente.");
} else if (_func_cancel !== undefined) {
_func_cancel();
} else if (_mensagem.indexOf("Maximum request length exceeded") !== -1) {
DDS.Mensagem("Tamanho máximo excedido.");
} else {
$('#ddstibase_conteudo').html("Site com problemas temporariamente
Desculpe o transtorno!
Volte mais tarde.");
}
$('body').css("cursor", "default");
}
});
}
}
};
DDS._url = undefined; //Como aqui são apenas propriedades elas estão em minúsculo
DDS._dto = undefined; //Como aqui são apenas propriedades elas estão em minúsculo
DDS._func_cancel = function () { };//metodo privado não é usado diretamente pelo programador
DDS._func_sucesso = function () { };//metodo privado não é usado diretamente pelo programador
DDS.Repetir = function (str) {
DDS.ModalOKCancel(str);
$('.modal_Ok_Cancel_BtnOk').html('Repetir');
$('.modal_Ok_Cancel_BtnCancel').click(function (e) {
e.preventDefault();
$('#modal_Ok_Cancel').modal('hide');
if (DDS._func_cancel !== undefined) {
DDS._func_cancel();
} else {
$('#ddstibase_conteudo').html("Site com problemas temporariamente
Desculpe o transtorno!
Volte mais tarde.");
}
});
$('.modal_Ok_Cancel_BtnOk').click(function (e) {
e.preventDefault();
DDS.Executa(DDS._url, DDS._dto, DDS._func_sucesso, DDS._func_cancel);
$('#modal_Ok_Cancel').modal('hide');
});
};
DDS.IEBad = function () {//retorna true se o IE for menor que 10
var _ret = false;
// no ie 11 o navigator.appName muda para NETSCAPE
if (navigator.appName === 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) !== null) {
var versao = parseFloat(RegExp.$1);
// nao roda ie < 10
if (versao < 10) _ret = true;
}
}
return _ret;
};
DDS.VerificaVersaoIE = function () {//verifica a versão do IE se for acima de 10 então pode
var _ret = false;
if (navigator.appName === 'Netscape') {
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) !== null)
var versao = parseFloat(RegExp.$1);
if (versao >= 10) _ret = true;
}
return _ret;
};
DDS.VerificaSafari = function () {
var _ret = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/);
return _ret;
};
DDS.Qual_Nagegador = function () {
var ua = navigator.userAgent, tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE ' + (tem[1] || '');
}
if (M[1] === 'Chrome') {
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if (tem !== null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((tem = ua.match(/version\/(\d+)/i)) !== null) M.splice(1, 1, tem[1]);
return M.join(' ');
};
DDS.Executa("/Home/Timeout", undefined, function (response) {
$.ajaxSetup({
timeout: response,
statusCode: {
306: function () {
DDS.Mensagem("Desculpe a Falha do Site, tente Novamente.");
},
500: function () {
DDS.Repetir('O Servidor encontrou uma condição insatisfatória para responder à esse chamado');
},
501: function () {
DDS.Repetir('O Servidor não suportou essa operação');
},
502: function () {
DDS.Repetir('O Servidor está temporariamente sobre-carregado');
},
503: function () {
DDS.Repetir('Essa operação demorou mais tempo do que o possível');
}
}
});
});
DDS.ModalOKCancel = function (str) {
if (str === undefined) str = "";
$('.modal-backdrop').remove();
$('#modal_Ok_Cancel').remove();
$('#modal_Ok_Cancel_CSS').remove();
var _htmlModal = '';
$('head').append(_htmlModal);
//_htmlModal = '