function checkNumber(field, e)
{
	var code = e.charCode;
	if (code == null || code=="undefined")
	{
		code = e.keyCode;
	}

	if (code  == 13)
	{
		x = 0;
	}
	else if ((code != 0) &&( code <= 47 || code > 57))
	{
		// 47 a 57 números de 0 a 9
		e.returnValue = false; 
		return false;
	}
	
	return true; 
}

//Verifica os dígitos e verifica se o banco é HSBC ou BANRISUL
function verifyDigitCont2(field,fieldBank,e)
{
	 var bank = fieldBank.options[fieldBank.selectedIndex].value;
	 var tecla = e.KeyCode;

	if(tecla == null || tecla == 'undefined')

	tecla = e.charCode;
	if (tecla == 13)
	{
		x = 0;
	}
	//aceita a letra 'x'
	 if (document.all)
	 {
		if (bank != "399" && bank != "41" )
			if (field.value.length > 0)
				e.returnValue = false;

		if(e.keyCode != 88 && e.keyCode != 120)
		{
			if(e.keyCode <= 45 || e.keyCode > 57)
			{
				e.returnValue = false;
			}
		}
	}
	else
	{
		if (bank != "399" && bank != "41" )
			if (field.value.length > 0)
			{
				if(tecla != 0)
				{
					e.returnValue = false;
					return false;
				}
			}

		if(tecla != 88 && tecla != 120)
		{
			if((tecla <= 45 || tecla > 57)&&(tecla != 0))
			{
				e.returnValue = false;
				return false;
			}
		}
	}
}

//Valida o digito da conta
function verifyDigitCont(field,e)
{
	var tecla = e.KeyCode;

	if (tecla == null || tecla == 'undefined')

	tecla = e.charCode;
	if(tecla == 13)
	{
		x = 0;
	}
	//aceita a letra 'x'

	if (document.all)
	{
		if(e.keyCode != 88 && e.keyCode != 120)
		{
			if(e.keyCode <= 45 || e.keyCode > 57)
			{
				e.returnValue = false;
			}
		}
	}
	else
	{
		if(tecla != 88 && tecla != 120)
		{
			if((tecla <= 45 || tecla > 57)&&(tecla != 0))
			{
				e.returnValue = false;
				return false;
			}
		}
	}
}

// Assumes that date is valid and using (dd/mm/yyyy)
function is_under_eighteen(date)
{
	var year = parseInt(date.substr(6,4));
	var month = date.substr(3,2);
	var day = date.substr(0,2);
	
	var diffMls = new Date();
	var now = new Date();
	var age;
	
	diffMls.setDate(day)
	diffMls.setMonth(month - 1);
	diffMls.setFullYear(year + 18);
	if(diffMls > now)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// check_date copyright:
// This script and many more are available free online at
// The JavaScript Source!! http://javascript.internet.com
// Original:  Torsten Frey (tf@tfrey.de) 
// Web Site:  http://www.tfrey.de

function check_date(field)
{

	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var DateTemp = "";
	var seperator = "/";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
	err = 0;
	DateValue = DateField.value;

	/* Delete all chars except 0..9 */
	/* Always change date to 8 digits - string*/
	/* if year is entered as 2-digit / always assume 20xx */
	if (DateValue.length == 6) 
	{
		DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); 
	}
	if (DateValue.length != 10) 
	{
		err = 19;
	}
	/* year is wrong if year = 0000 */ 
	year = DateValue.substr(6,4);
	if (year == 0 || year < 1900) 
	{
		err = 20;
	}
	/* Validation of month*/
	month = DateValue.substr(3,2);
	
	if ((month < 1) || (month > 12)) 
	{
		err = 21;
	}
	/* Validation of day*/
	day = DateValue.substr(0,2);
	if (day < 1) 
	{
		err = 22;
	}
	/* Validation leap-year / february / day */
	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) 
	{
		leap = 1;
	}
	if ((month == 2) && (leap == 1) && (day > 29)) 
	{
		err = 23;
	}
	if ((month == 2) && (leap != 1) && (day > 28)) 
	{
		err = 24;
	}
	/* Validation of other months */
	if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) 
	{
		err = 25;
	}
	if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) 
	{
		err = 26;
	}
	/* if 00 ist entered, no error, deleting the entry */
	if ((day == 0) && (month == 0) && (year == 00)) 
	{
		err = 0; day = ""; month = ""; year = ""; seperator = "";
	}

	if (err != 0) 
	{
		alert('Formato da data invalido');
		field.value = "";
		return false;
	}

	if(DateValue == "")
	{
		return false;
	}

	return true;
}

function checkphone(field,e)
{
	if(field.value != "")
	{
		if(field.value.length < 11 || field.value.length > 12 )
		{
			alert('Formato inválido');
			field.value = "";
			field.focus();
			return false;
		}
	}
	return true;
}

function visible()
{
	if($('divAdd').style.display == "none")
	{
		$('divAdd').style.display = "block";
		$('box_quote_seta').src = "../im/bt_setaup.gif";
		$('box_quote_label').innerHTML = "Clique para compactar";
	}
	else
	{
		$('divAdd').style.display = "none";
		$('box_quote_seta').src = "../im/bt_setadw.gif";
		$('box_quote_label').innerHTML = "Clique para detalhes";
	}
}

function responder(opt)
{
	var obj = 'div_resp_' + opt;
	
	if($(obj).style.display == "none")
	{
		$(obj).style.display = "block";
	}
	else
	{
		$(obj).style.display = "none";
	}
}

function showAlert()
{
	var obj = $('alertbox');
	obj.style.display = "";
	obj.style.height = screen.height - 180;
	obj.style.width = document.body.clientWidth + 10;
}

function showAlert2()
{
	var obj = $('alertbox_email');
	obj.style.display = "";
}

function closeBox2()
{
	var obj = $('alertbox_login');
	obj.style.display = "none";
	
	var obj2 = $('alertbox_contato');
	obj2.style.display = "block";
}

function closeBox()
{
	var obj = $('alertbox');
	obj.style.display = "none";
}

function showDivErroAteOn(dados)
{
	if (dados.responseText == -1)
	{
		$('divErroAteOn').show();
		$('divErroEmail').hide();
		$('divErroSenha').hide();
	}
	else if(dados.responseText == 1)
	{
		window.location = "../../common/message.aspx";
	}
}

// Invocado por 'tentar novamente'
function showSenhaAndEmail()
{
	$('password').value = "";
	$('email').value = "";
	$('divErroAteOn').hide();
	$('divErroSenha').show();
}

function closeError()
{
	$("errormsg").style.display = "none";
}

function showError(str)
{
	$("errormsg").style.display = "block";
	$("labelmsg").innerHTML = str;
}

function showCSR()
{
	$("CSR").style.display = "block";
}

function closeCSR()
{
	$("CSR").style.display = "none";
}

function showDivErroEmail()
{
	$('divErroEmail').style.display = "";
}

function are_preconditions_satisfied(e)
{
	if (!blnResponsibleAndAttorney)
	{
		alert(proceedMessageResponsibleAndAttorney);
		return false;
	}

	if (!blnCPF)
	{
		alert(proceedMessageCPF);
		return false;
	}

	if (!blnLogin)
	{
		alert(proceedMessageLogin);
		return false;
	}

	if (!blnRepresent)
	{
		alert(proceedRepresent);
		return false;
	}

	if (!canProceedVinculo)
	{
		alert(proceedVinculo);
		return false;
	}

	if (!canTradeByYourOwn)
	{
		alert(proceedTradeByYourOwn);
		return false;
	}

	if (!canProceedPortifolio)
	{
		alert(proceedPortifolio);
		return false;
	}

	if (!blnPoliticalExposedPerson)
	{
		alert(proceedMessagePoliticalExposedPerson);
		return false;
	}
	
	if (!canProceedOrder)
	{
		alert(proceedOrder);
		return false;
	}
	
	if (!blnZipcode)
	{
		alert("CEP inválido.");
		return false;
	}
	
	if (!canProceed && noMessage)
	{
		alert(proceedMessage);
		return false;
	}
	else if (!canProceed && !noMessage)
	{
		return false;
	}

	return FormValidation.validate(e);
}

function init_form_validation_hooks()
{
	var form = $('mainform');

	if (form != null)
	{
		form.onsubmit = are_preconditions_satisfied;;
	}
	
	FormValidation.setEvents();
}

function change_to_individual(isIndividualAlready, isTestDrive)
{
	if (isIndividualAlready) return;
	
	if (isTestDrive)
	{
		window.location.href = '../ProspectIndividualWizard/BasicInformationStep.win';
	}
	else
	{
		window.location.href = '../RegistrationIndividualWizard/BasicInformationStep.win';
	}
}

function change_to_company(isCompanyAlready, isTestDrive)
{
	if (isCompanyAlready) return;
	
	if (isTestDrive)
	{
		window.location.href = '../ProspectCompanyWizard/BasicInformationStep.win';
	}
	else
	{
		window.location.href = '../RegistrationCompanyWizard/BasicInformationStep.win';
	}
}

function loadCities(ufField)
{
	if (ufField.selectedIndex != 0)
	{
		var url = '../RegistrationServices/LoadCities.win';
		var pars = 'state=' + ufField.options[ufField.selectedIndex].value;
		new Ajax.Request(url,{method: 'post', parameters: pars});
	}
}

function VerifyCNPJ(cnpj,company)
{
	if (cnpj != "")
	{
		var url = '../RegistrationServices/CheckCNPJ.win';
		var pars = 'cnpj=' + cnpj + '&company=' + company;
		var myAjax = new Ajax.Request(url,{method: 'post', parameters: pars});
	}
}

function VerifyCPF(login,cpf)
{
	if (cpf != "")
	{
		var url = '../RegistrationServices/CheckCPF.win';
		var pars = 'cpf=' + cpf;
		new Ajax.Request(url,{method: 'post', parameters: pars});
	}
}

function VerifyResponsibleCPF(cpf,ResponsibleCPF)
{
	blnResponsibleAndAttorney = true;

	if (cpf != "")
	{
		if(cpf != ResponsibleCPF)
		{
		
			var url = '../RegistrationServices/CheckCPF.win';
			var pars = 'cpf=' + cpf + '&responsible=true';
			new Ajax.Request(url,{method: 'post', parameters: pars});
		
			getResponsibleName(cpf);
		
		}
		else
		{
			alert("O CPF não pode ser o mesmo do titular.");
			document.getElementById("step2_Responsible_BasicData_CPF").value = '';
			document.getElementById("step2_Responsible_BasicData_Name").value = '';
			document.getElementById("step2_Responsible_ResponsibleClassificationType").selectedIndex = 0;
		}
	}
	else
	{
		document.getElementById("step2_Responsible_BasicData_CPF").value = '';
		document.getElementById("step2_Responsible_BasicData_Name").value = '';
		document.getElementById("step2_Responsible_ResponsibleClassificationType").selectedIndex = 0;
	}
}


function VerifyAttorneyCPF(cpf,AttorneyCPF)
{
	blnResponsibleAndAttorney = true;

	if (cpf != "")
	{
		if(cpf != AttorneyCPF)
		{

			var url = '../RegistrationServices/CheckCPF.win';
			var pars = 'cpf=' + cpf + '&represent=true';
			new Ajax.Request(url,{method: 'post', parameters: pars});
		
			getAttorneyName(cpf);
		
		}
		else
		{
			alert("O CPF não pode ser o mesmo do titular.");
			document.getElementById("step3_Representative_BasicData_CPF").value = '';
			document.getElementById("step3_Representative_BasicData_Name").value = '';
		}
	}
	else
	{
		document.getElementById("step3_Representative_BasicData_CPF").value = '';
		document.getElementById("step3_Representative_BasicData_Name").value = '';
	}
}

function getResponsibleName(cpf)
{
		var url = '../RegistrationServices/getResponsibleAndAttorneyName.win';
		var pars = 'cpf=' + cpf + '&responsible=true';
		new Ajax.Request(url, {method: 'post', parameters: pars});
}

function getAttorneyName(cpf)
{
		var url = '../RegistrationServices/getResponsibleAndAttorneyName.win';
		var pars = 'cpf=' + cpf + '&represent=true';
		new Ajax.Request(url, {method: 'post', parameters: pars});
}

function VerifyRepresentCPF(cpf)
{
	if (cpf != "")
	{
		var url = '../RegistrationServices/CheckCPF.win';
		var pars = 'cpf=' + cpf + '&represent=true';
		new Ajax.Request(url,{method: 'post', parameters: pars});
	}
}

function VerifyRepresentCNPJ(cnpj)
{
	if (cnpj != "")
	{
		var url = '../RegistrationServices/CheckCNPJ.win';
		var pars = 'cnpj=' + cnpj + '&represent=true';		
		var myAjax = new Ajax.Request(url,{method: 'post', parameters: pars});        
	}
}

function VerifyPrimaryCPF(cpf,indice)
{
	if (cpf != "")
	{
		var url = '../RegistrationServices/CheckCPF.win';
		var pars = 'cpf=' + cpf + '&Primary=true' + '&indice=' + indice.toString();
		new Ajax.Request(url,{method: 'post', parameters: pars});
	}
}

/* Check Login */
function CheckCPF(login,cpf,value,Individual)
{
	if (cpf != "")
	{
		var url = '../RegistrationServices/CheckCPF.win';
		var pars = 'login=' + login + '&cpf=' + cpf + '&value=' + value + '&Individual=' + Individual ;;
		new Ajax.Request(url,{method: 'post', parameters: pars});
	}
}

function CheckLogin(login,cpf)
{
	if (login != "")
	{
		var url = '../RegistrationServices/CheckLogin.win';
		var pars = 'login=' + login + '&cpf=' + cpf;;
		new Ajax.Request(url,{method: 'post', parameters: pars});
	}
}

function VerifyLoginAndCnpj(login, cnpj)
{
	if (login != "")
	{
		var url = '../RegistrationServices/CheckLoginAndCNPJ.win';
		var pars = 'login=' + login + '&cnpj=' + cnpj;
		new Ajax.Request(url,{method: 'post', parameters: pars});
	}
}
function SendPassword(type, id, email)
{
	if (email == '')
	{
		alert('Informe seu email');
		return;
	}
	
	var url = '../RegistrationServices/SendPassword.win';
	var pars = 'type=' + type + '&id=' + id + '&email=' + email;
	new Ajax.Request(url,{method: 'post', parameters: pars});
}

function VerifySenha(type, id, password,represent,procurador)
{
	if (password == '')
	{
		alert('Informe sua senha');
		return;
	}
	
	var url = '../RegistrationServices/RetrieveExistingData.win';
	var where = isTestDrive ? 'testdrive' : 'registration';
	var pars = 'id=' + id + '&password=' + password + '&where=' + where + '&type=' + type + '&represent=' + represent + '&procurador=' + procurador;
	new Ajax.Request(url,{method: 'post', parameters: pars});
}

function GetCEPData(index)
{
	var zip = "";
	if (index == 0)
	{
		zip = $F('basicdata_address_0_ZipCode');
	}
	else
	{
		zip = $F('basicdata_address_1_ZipCode');
	}
	
	if (zip != "")
	{
		VerifyZipCode(zip);
		var url = '../RegistrationServices/RetrieveAddressFromZip.win';
		var pars = 'zip=' + zip + '&index=' + index;
		new Ajax.Request(url, {method: 'post', parameters: pars});
	}
}

function GetCEPDataStep2()
{
	var zip = $F('step2_BussinesAddress_ZipCode');
	if (zip != "")
	{
		VerifyZipCode(zip);
		var url = '../RegistrationServices/RetrieveAddressFromZip.win';
		var pars = 'zip=' + zip + '&company=true';
		new Ajax.Request(url, {method: 'post', parameters: pars});
	}
}

function GetCEPDataStep2AlternateAddress()
{
	var zip = $F('step2_AlternateAddress_ZipCode');
	if (zip != "")
	{
		VerifyZipCode(zip);
		var url = '../RegistrationServices/RetrieveAddressFromZip.win';
		var pars = 'zip=' + zip + '&alternate=true';
		new Ajax.Request(url, {method: 'post', parameters: pars});
	}
}

function GetCEPDataStep3Represent()
{
	var zip = $F('step3.Responsible.Address.ZipCode');
	if (zip != "")
	{
		VerifyZipCode(zip);
		var url = '../RegistrationServices/RetrieveAddressFromZip.win';
		var pars = 'zip=' + zip + '&represent=true';
		new Ajax.Request(url, {method: 'post', parameters: pars});
	}
}

function VerifyZipCode(zip)
{
	var regex = /^\d{5}-\d{3}$/;
	if (regex.test(zip))
	{
		blnZipcode = true;
	}
	else
	{
		blnZipcode = false;
	}
}

function checkNationality(selectField)
{
	var countrySel = $('personalData_BornCountry');
	var itemSelected = selectField.options[selectField.selectedIndex].value;

	if (itemSelected == 'Foreigner') // Estrangeiro
	{
		document.getElementById("nationalityUF").style.display = "none";
		document.getElementById("nationalityCity").style.display = "none";
		
		FormValidation.disableFor(['personalData_BornState','personalData_BornCity','personalData_EmissorDate']);
		FormValidation.enableFor(['personalData_BornCountry']);
		document.getElementById('Div_BrasileiroNaturalizado').style.display = "none";
	}
	else if(itemSelected == 'Brasilian')
	{
		for(var i=0; i < countrySel.options.length; i++)
		{
			if (countrySel.options[i].value == 'BRA')
			{
				countrySel.selectedIndex = i;
				document.forms[0].personalData_BornCountry.selectedIndex = i;
				break;
			}
		}
		$('nationalityUF').show();
		$('nationalityCity').show();
		FormValidation.enableFor(['personalData_BornState','personalData_BornCity','personalData_EmissorDate']);
		FormValidation.disableFor(['personalData_BornCountry']);
		document.getElementById('Div_BrasileiroNaturalizado').style.display = "none";
	}
	else
	{
		document.getElementById('Div_BrasileiroNaturalizado').style.display = "block";
		for(var i=0; i < countrySel.options.length; i++)
		{
			if (countrySel.options[i].value == 'BRA')
			{
				countrySel.selectedIndex = i;
				document.forms[0].personalData_BornCountry.selectedIndex = i;
				break;
			}
		}
		$('nationalityUF').show();
		$('nationalityCity').show();
		FormValidation.enableFor(['personalData_BornState','personalData_BornCity','personalData_EmissorDate']);
		FormValidation.disableFor(['personalData_BornCountry']);
	}
}

function CheckCities(selectField)
{
	var citySel = document.getElementById('personalData_BornCity');
	for(var i = 0; i < citySel.options.length; i++)
		{
			if (citySel.options[i].value == selectField)
			{
				document.forms[0].personalData_BornCity.selectedIndex = i;
				break;
			}
		}
}

function CheckCountry(selectField)
{
	var countrySel = document.getElementById('personalData_BornCountry');
	 for(var i = 0; i < countrySel.options.length; i++)
		{
			if (countrySel.options[i].value == selectField)
			{
				document.forms[0].personalData_BornCountry.selectedIndex = i;
				break;
			}
		}
}

function insertBankRow(afterIndex)
{
	var included = insertRow(bankRows, afterIndex, 'BankPropertyInfoStep-InsertBankRow.win', 'tbBankContainer')
	
	if (!included)
	{
		alert("Você pode cadastrar até quatro contas bancárias");
	}
}

function insertPropertyRow(afterIndex)
{
	var included = insertRow(propRows, afterIndex, 'BankPropertyInfoStep-InsertPropertyRow.win', 'propertyContainer')
	
	if (!included)
	{
		alert("Você pode cadastrar até quatro imóveis");
	}
}

function insertLegalRepRow(afterIndex)
{
	var included = insertRow(legalRepsRows, afterIndex, 'BankPropertyInfoStep-InsertLegalRepRow.win', 'tbLegalRepContainer')
	
	if (!included)
	{
		alert("Você pode cadastrar até quatro representantes legais");
	}
}

function insertStakeHolderRow(afterIndex)
{
	var included = insertRow(stakeHolderRows, afterIndex, 'PeopleInfoStep-InsertStakeHolderRow.win', 'stakeHolderContainer')
	
	if (!included)
	{
		alert("Você pode cadastrar até quatro controladores");
	}
}

function insertAuthPersonRow(afterIndex)
{
	var included = insertRow(authPersonsRows, afterIndex, 'PeopleInfoStep-InsertAuthPersonRow.win', 'authContainer')
	
	if (!included)
	{
		alert("Você pode cadastrar até quatro pessoas");
	}
}
function insertRelatedControllersRow(afterIndex)
{
	var included = insertRow(relatedControllersRows, afterIndex, 'PeopleInfoStep-InsertRelatedControllersRow.win', 'relatedControllersContainer')
	
	if (!included)
	{
		alert("Você pode cadastrar até quatro pessoas");
	}

}

function insertRow(varContainer, afterIndex, url, containerName)
{
	var included = false;
	
	for(var k = 0; k < varContainer.length; k++)
	{
		if (varContainer[k] == -1)
		{
			varContainer[k] = k;
			new Ajax.Request(url, {method: 'post', onComplete:FormValidation.setEvents, parameters: 'index=' + (k+1) + '&afterId=' + containerName + afterIndex});
			included = true;
			break;
		}
	}
	
	return included;
}

function fillPlaceholder(varContainer)
{
	for(var k = 0; k < varContainer.length; k++)
	{
		if (varContainer[k] == -1)
		{
			varContainer[k] = k;
			break;
		}
	}
}

function deleteBankRow(elemId, index)
{
	Element.replace(elemId, '');
	bankRows[index - 1] = -1;
}

function deletePropertyRow(elemId, index)
{
	Element.replace(elemId, '');
	propRows[index - 1] = -1;
}

function deleteLegalRepRow(elemId, index)
{
	Element.replace(elemId, '');
	legalRepsRows[index - 1] = -1;
}

function deleteStakeHolderRow(elemId, index)
{
	Element.replace(elemId, '');
	stakeHolderRows[index - 1] = -1;
	UpdateStakeHolders(index);
}

function deleteAuthPersonRow(elemId, index)
{
	Element.replace(elemId, '');
	authPersonsRows[index - 1] = -1;
	UpdateAuthorizedPersons(index);
}

function deleteRelatedControllersRow(elemId, index)
{
	Element.replace(elemId, '');
	relatedControllersRows[index - 1] = -1;
	UpdateControllers(index);
}

function enableorDisabledRepresent(field)
{
	if(field)
	{
		document.getElementById("HasRepresent").checked = false;
		document.getElementById("parentsinfo").style.display = "none";

		//Limpa os campos
		document.getElementById("step2_Responsible_BasicData_CPF").value = "";
		document.getElementById("step2_Responsible_BasicData_Name").value = "";

		//Desabilita os campos
		document.getElementById("step2_Responsible_ResponsibleClassificationType").selectedIndex = 0;
		FormValidation.disableFor(['step2_Responsible_BasicData_CPF','step2_Responsible_ResponsibleClassificationType']);
		canProceed = true;
	}

	if (is_under_eighteen(document.getElementById("personalData_BirthDate").value))
	{
		if(field == false && document.getElementById("HasRepresent").checked == false)
		{
			blnRepresent = false;
			proceedRepresent = "É obrigatório o cadastro do responsável legal."
		}
		else
		{
			blnRepresent = true;
		}
	}
	else
	{
		blnRepresent = true;
	}
}

function enableOrDisableParents()
{
	var emancipado = false;
	var represent = false;

	if (is_under_eighteen(document.getElementById("personalData_BirthDate").value))
	{
		if(document.getElementById("personalData_IsEmancipaded").checked)
		{
			emancipado = true;
		}
	}

	if( document.getElementById("HasRepresent").checked)
	{
		represent = true;
	}

	if(represent == false && emancipado == false || represent == false && emancipado)
	{
		document.getElementById("parentsinfo").style.display = "none";

		//Limpa os campos
		document.getElementById("step2_Responsible_BasicData_CPF").value = "";

		//Desabilita os campos
		document.getElementById("step2_Responsible_ResponsibleClassificationType").selectedIndex = 0;
		FormValidation.disableFor(['step2_Responsible_BasicData_CPF','step2_Responsible_ResponsibleClassificationType']);
		document.getElementById("step2_Responsible_BasicData_Name").value = "";
		canProceed = true;
		blnResponsibleAndAttorney = true;
	}
	else
	{
		document.getElementById("parentsinfo").style.display = "block";
		FormValidation.enableFor(['step2_Responsible_BasicData_CPF','step2_Responsible_ResponsibleClassificationType']);
	}
	
	if (is_under_eighteen(document.getElementById("personalData_BirthDate").value))
	{
		if(represent == false && emancipado == false)
		{
			blnRepresent = false;
			proceedRepresent = "É obrigatório o cadastro do responsável legal."
		}
		else
		{
			blnRepresent = true;
		}
	}
	else
	{
		blnRepresent = true;
	}
}

function CalculateFinancialSituationWithMonthIncomes()
{
	var ShareholderEquitity = parseFloat(document.getElementById("ExtraData_ShareholderEquitity").value.replace('.','').replace(',','.'));
	var Others = parseFloat(document.getElementById("ExtraData_Others").value.replace('.','').replace(',','.'));
	var MonthIncomes = parseFloat(document.getElementById("ExtraData_MonthIncomes").value.replace('.','').replace(',','.'));
	var OthersIncomes = parseFloat(document.getElementById("ExtraData_OthersIncomes").value.replace('.','').replace(',','.'));

	if(ShareholderEquitity + Others + MonthIncomes + OthersIncomes < 100)
	{
		alert("Posição patrimonial insuficiente para operar em bolsa. Por favor reveja os dados patrimoniais informados");
		return false;
	}
	else
	return true;
}

function CalculateFinancialSituationWithoutMonthIncomes()
{
	var ShareholderEquitity = parseFloat(document.getElementById("ExtraData_ShareholderEquitity").value.replace('.','').replace(',','.'));
	var Others = parseFloat(document.getElementById("ExtraData_Others").value.replace('.','').replace(',','.'));
	var OthersIncomes = parseFloat(document.getElementById("ExtraData_OthersIncomes").value.replace('.','').replace(',','.'));

	if(ShareholderEquitity + Others + OthersIncomes < 100)
	{
		alert("Posição patrimonial insuficiente para operar em bolsa. Por favor reveja os dados patrimoniais informados");
		return false;
	}
	else
	return true;
}

function VerifyFinancialSituation()
{
	var employed = document.getElementById("Employed").value;
	if(employed == "False")
	{
		return CalculateFinancialSituationWithoutMonthIncomes();
	}
	else
	{
		return CalculateFinancialSituationWithMonthIncomes();
	}
}

function showAndHide(field,indice)
{
	if(field.checked)
	{
		document.getElementById('tblconjunta' + indice).style.display = "block";
		FormValidation.enableFor(["BankAccounts_" + indice + "_PrimaryName","BankAccounts_" + indice + "_PrimaryCPF"]);
	}
	else
	{
		document.getElementById("BankAccounts_" + indice + "_PrimaryName").value = "";
		document.getElementById("BankAccounts_" + indice + "_PrimaryCPF").value = "";
		FormValidation.disableFor(["BankAccounts_" + indice + "_PrimaryName","BankAccounts_" + indice + "_PrimaryCPF"]);   
		document.getElementById("tblconjunta" + indice).style.display = "none";
	}
}

function showAndHideDigitAgency(indice)
{
	var field  = document.getElementById("BankAccounts_" + indice + "_BankCode");
	var bank = field.options[field.selectedIndex].value;

	
	//Só exibe o digito da agência,quando for banco do Brasil.
	if (bank == '1')
	{
		document.getElementById("tdDigitAgency" + indice).style.display = "block";
		FormValidation.enableFor(["BankAccounts_" + indice + "_AgencyDigit"]);
	}
	else
	{
		document.getElementById("tdDigitAgency" + indice).style.display = "none";
		FormValidation.disableFor(["BankAccounts_" + indice + "_AgencyDigit"]);
		document.getElementById("BankAccounts_" + indice + "_AgencyDigit").value = "";
	}
	
	 //Verifica se deve ou não exibir do dígito da conta
	if (bank == '745' || bank == '752'|| bank == '21' || bank == '399')
	{
		if(bank == '21' || bank == '399')
			document.getElementById("dvAccountDigit" + indice).style.display = "block";
		else
			document.getElementById("dvAccountDigit" + indice).style.display = "none";

		FormValidation.disableFor(["BankAccounts_" + indice + "_AccountDigit"]);
		document.getElementById("BankAccounts_" + indice + "_AccountDigit").value = "";
	}
	else
	{
		document.getElementById("dvAccountDigit" + indice).style.display = "block";
		FormValidation.enableFor(["BankAccounts_" + indice + "_AccountDigit"]);
	}
}


function showAndHideAttorney(value)
{
	if(! value)
	{
		//Desabilita os campos
		FormValidation.disableFor(['step3_Representative_BasicData_CPF']);
		canProceed = true;
		document.getElementById("tblAttorney").style.display = "none";
	}
	else
	{
		document.getElementById("tblAttorney").style.display = "block";
		//Limpa os campos

		//Desabilita os campos
		FormValidation.enableFor(['step3_Representative_BasicData_CPF']);
	}
}

function showAndHideTradeByYourOwn(value)
{
	if(! value)
	{
		canTradeByYourOwn = false;
		proceedTradeByYourOwn = "Somente clientes que operam por conta própria, podem completar o cadastro via internet."
	}
	else
	{
		canTradeByYourOwn = true;
	}
}

function BlockCtrl(e)
{

	if(document.all)
	{
		var ctrl=window.event.ctrlKey;
		var tecla=window.event.keyCode;

		if (ctrl && tecla == 86) 
		{
			 event.keyCode=0;
			 event.returnValue=false;
		}
	}
}

function showAndHideNottery(value)
{
	if(value)
	{
		document.getElementById("dvnottary").style.display = "block";
		FormValidation.enableFor(["nottaryInfo"]);
	}
	else
	{
		FormValidation.disableFor(["nottaryInfo"]);
		document.getElementById("nottaryInfo").value = "";
		document.getElementById("dvnottary").style.display = "none";
	}
}

function openFeedBack()
{
	var obj = document.getElementById("feedback");
	if (obj.style.display == 'none')
	{
		obj.style.display = 'block';
	}
	else
	{
		obj.style.display = 'none';
	}
}

function sendMessage(ident)
{
	var rdo = "???";
	if (document.getElementById('rdoFeedback1').checked)
		rdo = "Ótima";
	else if (document.getElementById('rdoFeedback2').checked)
		rdo = "Boa";
	else if (document.getElementById('rdoFeedback3').checked)
		rdo = "Regular";
	else if (document.getElementById('rdoFeedback4').checked)
		rdo = "Ruim";

	if (rdo != "???" || $F("txtMsg") != "")
	{
		var msg = document.getElementById("txtMsg").value;
		var url = '../RegistrationServices/sendFeedbackMessage.win';
		var pars = 'rdo=' + rdo + '&msg=' + msg + '&ident=' + ident;
		var myAjax = new Ajax.Request(url,{method: 'post', parameters: pars, onComplete: sendMessageResponse});        
	}
}

function sendMessageResponse(originalRequest)
{
	var str = '<p align="center" style="color:#69849F;font-weight:bold" >Sua avaliação e comentarios foram enviados com sucesso !</p>';
	str += '<p align="center" style="color:#69849F;" >Vamos avaliar suas sugestões.<br/>Muito obrigado pela sua colaboração.</p>';
	str += '<p align="center"><a href="javascript:openFeedBack();" class="bt"> Fechar </a></p>';
	str += '<p style="height:78px;">&nbsp;</p>';
	document.getElementById('feedBackContent').innerHTML = str;
}

var feedoldcolor = "";
function changeColorFeedBack(opt){
	$(opt).style.color = '#FF9304';
	if (feedoldcolor != "") $(feedoldcolor).style.color='#7C7A7B';
	feedoldcolor=opt;
}

function enviarFeedBack(clientid)
{
	sendMessage(clientid);
}

function checkNumberLogin(field, e)
{
	if(document.all)
	{
		var tecla=window.event.keyCode;

		if(tecla == 13)
			x=0;
		else if(tecla == 47 || tecla < 45 || tecla > 57 && tecla < 64 || tecla > 125)
			return false;
	}
	else
	{
		var tecla = e.charCode;
		if(tecla == 13)
			x=0;
		else if(tecla == 47 || tecla < 45 && tecla > 0 ||  tecla > 57 && tecla < 64 || tecla > 125)
			return false;
	}
}

function checkCpfCnpj(number)
{
	if(number.length < 12)
	{
		VerifyRepresentCPF(number);
	}
	else
	{
		VerifyRepresentCNPJ(number);
	}
}

function openPopupResponsibleAndAttorney(url,name,features)
{
	window.open(url,name,features);
}

function VerifyRepresentDate(date)
{
	var today=new Date();
	var todayd=today.getDate();
	var todaym=today.getMonth();
	var todayy=today.getFullYear();

	todaym += 1;
	if (todaym.toString().length == 1)
		todaym = "0" + todaym;

	if(todayd.toString().length == 1)
		todayd = "0" + todayd;

	var dataAtual = todayd + "/" + todaym + "/" + todayy;

	if ( parseInt( date.value.split( "/" )[2].toString() + date.value.split( "/" )[1].toString() + date.value.split( "/" )[0].toString() ) > parseInt( dataAtual.split( "/" )[2].toString() + dataAtual.split( "/" )[1].toString() + dataAtual.split( "/" )[0].toString() ) ) 
	{
		alert("A data não pode ser maior que a data de hoje.");
		date.value = "";
		return false;
	}
}

function VerifyCpfRepresent()
{
	var text='<div>';
	text += '  <table width="405" border="0" cellspacing="0" cellpadding="0">'
	text += '  <tr>'
	text += '    <td><img src="' + SITE_ROOT + '/im/topProcurador.gif" width="405" height="11" /></td>'
	text += ' </tr>'
	text += ' <tr>'
	text += '    <td align="center" background=" ' + SITE_ROOT + '/im/bgProcurador.gif" style="padding-left:15px; padding-right:10px;">'
	text += ' <table width="100%" border="0" cellspacing="0" cellpadding="0">'
	text += '	<tr>'
	text += '				<td width="368" align="left" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#c80002; font-weight:bold"><img src="' + SITE_ROOT + '/im/icoEx.gif" width="27" height="24" align="absmiddle"/> &nbsp;&nbsp;&nbsp;CPF j&aacute; cadastrado</td>'
	text += '				</tr>'
	text += '				<tr>'
	text += '					<td height="20" colspan="2">&nbsp;</td>'
	text += '				</tr>'
	text += '				<tr>'
	text += '					<td colspan="2" class="texto_box" style="text-align:left;">O procurador ou representante legal j&aacute; possui cadastro conosco. Por favor, clique no bot&atilde;o a baixo para fechar esta janela e informe o n&uacute;mero do CPF de seu procurador ou representante legal em seu cadastro. </td>'
	text += '				</tr>'
	text += '				<tr>'
	text += '					<td height="35" colspan="2">&nbsp;</td>'
	text += '				</tr>'
	text += '				<tr>'
	text += '					<td colspan="2" align="center"><a href="javascript:self.close();"><img src="' + SITE_ROOT + '/im/btFecharDiv.gif" width="298" height="30" /></a></td>'
	text += '				</tr>'
	text += '				<tr>'
	text += '					<td height="35" colspan="2">&nbsp;</td>'
	text += '				</tr>'
	text += '			</table></td>'
	text += '		</tr>'
	text += '		<tr>'
	text += '			<td><img src="' + SITE_ROOT + '/im/subProcurador.gif" width="405" height="17" /></td>'
	text += '		</tr>'
	text += '	</table>'
	text += '</div>'

	Dialog.info(text, {width:670,height:300, className: "alphacube", destroyOnClose: true, wiredDrag: true });
}

function UpdateControllers(total)
{
	document.getElementById('TotalControllers').value = total;
}
function UpdateAuthorizedPersons(total)
{
	document.getElementById('TotalAuthorizeds').value = total;
}
function UpdateStakeHolders(total)
{
	document.getElementById('TotalStakes').value = total;
}

function VerifyAllFields(totalStakeHolders, totalAuthPersons, totalControllers)
{
	var flagControllers = true;
	var flagAuthorizeds = true;
	var flagStakes = true;
	var objCpf = '';
	var objCpf2 = '';
	var lbl1 = '';
	var lbl2 = '';
	var str = "";
	var message = '';
	var flagLblStake = new Array();
	var flagLblControllers = new Array();
	var flagLblAuthorized = new Array();
	noMessage = false;
	for(i=0; i<totalStakeHolders; i++)
	{
		flagLblStake[i] = true;
	}
	for(i=0; i<totalAuthPersons; i++)
	{
		flagLblAuthorized[i] = true;
	}
	for(i=0; i<totalControllers; i++)
	{
		flagLblControllers[i] = true;
	}

	
	for(i = 0; i < totalStakeHolders - 1; i++)
	{
		for(j = i+1; j < totalStakeHolders; j++)
		{
			objCpf = 'ControlersAndAdministrators_'+i+'_CPF_CNPJ';
			objCpf2 = 'ControlersAndAdministrators_'+j+'_CPF_CNPJ';
			lbl1 = 'lbl_ControlersAndAdministrators_'+i+'_CPF_CNPJ';
			lbl2 = 'lbl_ControlersAndAdministrators_'+j+'_CPF_CNPJ';
			if(document.getElementById(objCpf).value == document.getElementById(objCpf2).value)
			{
				canProceed = false;
				document.getElementById(lbl1).style.color="red";
				document.getElementById(lbl2).style.color="red";
				flagLblStake[i] = false;
				flagLblStake[j] = false;
				
				if(flagStakes == true)
				{
					message += '<li> Você não pode cadastrar dois ou mais controladores <br>com o mesmo CPF!';
					flagStakes = false;
				}
			}
			else
			{
				if(flagLblStake[i] == true)
					document.getElementById(lbl1).style.color="#6784A0";
				if(flagLblStake[j] == true)
					document.getElementById(lbl2).style.color="#6784A0";
			}
		}
	}
	
	for(i = 0; i < totalAuthPersons - 1; i++)
	{
		for(j = i+1; j < totalAuthPersons; j++)
		{
			objCpf = 'AuthorizedPersons_'+i+'_CPF_CNPJ';
			objCpf2 = 'AuthorizedPersons_'+j+'_CPF_CNPJ';
			lbl1 = 'lbl_AuthorizedPersons_'+i+'_CPF_CNPJ';
			lbl2 = 'lbl_AuthorizedPersons_'+j+'_CPF_CNPJ';
			if(document.getElementById(objCpf).value == document.getElementById(objCpf2).value)
			{
				canProceed = false;
				document.getElementById(lbl1).style.color="red";
				document.getElementById(lbl2).style.color="red";
				flagLblAuthorized[i] = false;
				flagLblAuthorized[j] = false;
				if(flagAuthorizeds == true)
				{
					message +='<li> Você não pode cadastrar duas ou mais pessoas autorizadas<br>com o mesmo CPF!';
					flagAuthorizeds = false;
				}
			}
			else
			{
				if(flagLblAuthorized[i] == true)
					document.getElementById(lbl1).style.color="#6784A0";
				if(flagLblAuthorized[j] == true)
					document.getElementById(lbl2).style.color="#6784A0";
			}
		}
	}

	for(i = 0; i < totalControllers - 1; i++)
	{
		for(j = i+1; j < totalControllers; j++)
		{
			objCpf = 'RelatedControllers_'+i+'_Cpf_CNPJ';
			objCpf2 = 'RelatedControllers_'+j+'_Cpf_CNPJ';
			lbl1 = 'lbl_RelatedControllers_'+i+'_Cpf_CNPJ';
			lbl2 = 'lbl_RelatedControllers_'+j+'_Cpf_CNPJ';
			if(document.getElementById(objCpf).value == document.getElementById(objCpf2).value)
			{
				canProceed = false;
				document.getElementById(lbl1).style.color="red";
				document.getElementById(lbl2).style.color="red";
				flagLblControllers[i] = false;
				flagLblControllers[j] = false;
				if(flagControllers == true)
				{
					message +='<li>Você não pode cadastrar dois ou mais controladores <br>com o mesmo CNPJ';
					flagControllers = false;
				}
			}
			else
			{
				if(flagLblControllers[i] == true)
					document.getElementById(lbl1).style.color="#6784A0";
				if(flagLblControllers[j] == true)
					document.getElementById(lbl2).style.color="#6784A0";
			}
		}
	}

	if(flagStakes == true && flagAuthorizeds == true && flagControllers == true)
	{
		canProceed = true;
		closeError();
	}
	else
	{
		showError(message);
	}
}

function showHolderAccount(field, index)
{
	var trCotitular = 'trCoTitular_'+index;
	var trTitular = 'trTitular_'+index;
	
	if(field.checked == true)
	{
		document.getElementById(trCotitular).style.display = "block";
		document.getElementById(trTitular).style.display = "none";
	}
	else
	{
		document.getElementById(trCotitular).style.display = "none";
		document.getElementById(trTitular).style.display = "block";
	}
}

function ValidAddressFields(field,e)
{
	var code = e.charCode;
	if (code == null || code == "undefined")
	{
		code = e.keyCode;
	}
	if (code  == 13)
	{
		x = 0;
	}
	else if ((code != 0) && (code == 44 || code == 47 || code == 46))
	{
		e.returnValue = false;
		return false;
	}
	
	return true; 
}

function blocksCharactersSpaceAndCommaAndSemicolon(e)
{
	var code = e.charCode;
	if(code == null || code == 'undefined')
	{
		code = e.keyCode;
	}
	if(code == 13)
	{
		x=0;
	}
	else if ((code != 0) && (code == 32 || code == 44 || code == 59))
	{
		e.returnValue = false;
		return false;
	}
	
	return true; 
}