﻿/// JScript File
// Adicionando funções úteis ao protótipo do tipo string.
String.prototype.trim = Function("return this.replace(/((^\\s+)|(\\s+$))/g, '');");

var backspaceKey = 8;
var deleteKey = 46;
var pasteKey = 86;
var cutKey = 88;


function showException(scopeName, e)
{
	var msg = "SCOPE: " + scopeName + ".\nMESSAGE: ";
	if (typeof(e.message) == 'undefined') msg += e;
	else msg += e.message;

	//alert(msg);
}

function setMaskEdit(id, validateFunction)
{
	try
	{
		var src = document.getElementById(id);
		if (src == null)
		{
			throw "Input element not found";
		}

		if (src.tagName.toUpperCase() != "INPUT" || src.type.toUpperCase() != "TEXT")
		{
			throw "Invalid input element";
		}	
	
//		src.oldValue = "";
//		src.value = "";

		src.maskFormat = new Array();
		src.Matches = new Array();
		src.oldMatches = new Array();

		if (arguments.length > 2)
		{
			for (var i = 2; i < arguments.length; i++)
			{
				src.maskFormat[i-2] = arguments[i];
				src.Matches[i-2] = "";
				src.oldMatches[i-2] = "";
			}
		}

		src.onblur = maskEditValidate;
		src.onkeydown = specialKeyFilter;
		src.onkeypress = maskEditFilter;
		src.onpaste = pasteValidate;
		src.oncut = cutValidate;
		src.ondrag = dragValidate;
		src.ondrop = dropValidate;
		
		src.getValue = getValue;
		src.build = buildValue;
		src.validate = null;
		src.setPrompt = setPrompt;
		src.getPrompt = getPrompt;
		src.commit = commitChange;
		src.rollback = rollbackChange;
		src.clear = clearValue;
		
		// Atributos para identificação da mudança
		src.isBackspace = false;
		src.isDelete = false;
		src.isPaste = false;
		src.isCut = false;
		
		try {eval("src.validate = " + validateFunction);} catch (e) {}
	}
	catch (e)
	{
		showException("setMaskEdit", e);
	}
}

function maskEditFilter()
{
	var _onblur = this.onblur;
	this.onblur = null;

	try
	{
		var s = document.selection.createRange().text;
		var p = this.getPrompt();
		
		var v = this.value.substr(0, p);
		v += String.fromCharCode(event.keyCode);
		v += this.value.substr(p + s.length);
        
		v = this.getValue(v, false);
		if (v != this.oldValue || v == "")
		{
		    this.commit(v);
		}
		else
		{
		    this.rollback();
		}
	}
	catch (e)
	{
		showException("maskEditFilter", e);
	}

	this.onblur = _onblur;
	
	//event.preventDefault? event.preventDefault() : event.returnValue = false; 
	event.returnValue = false

	return false;
}

function specialKeyFilter()
{
	var _onblur = this.onblur;
	this.onblur = null;
	
	try
	{
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	
		if (event.keyCode != backspaceKey && event.keyCode != deleteKey 
		&& !(event.keyCode == pasteKey && event.ctrlKey) && !(event.keyCode == cutKey && event.ctrlKey))
		{
			this.onblur = _onblur;
			event.returnValue = true;
			return true;
		}
		else if (event.keyCode == backspaceKey)
		{
		    this.isBackSpace = true;
		}
		else if (event.keyCode == backspaceKey)
		{
		    this.isDelete = true;
		}
		else if (event.keyCode == pasteKey)
		{
		    this.isPaste = true;
		}
		else if (event.keyCode == cutKey)
		{
		    this.isCut = true;
		}

		var v = "";
		var p = this.getPrompt();
		var s = document.selection.createRange().text;
	    
	    if (this.isPaste)
	    {
	        var d = clipboardData.getData("Text");
	        v = this.value.substr(0, p) + d;
	        v += this.value.substr(p + s.length);
	    }
	    else
	    {
	        if (this.isCut)
	        {
    	        clipboardData.setData("Text", s);
	        }

            if (s != "" || this.isCut)
            {
                if (s != "")
                {
	                v += this.value.substr(0, p);
	                v += this.value.substr(p + s.length);
                }
                else
                {
                     p = -1;
                }
            }
            else
            {
	            if (event.keyCode == backspaceKey)
	            {
		            if (p > 0)
		            {
			            v += this.value.substr(0, p - 1);
			            v += this.value.substr(p + s.length);
		            }
		            else
		            {
			            p = -1;
		            }
	            }
	            else if (event.keyCode == deleteKey)
	            {
		            if (p < this.value.length)
		            {
			            v += this.value.substr(0, (p + 1));
			            v += this.value.substr((p + 2) + s.length);
		            }
		            else
		            {
			            p = -1;
		            }
	            }
            }
	    }
		
		if (p >= 0)
		{
		    v = this.getValue(v, false);
		    if (v != this.oldValue  || v == "" || this.value != v)
		    {
		        this.commit(v);
		    }
		    else
		    {
		        this.rollback();
		    }
		}
	}
	catch (e)
	{
		showException("specialKeyFilter", e);
	}	

	this.onblur = _onblur;	
	
	//e.preventDefault? e.preventDefault() : e.returnValue = false;
	event.returnValue = false;
	
    this.isBackSpace = false;
    this.isDelete = false;
    this.isPaste = false;
    this.isCut = false;
    
	return false;
}

function maskEditValidate()
{
	var _onblur = this.onblur;
	this.onblur = null;
	
	try
	{
	    var v = this.value;
	    var n = this.getValue(v, true); 
	    if (n == "")
	    {
	        this.clear();
	    }
	    else if (n != v)
	    {
	        this.value = n;
	    }
	}
	catch (e)
	{
		showException("maskEditValidate", e);
	}

	this.onblur = _onblur;
	//e.preventDefault? e.preventDefault() : e.returnValue = false;
	event.returnValue = false;
	
	return false;
}

function pasteValidate()
{
	//e.preventDefault? e.preventDefault() : e.returnValue = false;
	event.returnValue = false;
	return false;
}

function cutValidate()
{
	//e.preventDefault? e.preventDefault() : e.returnValue = false;
	event.returnValue = false;
	return false;
}

function dragValidate()
{
	//e.preventDefault? e.preventDefault() : e.returnValue = false;
	event.returnValue = false;
	return false;
}

function dropValidate()
{
	//e.preventDefault? e.preventDefault() : e.returnValue = false;
	event.returnValue = false;
	return false;
}

function getValue(newValue, fullValidate)
{
	try
	{
		if (this.maskFormat != null && (this.value != newValue || fullValidate))
		{
			for (var i = 0; i < this.Matches.length; i++)
			{
				this.Matches[i] = "";
			}

			var nValue = newValue;
			for (var i = 0; i < this.maskFormat.length; i++)
			{
				var mch = "";
				var frm = this.maskFormat[i];
				
				if (typeof(frm) == "object")
				{
					var arr = frm.exec(nValue);
					if (arr == null)
					{
					    break;
					}

					mch = arr[0];					
				    nValue = nValue.substr(mch.length + RegExp.leftContext.length);
				}
				else
				{
					if (nValue.substr(0, this.maskFormat[i].length) == this.maskFormat[i])
					{
				        nValue = nValue.substr(this.maskFormat[i].length);
				        mch = this.maskFormat[i];
					}
					else if (fullValidate)
					{
					    break;
					}
				}
				
				this.Matches[i] = mch;
			}
                        
            if (nValue != "")
            {
                if (fullValidate)
                {
                    return "";
                }
                else 
                {
                    return this.oldValue;
                }
            }
            
            if (this.validate != null)
            {
                if (!this.validate(fullValidate))
                {
                    if (fullValidate)
                    {
                        return "";
                    }
                    else 
                    {
                        return this.oldValue;
                    }
                }
            }
            
			return this.build();
		}		
	}
	catch (e)
	{
		showException("getValue", e);
	}
	
	return newValue;
}

function setPrompt(x)
{
    try
    {
	    var rng = this.createTextRange();
	    var sel = document.selection.createRange();

        if (sel.parentElement() != rng.parentElement()) return 0;        
        
        var nvl = rng.text.length;
	    document.selection.TextRange = rng;
        	    
	    for (var j = 0; j < x; j++)
	    {
	        rng.moveStart("character", 1);
	    } 
        
	    for (var j = x; j < nvl; j++)
	    {
	        rng.moveEnd("character", -1);
	    } 
	    
	    rng.select();
    }
    catch (e)
    {
		showException("setPrompt", e);
    }
}

function getPrompt()
{
    try
    {
	    var rng = this.createTextRange();
	    var sel = document.selection.createRange();

      if (sel.parentElement() != rng.parentElement()) return 0;
        
        var x = 0;

        while (sel.compareEndPoints("StartToStart", rng) > 0)
        {
            if (x > this.value.length) return (this.value.length - 1);
            rng.moveStart("character", 1);
            x++;
        }
        
        return x;
    }
    catch (e)
    {
		showException("getPrompt", e);
		return 0;
    }
}

function buildValue()
{
	try
	{
	    var l = -1;
	    for (var n = 0; n < this.Matches.length; n++)
	    {
			if (typeof(this.maskFormat[n]) == "object")
			{
	            if (this.Matches[n] != "")
	            {
	                l = n;
	            }
			}
	    }
	    
	    var v = "";
	    for (var n = 0; n < this.Matches.length; n++)
	    {
			if (typeof(this.maskFormat[n]) != "object")
			{
				if ((n + 1) < this.Matches.length)
				{
					if (l > n)
					{
						this.Matches[n] = this.maskFormat[n];
					}
				}
				else
				{
					this.Matches[n] = this.maskFormat[n];
				}
			}
			
	        v += this.Matches[n];
	    }
	    
	    return v;
	}
	catch (e)
	{
		showException("buildValue", e);
	}
}

function commitChange(newValue)
{
	try
	{
	    var t = p = this.getPrompt();
        var s = document.selection.createRange();
        var oldValue = this.value;
        
        if (s == "")
        {
            if (this.isBackspace)
            {
                p--;
            }
            else if (!this.Delete)
            {
                p += (newValue.length - this.value.length);   
            }
        }
        else
        {   
         
            p += (newValue.length - this.value.length + s.text.length);
        }
        
        this.value = newValue;
	    this.oldValue = newValue;
	    this.oldMatches = this.Matches;
	    
	    this.setPrompt(p);
	}
	catch (e)
	{
		showException("commitChange", e);
	}
}

function rollbackChange()
{
	try
	{
	    this.Matches = this.oldMatches;
	}
	catch (e)
	{
		showException("rollbackChange", e);
	}
}

function clearValue()
{
	try
	{
		for (var i = 0; i < this.Matches.length; i++)
		{
			this.Matches[i] = "";
			this.oldMatches[i] = "";
		}
		
		this.oldValue = "";
		this.value = "";
	}
	catch (e)
	{
		showException("clearValue", e);
	}
}

//#****************************************************************
// Funções de validação específicas por tipo de máscara.
//#****************************************************************


// Valida um campo de data.
function dateValidate(fullValidate)
{
    try
    {
		if (this.Matches[0].length == 2)
		{
		    if (this.Matches[0] > "31")
		    {
		        return false;
		    }
		}

		if (this.Matches[2].length == 2)
		{
		    if (this.Matches[2] > "31")
		    {
		        return false;
		    }
		}
            
        if (fullValidate)
        {
            var dt = new Date();
            var y = dt.getFullYear().toString();
            
            if (this.Matches[4].length < y.length)
            {
                if (this.Matches[4].length == 2)
                {
                    y = y.substr(0, y.length - 2);
                    y += this.Matches[4];
                                       
                    this.Matches[4] = y.toString();
                    dt.setFullYear(y);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                dt.setFullYear(this.Matches[4]);
            }
            
            if (this.Matches[2].length == 1)
            {
                this.Matches[2] = "0" + this.Matches[2];
            }
            
            if (this.Matches[0].length == 1)
            {
                this.Matches[0] = "0" + this.Matches[0];
            }
            
            dt.setMonth(this.Matches[2]);
            dt.setMonth(dt.getMonth() - 1);
            dt.setDate(this.Matches[0]);
            
            if (dt.getDate() != this.Matches[0] || (dt.getMonth() + 1) != this.Matches[2] || dt.getFullYear() != this.Matches[4])
            {
                return false;
            }            
        }
    }
    catch (e)
    {
        showException("dateValidate", e);
        return false;
    }    
    
    return true;
}

// Valida um campo de CNPJ
function cnpjValidate(fullValidate)
{
    try
    {
        if (!fullValidate) return true;
        
        while (this.Matches[0].length < 2)
            this.Matches[0] = "0" + this.Matches[0];
         
        while (this.Matches[2].length < 3)
            this.Matches[2] = "0" + this.Matches[2];
            
        while (this.Matches[4].length < 3)
            this.Matches[4] = "0" + this.Matches[4];
            
        while (this.Matches[6].length < 4)
            this.Matches[6] = "0" + this.Matches[6];
            
        while (this.Matches[8].length < 2)
            this.Matches[8] = "0" + this.Matches[8];
            
	    var i = 0;
	    var c = this.Matches[0] + this.Matches[2] + this.Matches[4] + this.Matches[6];
	    var dv = this.Matches[8];
	    var d1 = 0;
	    for (i = 0; i < 12; i++)
	    {
		    d1 += c.charAt(11-i)*(2+(i % 8));
	    }
    	
	    if (d1 == 0)
	    {
            return false;
	    }
	    
		d1 = 11 - (d1 % 11);
	    if (d1 > 9) d1 = 0;
	    if (dv.charAt(0) != d1)
	    {
            return false;
	    }

	    d1 *= 2;
	    for (i = 0; i < 12; i++)
	    {
		    d1 += c.charAt(11-i)*(2+((i+1) % 8));
	    }
    	
	    d1 = 11 - (d1 % 11);
	    if (d1 > 9) d1 = 0;
	    if (dv.charAt(1) != d1)
	    {
            return false;
	    }
    }
    catch (e)
    {
        showException("cnpjValidate", e);
        return false;
    }
    	
	return true;		
}

// Valida um campo de CPF
function cpfValidate(fullValidate)
{
    try
    {
        if (!fullValidate) return true;
        
        while (this.Matches[0].length < 3)
            this.Matches[0] = "0" + this.Matches[0];
         
        while (this.Matches[2].length < 3)
            this.Matches[2] = "0" + this.Matches[2];
            
        while (this.Matches[4].length < 3)
            this.Matches[4] = "0" + this.Matches[4];
            
        while (this.Matches[6].length < 2)
            this.Matches[6] = "0" + this.Matches[6];
            
        var CPF = this.Matches[0]+this.Matches[2]+this.Matches[4]+this.Matches[6];
		if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
			CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
			CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
			CPF == "88888888888" || CPF == "99999999999")
        {
			return false;
        }
			
		soma = 0;
		for (i=0; i < 9; i ++)
			soma += parseInt(CPF.charAt(i)) * (10 - i);
			
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)
			resto = 0;
			
		if (resto != parseInt(CPF.charAt(9)))
        {
			return false;
        }
        
		soma = 0;
		for (i = 0; i < 10; i ++)
			soma += parseInt(CPF.charAt(i)) * (11 - i);
			
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)
			resto = 0;
			
		if (resto != parseInt(CPF.charAt(10)))
        {
			return false;
        }        
    }
    catch (e)
    {
        showException("cpfValidate", e);
        return false;
    }
    	
	return true;		
}

//Formata um campo Double
function doubleValidate(fullValidate)
{
    try
    {
        var n = this.Matches[0]+this.Matches[1];
        n = n.replace(/\./g, "");

        var x = "";
        for (var i = 0; i < n.length; i++)
        {
            if (i > 0 && i % 3 == 0)
            {
	            x = "." + x;
            }

            x = n.charAt(n.length - (i + 1)) + x;
        }

        this.Matches[0] = x.charAt(0);

        if (x.length > 1)
        {
            this.Matches[1] = x.substr(1);
        }
    }
    catch (e)
    {
        showException("doubleValidate", e);
    }  		
    
    return true;
}

//Valida um campo de Hora.
function horaValidate(fullValidate)
{
  try
    {
		if (this.Matches[0].length == 1)
		{
		    if (this.Matches[0] > "2")
		    {
		        return false;
		    }
		}
		else
		{
		     if (this.Matches[0] > "23")
		    {
		        return false;
		    }
		}

		if (this.Matches[2].length == 1)
		{
		    if (this.Matches[2] > "5")
		    {
		        return false;
		    }
		}
		else
		{
		     if (this.Matches[2] > "59")
		    {
		        return false;
		    }
		}
		            
        if (fullValidate)
        {
        
             if (this.Matches[0].length == 1)
            {
                return false ;
            }
            else if(this.Matches[0].length == 2 && this.Matches[2].length==0)
            {
                this.Matches[2] = this.Matches[2]+"00";
            }
           
            if (this.Matches[2].length == 1)
            {
                this.Matches[2] =  this.Matches[2]+ "0" ;
            }
            
           
                       
                
        }
    }
    catch (e)
    {
        showException("dateValidate", e);
        return false;
    }    
    
    return true;

}


//Valida um campo de CEP.
function cepValidate(fullValidate)
{
  try
    {
        if (!fullValidate) return true;
        
        while (this.Matches[4].length < 3)
            this.Matches[4] =   this.Matches[4] + "0";
            
        if(this.Matches[0]==00 || this.Matches[2]==000)
            return false;
        
        var CEP = this.Matches[0]+this.Matches[2]+this.Matches[4];
        
        if(this.Matches[0].length < 2||this.Matches[2].length < 3||CEP=="00000000"||
            CEP=="11111111"||CEP=="22222222"||CEP=="33333333"||CEP=="44444444"||
            CEP=="55555555"||CEP=="66666666"||CEP=="77777777"||CEP=="88888888"||CEP=="99999999")
            return false;                   
      
    }
    catch (e)
    {
        showException("cepValidate", e);
        return false;
    }
    	
	return true;		
}

//Letras maiusculas
function upCaseFormat(fullValidate)
{
     if (!fullValidate) return true;
    try
    {
        this.Matches[0] = this.Matches[0].toUpperCase();        
        return true;       
                      
   }
    catch (e)
    {
        showException("upCaseFormat", e);
    }

}

//Valida e-mail
function emailValidate(fullValidate)
{ 
//#**********************************************************************
// Expressões Regulares para e-mail
// e-mail livre    --> /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/
// e-mail compacto --> /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
// e-mail restrito --> /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
//#**********************************************************************
  if (!fullValidate) return true;
   
  var er = new RegExp(/^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/);
  try
  {
   if(er.test(this.Matches[0]))
   return true;  
 	
  }
   catch (e)
 {
       showException("emailValidate", e);
 }  
  return false; 
}

function Mascara_Hora(obj, culture){ 
    var hs = obj.value;
    
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    //if (e.keyCode) keyCode = e.keyCode;         
	//else if (e.which) keyCode = e.which; // Netscape 4.?   
	//else if (e.charCode) keyCode = e.charCode; // Mozilla  
    
    if (keyCode >= 48 && keyCode <= 57 && hs.length < 5)
    {
        var hora01 = ''; 
        hora01 = hora01 + obj.value; 
        
        if (hora01.length == 2)
        { 
            hora01 = hora01 + ':'; 
            obj.value = hora01;
        } 
        if (hora01.length == 4)
        { 
            if (Verifica_Hora(hora01))
            {
                obj.value = hora01;
            }
            else
            {
                obj.value = "";
                //e.preventDefault? e.preventDefault() : e.returnValue = false;
                event.returnValue = false;
            }
        }
    }
    else if (culture == "en-us")
    {
        var hora01 = obj.value;
        if (hora01.substring(0,2) < 12)
        {
            if (keyCode == 32 && hora01.length == 5)
            {
                event.returnValue = true;
            }
            else if ((keyCode == 97 || keyCode == 112 || keyCode == 65 || keyCode == 80 )  && hora01.length == 6)
            {
                event.returnValue = true;
            }
            else if ((keyCode == 109  || keyCode == 77) && hora01.length == 7) 
            {
                event.returnValue = true;
            }
            else
            {
                event.returnValue = false;
            }
        }
        else
        {
            //event.preventDefault? event.preventDefault() : event.returnValue = false;
            event.returnValue = false;
        }
    }
    else
    {
        event.returnValue = false;
    }
} 

function Complete_Hora(obj, culture){ 
    if (obj.value.length == 1)
    {
        valor = obj.value;
        obj.value = "0" + valor + ":00";
    }
    else if (obj.value.length == 2)
    {
        obj.value = obj.value + ":00";
    }
    else if (obj.value.length == 4)
    {
        obj.value = obj.value + "0";
    }
    if (!Verifica_Hora(obj.value)) 
    {
        obj.value = "";
        //e.preventDefault? e.preventDefault() : e.returnValue = false;
        event.returnValue = false;
    }
    else
    {
        if (culture == "en-us")
        {
            var hora01 = obj.value;
            if (hora01.substring(0,2) < 12 && hora01.length == 5)
            {
                obj.value = obj.value + " AM";
            }
            else if (hora01.substring(0,2) < 12 && hora01.length == 6)
            {
                obj.value = obj.value + "AM";
            }
            else if (hora01.length == 7)
            {
                obj.value = obj.value.toUpperCase() + "M";
            }
            else
            {
                obj.value = obj.value.toUpperCase();
            }
        }
    }
} 

           
function Verifica_Hora(value)
{ 
    hrs = (value.substring(0,2)); 
    min = (value.substring(3,5)); 
               
    if ((hrs < 00 ) || (hrs > 23) || ( min < 00) ||( min > 59))
    { 
        return false;
    } 
    else
        return true;
} 


function teclaPressionadaMascara(elem, event, mask) {
    var m = mask.charAt(elem.value.length);
    var codigo = (window.event) ? window.event.keyCode : event.which;
    var tecla = String.fromCharCode(codigo);
    var valido = true;

    if (codigo == 0 || codigo == 10 || codigo == 13 || codigo == 8) {
    return true;
    }

    if ((tecla.toUpperCase() != m) && (m != '9')) {
    if (mask.charAt(elem.value.length + 1) == '9') {
    if (verificarDigito(codigo)) {
    elem.value += m;
    } else {
    valido = false;
    }
    } else {
    elem.value += m;
    }
    } else {
    valido = (m == '9') ? verificarDigito(codigo) : true;
    }

    if (window.event) {
    window.event.returnValue = valido;
    }

    return valido;
}

function verificarDigito(keyCode) {
       return ((keyCode >= 48) && (keyCode <= 57));
}

