var ie		= (typeof window.ActiveXObject != 'undefined');
var moz		= (typeof document.implementation != 'undefined') &&(typeof document.implementation.createDocument != 'undefined');

var SM_PATH	= url();
var IMG_ND	= "../../_images/imagem_indisponivel.gif";
var ALT_OK	= "Alteração realizada com sucesso !";
var INC_OK	= "Inclusão realizada com sucesso !";
var DEL_OK	= "Exclusão realizada com sucesso !";
var REG_DUPL = "Não foi possível completar esta operação pois já existe um registro com este nome. \n\t\t\t Tente novamente.";
var REG_DUPL_VAGA = "Não foi possível completar esta operação pois já existe um registro com este código. \n\t\t\t Tente novamente.";
var CNF_IMG	= "Confirma a exclusão da Imagem ?";

function url()
{
	//return "http://localhost/richs.web/_includes/ServiceManager.aspx";
	
	var loc = document.location.href;

	var locUpper = loc.toUpperCase()
	
	var pos = locUpper.indexOf("/ADMIN");
	
	if (pos > 0)
	{
		loc = loc.substr(0, pos);		
		loc += "/_includes/ServiceManager.aspx";		
	}
	else
		loc = "";
	
	return loc;
	
	
}
	
function Replace( Text, oldText, newText )
{
	do{	
		Text = Text.replace(oldText, newText);
	} while (Texto.indexOf(oldText) > 0)
	
	return Text;
}

function SelectOptionByText(pCombo, pTexto) {

	var ret="";
	for(var i=0; i < pCombo.options.length ; i++ )
	{
		pCombo.options[i].selected = false;
	}


	for(var i=0; i < pCombo.options.length ; i++ )
	{
	    if(pCombo.options[i].text == pTexto) {
			pCombo.options[i].selected = true;
			break;
	    }
	}    

	return ret;

}

function queryString(ParamName, pURL)
{
	if( pURL == null )
		var strURL	 = document.location.toString();
	else
		var strURL	 = pURL;
		
	if(strURL.indexOf(ParamName) == -1)
		return "";
		 
	var intStart = strURL.indexOf(ParamName + "=");
		intStart+= ParamName.length + 1;
	var strRet	 = "";
	
	for(var i=(intStart); i < strURL.length; i++)
	{
		if(strURL.substr(i,1) == "&")
			break;
		else
		{
			strRet+=strURL.substr(i,1);
		}
	}
	return strRet;
}

function lTrim(){
    var a=lTrim.arguments[0]; i=0;
    while( (a.substring(i, i+1))==" " )i++;
    return a.substring(i, a.length);
}
function rTrim(){
    var a=rTrim.arguments[0]; i=a.length-1;
    while( (a.substring(i, i+1))==" " )i--;
    return a.substring(0, i+1);
}
function Trim(){
    return rTrim(lTrim(Trim.arguments[0]));
}

function isDate(pDate) {

	
	var strDatestyle = "EU";  
	var strDate;
	var strDateArray;
	var strDay		 = "";
	var strMonth	 = "";
	var strYear		 = "";
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = pDate;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	strDate = datefield;

	if (strDate == "") {
		return true;
	}

	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {

		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			
			if (strDateArray.length != 3) {
				err = 1;
				return false;
			}
			else {
				strDay		= strDateArray[0];
				strMonth	= strDateArray[1];
				strYear		= strDateArray[2];
			}
			
			booFound = true;
	}
	}

	if (booFound == false) {
		
		if (strDate.length > 5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
	}
	}
	
	if(strDate.length < 6) 
		return false;
			
	if (strYear.length == 2) {
		strYear = '20' + strYear;
	}
	
	if (strDatestyle == "US") {
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}

	intday = parseInt(strDay, 10);
	if (isNaN(intday)) {
		err = 2;
		return false;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}

		if (isNaN(intMonth)) {
			err = 3;
			return false;
	}
	}

	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) {
		err = 4;
		return false;
	}
	if (intMonth>12 || intMonth<1) {
		err = 5;
		return false;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
		err = 6;
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
		err = 7;
		return false;
	}
	if (intMonth == 2) {
		if (intday < 1) {
			err = 8;
			return false;
		}
		if (LeapYear(intYear) == true) {
			if (intday > 29) {
				err = 9;
				return false;
			}
		}
		else {
			if (intday > 28) {
				err = 10;
				return false;
			}
		}
	}

	return true;

}

function LeapYear(intYear) {

	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { return true; }
	}
	else {
		if ((intYear % 4) == 0) { return true; }
	}
	
	return false;
}


function isNumber(oOrigem) {

	var valor = oOrigem.value;	
	
	for (i=0; i < valor.length; i++) {
		nDigito = valor.substring(i,i+1)
		if (nDigito != "0" && nDigito !="1" && nDigito !="2" && nDigito !="3" 
			&& nDigito !="4" && nDigito !="5" && nDigito !="6" && nDigito !="7" 
			&& nDigito !="8" && nDigito !="9") {
				return false;
		}
	}
	return true;
}

function ValidaEmail(emailStr) {

var emailPat=eval("/^(.+)@(.+)$/");
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var firstChars=validChars;
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=eval("/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/");
var atom="(" + firstChars + validChars + "*" + ")";
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
var Msg = "O campo de E-Mail esta preenchido incorretamente! \nPor favor preencha-o novamente.";

if (matchArray==null) {
  	
	return false;
}
var user=matchArray[1];
var domain=matchArray[2];

if (user.match(userPat)==null) {
    
    return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        
		return false;
	    }
    }
    return true;
}

var domainArray=domain.match(domainPat);
if (domainArray==null) {
	
    return false;
}

var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   
   return false;
}

if (domArr[domArr.length-1].length==2 && len<3) {
   
   return false;
}

if (domArr[domArr.length-1].length==3 && len<2) {
   
   return false;
}
return true;
}

function AttachEvent( obj, eventName, functionName )
{
	if( ie )
		obj.attachEvent("on" +	eventName, functionName );
	else
		obj.addEventListener( eventName, functionName, false);
}

function getActiveObject(e)
{	
	var ret = null;
	
	if( ie )	
		ret = e.srcElement;	
	else
		ret = e.target;
		
	return ret;
}

function StringToDecimal(pValue)
{
	var ret = Replace( pValue, ".", "" );
		ret = Replace( ret   , ",", ".");

	if( isNaN(parseFloat(ret)) )
		return 0;
	else
		return parseFloat(ret);
}

function StringToInt(pValue)
{
	var ret = Replace( pValue, ".", "" );

	if( isNaN(parseInt(ret)) )
		return 0;
	else
		return parseInt(ret);
}

function Busca()
{
	var obj = document.forms[0].txtSearch;
	if( obj )
	{
		location.href = "busc.aspx?search=" + escape(obj.value);
	}
} 

function cleanCCNum( ccnumber ) {

	var ret="";

	for(var i=0; i < ccnumber.length; i++) {
		
		var c=ccnumber.substring(i, i+1);
			if(!isNaN(c))
				ret+=c; 

	}
	
	return ret;
}



function cepMask(e)
{
	var fld			= getActiveObject(e);
	var strCheck	= '0123456789';
	var tam			= 0;
	var key			= "";
	var aux			= "";
	var whichCode	= (window.Event) ? e.which : e.keyCode;
	
	if( whichCode != 13 && whichCode != 8 )
	{
		key = String.fromCharCode(whichCode);  // Get key value from key code
		if( strCheck.indexOf(key) == -1 ) 
		{
			killEvent(e);
			return false;  // Not a valid key
		}
	}

	if( whichCode == 8 )
	{
		var charAux = fld.value.substring(fld.value.length - 1, fld.value.length);
		if( charAux == "-" )
			fld.value = fld.value.substring(0, fld.value.length - 2);
		else
			fld.value = fld.value.substring(0, fld.value.length - 1);
	}

	fld.value = fld.value.replace('-', '');
	fld.value+= key;
	tam		  = fld.value.length;

    if (tam <= 8) 
    {
	     if (tam < 5)
	 	    aux = fld.value;
	     else if ((tam >= 5) && (tam <= 8))
	 	    aux = fld.value.substr(0, 5) + '-' + fld.value.substr(5, 3);
	}	  
	else
		aux = fld.value.substr(0, 5) + '-' + fld.value.substr(5, 3);

	fld.value = aux;
	killEvent(e);
	return false;	
}

function foneMask(e)
{
	var fld			= getActiveObject(e);
	var strCheck	= '0123456789';
	var tam			= 0;
	var key			= "";
	var aux			= "";
	var whichCode	= (window.Event) ? e.which : e.keyCode;
	
	if( whichCode != 13 && whichCode != 8 )
	{
		key = String.fromCharCode(whichCode);  // Get key value from key code
		if( strCheck.indexOf(key) == -1 ) 
		{
			killEvent(e);
			return false;  // Not a valid key
		}
	}

	if( whichCode == 8 )
	{
		var charAux = fld.value.substring(fld.value.length - 1, fld.value.length);
		if( charAux == "-" || charAux == "(" || charAux == ")" || charAux == " " )
			fld.value = fld.value.substring(0, fld.value.length - 2);
		else
			fld.value = fld.value.substring(0, fld.value.length - 1);
	}

	fld.value = fld.value.replace('(', '');
	fld.value = fld.value.replace(')', '');
	fld.value = fld.value.replace('-', '');
	fld.value = fld.value.replace(' ', '');
	fld.value+= key;
	tam		  = fld.value.length;
	//0123456789012;
	//012 3456		= 999-9999
	//0123 4567		= 9999-9999
	//01 234 5678	= (99)999-9999
	//01 2345 6789	= (99)9999-9999
	if (tam <= 4)
		aux = fld.value;
	else if (tam <= 7)
		aux = fld.value.substr(0, 3) + '-' + fld.value.substr(3, 4);
	else if (tam <= 8)
		aux = fld.value.substr(0, 4) + '-' + fld.value.substr(4, 4);
	else if (tam <= 9)
		aux = '(' + fld.value.substr(0, 2) + ')' + fld.value.substr(2, 3) + '-' + fld.value.substr(5, 4);
	else 
 		aux = '(' + fld.value.substr(0, 2) + ')' + ' ' + fld.value.substr(2, 4) + '-' + fld.value.substr(6, 4);

	fld.value = aux;
	killEvent(e);
	return false;	
}

function dateTimeMask(e)
{
	var fld			= getActiveObject(e);
	var strCheck	= '0123456789';
	var tam			= 0;
	var key			= "";
	var aux			= "";
	var whichCode	= (window.Event) ? e.which : e.keyCode;
	var tpo			= "DATA";

	if( whichCode != 13 && whichCode != 8 )
	{
		key = String.fromCharCode(whichCode);  // Get key value from key code
		if( strCheck.indexOf(key) == -1 ) 
		{
			killEvent(e);
			return false;  // Not a valid key
		}
	}

	if( whichCode == 8 )
	{
		var charAux = fld.value.substring(fld.value.length - 1, fld.value.length);
		if( charAux == "/" || charAux == ":" || charAux == " " )
			fld.value = fld.value.substring(0, fld.value.length - 2);
		else
			fld.value = fld.value.substring(0, fld.value.length - 1);
	}

	fld.value = fld.value.replace('/', '');
	fld.value = fld.value.replace('/', '');
	fld.value = fld.value.replace(':', '');
	fld.value = fld.value.replace(':', '');
	fld.value = fld.value.replace(' ', '');
	fld.value = fld.value.replace(' ', '');
	fld.value+= key;
	tam		  = fld.value.length;

	switch( tpo )
	{
		case eFieldType.data:
			if (tam < 3)
		 		aux = fld.value;
		 	else if (tam >= 3 && tam <= 4)
		 		aux = fld.value.substr(0, 2) + '/' + fld.value.substr(2, 2);
		 	else
		 		aux = fld.value.substr(0, 2) + '/' + fld.value.substr(2, 2) + '/' + fld.value.substr(4, 4);
			break;

		case eFieldType.dataHora:
			if (tam < 3)
		 		aux = fld.value;
		 	else if (tam >= 3 && tam <= 4)
		 		aux = fld.value.substr(0, 2) + '/' + fld.value.substr(2, 2);
		 	else if (tam >= 5 && tam <= 8)
		 		aux = fld.value.substr(0, 2) + '/' + fld.value.substr(2, 2) + '/' + fld.value.substr(4, 4);
			else if (tam >= 9 && tam <= 10)
				aux = fld.value.substr(0, 2) + '/' + fld.value.substr(2, 2) + '/' + fld.value.substr(4, 4) + ' ' + fld.value.substr(8, 2);
			else if (tam >= 11 && tam <= 12)
				aux = fld.value.substr(0, 2) + '/' + fld.value.substr(2, 2) + '/' + fld.value.substr(4, 4) + ' ' + fld.value.substr(8, 2) + ':' + fld.value.substr(10, 2);
			else
				aux = fld.value.substr(0, 2) + '/' + fld.value.substr(2, 2) + '/' + fld.value.substr(4, 4) + ' ' + fld.value.substr(8, 2) + ':' + fld.value.substr(10, 2);
			break;
			
		case eFieldType.mesAno:
			if (tam < 3)
		 		aux = fld.value;
		 	else
		 		aux = fld.value.substr(0, 2) + '/' + fld.value.substr(2, 4);
			break;
			
		case eFieldType.horaMinSeg:
			if (tam < 3)
		 		aux = fld.value;
		 	else if ((tam >= 3) && (tam <= 4))
		 		aux = fld.value.substr(0, 2) + ':' + fld.value.substr(2, 2);
		 	else if ((tam >= 5) && (tam <= 6))
		 		aux = fld.value.substr(0, 2) + ':' + fld.value.substr(2, 2) + ':' + fld.value.substr(4, 2);
			else 
				aux = fld.value.substr(0, 2) + ':' + fld.value.substr(2, 2) + ':' + fld.value.substr(4, 2);
			break;

		case eFieldType.horaMin:
			if (tam < 3)
		 		aux = fld.value;
		 	else if ((tam >= 3) && (tam <= 4))
		 		aux = fld.value.substr(0, 2) + ':' + fld.value.substr(2, 2);
			else 
				aux = fld.value.substr(0, 2) + ':' + fld.value.substr(2, 2);
			break;
	}

	fld.value = aux;
	killEvent(e);
	return false;	
}

function killEvent (e)
{
	if (e.preventDefault) 
	{
		e.preventDefault();
        e.stopPropagation();
	}
	else
		event.returnValue = false;
}

function eFieldType()
{
	this.data			= "DATA";
	this.dataHora		= "DATAHORA";
	this.mesAno			= "MESANO";
	this.horaMinSeg		= "HORAMINSEG";
	this.horaMin		= "HORAMIN";

	this.string			= "CHAR";
	this.numerico		= "DECIMAL";
	this.inteiro		= "INTEIRO";
	
	this.cartao			= "CARTAO";
	this.cep			= "CEP";
	this.cnpj			= "CNPJ";
	this.cpf			= "CPF";
	this.eMail			= "EMAIL";
	this.fone			= "FONE";

	this.regExpr		= "REGEXPR";
}
eFieldType = new eFieldType();



function eParamType()
{
	this.nameValue	= 0;
	this.xml		= 1;
}
eParamType = new eParamType();

function numericMask (e)
{
	var fld			= getActiveObject(e);
	var milSep		= ".";
	var tpo			= "DECIMAL";
	var decSep		= ",";
	var sep			= 0;
	var key			= "";
	var neg			= "";
	var i			= j = 0;
	var len			= len2 = 0;
	var strCheck	= '0123456789';
	var aux			= aux2 = '';
	var whichCode	= (window.Event) ? e.which : e.keyCode;
	var dec			= 2;

	if( whichCode != 13 && whichCode != 45 && whichCode != 8 )
	{
		key = String.fromCharCode(whichCode);  // Get key value from key code
		if( strCheck.indexOf(key) == -1 ) 
		{
			Behavior.killEvent(e);
			return false;  // Not a valid key
		}
	}

	if( whichCode == 8 )
		fld.value = fld.value.substring(0, fld.value.length - 1);

	if( whichCode == 45 )
	{
		if( fld.value.substring(0,1) == "-" )
		{
			fld.value	= fld.value.replace("-", "");
			neg			= "";
		}
		else
			neg			= "-";
	}
	else if( fld.value.substring(0,1) == "-" )
	{
		fld.value	= fld.value.replace("-", "");
		neg			= "-";
	}
	
	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) 
			break;
	aux = '';

	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) 
			aux += fld.value.charAt(i);
	
	aux += key;
	len = aux.length;

	if (len == 0)
		fld.value = '';

	if (len <= dec)
	{
		fld.value = '0'+ decSep;

		for( var x=len; x < dec; x++ ) 
			fld.value+= '0';

		fld.value+= aux;	
	}
	
	if (len > dec)
	{
		aux2 = '';
		for (j = 0, i = len - (dec + 1); i >= 0; i--) 
		{
			if (j == 3)
			{
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		
		fld.value = '';
		len2 = aux2.length;
		
		for (i = len2 - 1; i >= 0; i--)
			fld.value += aux2.charAt(i);
		
		fld.value += decSep + aux.substr(len - dec, len);
	}

	fld.value = neg + fld.value;
	killEvent(e);
	return false;
}	

function adminActionResult( msg, mok )
{		
	if (mok)
	{
		top.prcp.a.document.getElementById('btnFind').click();
		top.prcp.titu.volt(); 
	}
	alert( msg );	
}

function adminFormLoad( form, opr )
{
	var strUrl = form + "_titu2.htm?Acao=" + opr
	top.prcp.titu.document.location.href( strUrl );
}

function adminSelectImage( img, file )
{
	if( file.value == "" )
		img.src = IMG_ND;
	else
		img.src = file.value;
}

function deletePicture( tpoEntity, codigo, tpoImagem, imgObj, btnExcl )
{	
	if( codigo == "0" )
	{
		return;
	}
	else
	{
		if( confirm("Confirma a exclusão da imagem ?") == false )
			return;
	}
			
	var objService = new ServiceManager();
		objService.urlDefault = SM_PATH;
	
	var arrParam = new Array();
		arrParam[0] = "Codigo=" + codigo;
		arrParam[1] = "Tipo="	+ tpoImagem;

	objService.request( tpoEntity, arrParam, eParamType.nameValue )
	if( objService.errorCode == "0" )
	{
		imgObj.src = IMG_ND;
		btnExcl.style.display = "none";
	}
	else
		alert("Erro na exclusão da imagem !");
}

function deleteFile( codigo, btnExcl )
{
	if( codigo == "0" || document.getElementById("lblArq").innerHTML != "Download" )
	{
		return;
	}
	else
	{
		if( confirm("Confirma a exclusão do arquivo ?") == false )
			return;
	}
			
	var objService = new ServiceManager();
		objService.urlDefault = SM_PATH;
	
	var arrParam = new Array();
		arrParam[0] = "Codigo=" + codigo;
		arrParam[1] = "Tipo="	+ "D";

	objService.request( "RECEITUARIO", arrParam, eParamType.nameValue )
	if( objService.errorCode != "0" )
	{
		alert("Erro na exclusão da imagem !");
		document.getElementById("dvDownload").style.display = "block";
		document.getElementById("dvEmpty").style.display = "none";
		btnExcl.style.display = "block";
	}
	else
	{
		document.getElementById("dvDownload").style.display = "none";
		document.getElementById("dvEmpty").style.display = "block";
		btnExcl.style.display = "none";
	}
}


function fakeButtonClick( button )
{
	document.getElementById(button).click();
}

function adminSelectFile( file )
{
	if( file.value == "" )
		return;
	
	var strFile = getFileName(file.value);
	var strExt  = getFileExt( strFile );

	if( strExt.toUpperCase() != "PDF" && strExt.toUpperCase() != "DOC" && strExt.toUpperCase() != "JPG" && strExt.toUpperCase() != "JPEG" && strExt.toUpperCase() != "PNG" && strExt.toUpperCase() != "GIF")
	{
		alert("Tipo de arquivo inválido !");	
	}
	else
	{		
		/*
		document.getElementById("dvDownload").style.display = "block";		
		document.getElementById("dvEmpty").style.display	= "none";
		document.getElementById("lblArq").innerHTML			= strFile;
		document.getElementById("lblFileSize").innerHTML	= "?";
		document.getElementById("lblDtCriacao").innerHTML	= "?";
		document.getElementById("lblDtModif").innerHTML		= "?";
		*/
		document.getElementById("dvEmpty").style.display	= "none";
		document.getElementById("dvSelectedFile").style.display = "block";		
		document.getElementById("lblMsgSelectedFile").innerHTML	= strFile;
		
	}	
}

function getFileName( strFilePath )
{
	var arrAux = strFilePath.split("\\");
	return arrAux[ arrAux.length - 1];
}

function getFileExt( strFileName )
{
	var arrAux = strFileName.split(".");
	return arrAux[ arrAux.length - 1];
}
function enterKeyBusca( e )
{
	var whichCode	= (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13)
	{
		Busca();
		killEvent(e);
		return false;  // Not a valid key
	}						
}
