//-------------------------------------------------------------
//
// Referente ao Selecionar Endereços.
//
//-------------------------------------------------------------

/**
 * Verifica a consistência dos dados do formalário
 * referente a 'novo usuário'. Para verificação do formulário
 * de endereço adicional a verificação é feita na função abaixo.
 */
 
function removeAddress(idAddress) {
	
	var url = '/entryPoint.php?plugin=shop&package=web&form=ajax&ajaxAction=removeAddress';
	
	// Parametros via POST.
	parametros = 'idAddress='+idAddress;
	
	var answer = confirm("Deseja realmente apagar este endereço?");
	
	// Verifica se foi confirmada a resposta.
	if (answer){	
		// Requisição Ajax pelo Prototype.
		new Ajax.Request(url ,
			{
				method:'post',
				parameters: parametros,
				
				onSuccess: function(e){
					var xml = e.responseXML;
					var response = xml.getElementsByTagName('result');
					alert(response[0].firstChild.data);
					
					if(response[0].firstChild.data == 'removido com sucesso!') {
						document.location.reload();
					}
				}
			}
		);
	}
	
}
	
	/*
 	
 	/*
}
 
/**
 * Faz a verificação dos campo do formulario Confirma Pagamento. 
 */
function validaConfirmaPagamento(){
	
	if($('nome').value == ""){
 		
 		alert("Por favor digite um nome.");
 		$('nome').style.background = "#FF0000";
 		$('nome').focus();
 		return false;
 	}
 	if($('email').value == ""){
 		
 		alert("Por favor digite um E-Mail.");
 		$('email').style.background = "#FF0000";
 		$('email').focus();
 		return false;
 	}
 	
 	if($('comentario').value == ""){
 		
 		alert("Por favor digite seu comentário.");
 		$('comentario').style.background = "#FF0000";
 		$('comentario').focus();
 		return false;	
 	}
	
	if($('banco').value == ""){
 		
 		alert("Por favor informe o Banco.");
 		$('banco').style.background = "#FF0000";
 		$('banco').focus();
 		return false;	
 	}
 	
 	if($('data').value == ""){
 		
 		alert("Por favor informe a Data.");
 		$('data').style.background = "#FF0000";
 		$('data').focus();
 		return false;	
 	}
 	
 	if($('valor').value == ""){
 		
 		alert("Por favor informe o Valor.");
 		$('valor').style.background = "#FF0000";
 		$('valor').focus();
 		return false;	
 	}
 	
 	
	
}
  
 
/**
 * Ajax para edição de endereço.
 */
function editAddress(idContact, idAddress) {
	
	// Endereço PHP.
	url = '/entryPoint.php?plugin=shop&package=web&form=ajax&ajaxAction=editAddress'; 
	
	// Parametros via POST.
	parametros = 'idContact='+idContact+'&idAddress='+idAddress;
	
	// Requisição Ajax pelo Prototype.
	new Ajax.Request(url ,
		{
			method:'post',
			parameters: parametros,
			
			onCreate: function() {
				
				$('aguarde').innerHTML = "Aguarde...";
				
			},
			
			onSuccess: function(transport){
				
				$('aguarde').innerHTML = "Editar endereço:";
				
				// Debug
				//var response2 = transport.responseText || "não foi retornado valor";
				//alert (response2);
				
				
				
				// Limpa os dados existentes no form.
				$('newAddress').reset();
				
				// XML com os dados do endereço.
				var response = transport.responseXML;
				
				// Altera os botões
				$('formButton').style.display = "none";
				$('formButtonEdit').style.display = "";
				$('formButtonCancel').style.display = "";
				
				// Inclui o id do endereço.
				$('idAddress').value = response.getElementsByTagName('idAddress')[0].firstChild.data;
				
				// Inclui os valores nos respectivos campos de endereço.
				$('formAddressPostalCode').value = response.getElementsByTagName('postalCode')[0].firstChild.data;
				$('formAddress').value = response.getElementsByTagName('address')[0].firstChild.data;
				$('formAddressNumber').value = response.getElementsByTagName('number')[0].firstChild.data;
				$('formAddressDistrict').value = response.getElementsByTagName('village')[0].firstChild.data;
				$('formAddressCity').value = response.getElementsByTagName('city')[0].firstChild.data;
				$('formAddressState').value = response.getElementsByTagName('state')[0].firstChild.data;
				
				// Nome
				$('formName').value = response.getElementsByTagName('name')[0].firstChild.data;
				
				// telefones
				$('formAddressDDD1').value = response.getElementsByTagName('ddDphone1')[0].firstChild.data;
				$('formAddressTelephone1').value =	response.getElementsByTagName('phone1')[0].firstChild.data;
				
				// Verifica se existe o telefone2.
				var telefone2 = response.getElementsByTagName('phone2')[0];
				if(telefone2 !== null){
					$('formAddressDDD2').value = response.getElementsByTagName('ddDphone2')[0].firstChild.data;
					$('formAddressTelephone2').value =	response.getElementsByTagName('phone2')[0].firstChild.data;
				}
				
				// Verifica se tem complemento
				complemento = response.getElementsByTagName('complement')[0];
				if(complemento !== null) {
					$('formAddressComplement').value = response.getElementsByTagName('complement')[0].firstChild.data;
				}
				
				// Verifica se tem referencia
				referencia = response.getElementsByTagName('reference')[0];
				if(referencia != null){
					$('addressReference').value = response.getElementsByTagName('reference')[0].firstChild.data;
				}
				
			},
		    
		    onFailure: function(){ 
		    		alert('Não foi possível realizar a requisição.') 
		    	}
		});
	
}

/**
 * Envia o formulario localizado em seleciona_endereco para edição.
 * 
 */
 
 function edit(form) {
 	
 	// Valida os campos.
 	if(!verifyAddAddress(form)){
 		return false;
 	}
 	$('newAddress').action = "/entryPoint.php?plugin=shop&package=web&acao=newAddress&tipo=edit";
 	$('newAddress').submit();
 	
 }
 	
/**
 * Envia o formulario localizado em meus_enderecos para edição.
 * 
 */
 
 function editEnderecos(form) {
 	
 	// Valida os campos.
 	if(!verifyAddAddress(form)){
 		return false;
 	}
 	$('newAddress').action = "/entryPoint.php?plugin=shop&package=web&acao=newAddress&tipo=edit&came=meusEnderecos";
 	$('newAddress').submit();
 	
 }

/**
 * Valida os telefones.
 */
 function telefones(){
 	
 	if (!verifyNewAddress()){return false};
 	
 		// Verifica DDD.
 	if($('DDD1').value == "") {
 		alert("Por favor digite um DDD.");
 		$('DDD1').style.background = "#FF0000";
 		$('DDD1').focus();
 		return false;
 		
 	}
 	
 	// Verifica Telefone.
 	if($('Telephone1').value == "") {
 		
 		alert("Por favor digite um telefone.");
 		$('Telephone1').style.background = "#FF0000";
 		$('Telephone1').focus();
 		return false;
 	}
 
 	
 
 	return true;	
 }

/**
 * Valida formulários dinamicamente.
 * Para incluir um campo na verificação basta adicionar um title com o nome do campo.
 * Ex:
 * <input type="text" id="nome" name="nome" title="Nome">
 * Por ter um title, esse input sera verificado.
 * 
 */
function checkForm(local){
	
	// Campos a serem verificados
	var arr = new Array('input','option','select','textarea');
	
	var titleValue = null;
	
	//var formName = new Array();
	
	for(var a=0; a < arr.length; a++){
		
		// Formulario a ser verificado.
		var localValidar = document.getElementById(local);
		
		// Campo a ser verificado.
		var formulario = localValidar.getElementsByTagName(arr[a]);
		
		// Loop percorrendo os campos.
		for (var i=0; i < formulario.length; i++){
			
			// Verifica se existe title.
			var title = formulario[i].attributes.getNamedItem("title");
			
			// Verifica se tem valor.
			if(title !== null){
				titleValue = title.value;
			}
			
			// Retorna a cor original do campo.
			//formulario[i].style.background = "#666666";
			
			// Se existir titulo...
			if(title !== null && titleValue !== null && titleValue.length > 0){
				
				// Se não foi digitado valor...
				if (formulario[i].value == ""){
					
					alert ("Por favor preencha o campo: " + titleValue );
					
					//formulario[i].style.background = "#FF0000";
					formulario[i].focus();
					
					return false;
				}
			}
		}
	}
	
	return true;
} 

/**
 * Valida o formulário de cadastro.
 */
function registerValidation(local) {
	
	// Valida os campos.
	if(!checkForm(local)) return false;
	
	// Verifica se no formulário tem data de nascimento.
	if($('birthDate')) {
		// Valida a data de nascimento.
		if(!dateValidation($('birthDate'))) return false;
	}
	
	// Confirma a senha.
	if($('password').value != $('passwdConfirm').value) {
		alert('Confirmação de senha inválida!');
		$('passwdConfirm').focus();
		return false;
	}
	
	return true;
}

/**
 * Valida a data de nascimento.
 * 
 */
function dateValidation(date) {
	
	if(date.value == "") return false;
	
	var dia = date.value.substring(0,2);
	var mes = date.value.substring(3,5);
	var ano = date.value.substring(6,10);
	
	// Valida o dia.
	if(dia.length != 2 || dia > 31 || dia < 1) {
		alert('Data de nascimento informada inválida!');
		date.value = "";
		date.focus();
		return false;
	}
	
	// Valida o mes.
	if(mes.length != 2 || mes > 12 || mes < 1) {
		alert('Data de nascimento informada inválida!');
		date.value = "";
		date.focus();
		return false;
	} 
	
	// Valida o mes.
	if(ano.length != 4) {
		alert('Data de nascimento informada inválida!');
		date.value = "";
		date.focus();
		return false;
	} 
	
	return true;	
}
