if(!window.Customer){
	window.Customer = {
			
		minimunAgeCPF: 14,
		lastStateId: "",
		enableCheckState:true,
		initialPage: false,

		newHealthInsuranceData: null,
		healthInsuranceId: "",
		healthInsuranceJSON: null,
		
		newHospitalData: null,
		hospitalId: "",
		hospitalJSON: null,
			
		init:function(step, initialPage){
			this.initialPage = (String(initialPage).toLowerCase() == "true");
			switch(step){
				case "summary":
					Consulte.toggleDimmer("dimmerCover", false);
					Consulte.setBackOptions({
						url:window.contextPath+"/customer/summary.action",
						hadBanner:true
					});
				break;

				case "healthInsurance":
				case "hospital":
					Consulte.toggleDimmer("dimmerCover", true);
				break;

				case "step1":
					if($F("customer.mode") == "edit"){
						/*
						// Graduacao
						if(graduations != null){
							var combo = $("combo.graduation");
							var cont = 1;
							graduations.each(function(domain){
								try{
									combo.add(new Option(domain.name, domain.id), null);
								}catch(e){
									combo.add(new Option(domain.name, domain.id));
								}
								if($F("customer.graduation") == domain.id){
									combo.options[cont].selected = true;
								}
								cont++;
							});
						}

						// Estado Civil
						if(relationshipStatus != null){
							var combo = $("combo.relationshipStatus");
							var cont = 1;
							relationshipStatus.each(function(domain){
								try{
									combo.add(new Option(domain.name, domain.id), null);
								}catch(e){
									combo.add(new Option(domain.name, domain.id));
								}
								if($F("customer.relationshipStatus") == domain.id){
									combo.options[cont].selected = true;
								}
								cont++;
							});
						}*/
					}
					
					Event.observe($("customer.fullName"), "blur", this.suggestShortNameUserName.bind(this));
					Event.observe($("customer.zipCode"), "blur", this.validateCep.bind(this));
					Event.observe($("customer.login"), "blur", this.verifyUserName.bind(this));
					if($F("customer.mode") == "new" || Consulte.isEmpty("customer.cpf")){
						Event.observe($("customer.cpf"), "blur", this.verifyCPF.bind(this));
						Mask.numberField("customer.cpf", Mask.CPF);
					}
					
					// Define Mascara ao campo
					Mask.numberField("customer.birthdate", Mask.DATE);
					Mask.numberField("customer.identityNumber");					
					Mask.numberField("customer.zipCode", Mask.CEP);
					Mask.charNumberField("customer.login");
					
					// Executa Evento do campo
					try{
						Mask.runEvent = true;
						if(Consulte.isNotEmpty("customer.cpf")){
							$("customer.cpf").value = Mask.setMask($F("customer.cpf"), Mask.CPF);
						}
						Consulte.lastValidatedCep = "";
						Consulte.runEvent($("customer.zipCode"), "blur");
					}finally{
						Mask.runEvent = false;
					}
				break;
				
				case "step2":
					this.clearDependedField();
					if(String.isEmpty($F("customer.street")) && states && jQuery){
						this.enableCheckState = true;
						this.bindState("customer.state", states);
						this.checkState();
					}else{
						this.enableCheckState = false;
					}
					// Define Mascara ao campo
					Mask.numberField("customer.number");
					Mask.numberField("customer.cellPhoneAreaCode", Mask.AREACODE);
					Mask.numberField("customer.cellPhoneNumber", Mask.PHONE);
					Mask.numberField("customer.homePhoneAreaCode", Mask.AREACODE);
					Mask.numberField("customer.homePhoneNumber", Mask.PHONE);
					Mask.numberField("customer.commercialPhoneAreaCode", Mask.AREACODE);
					Mask.numberField("customer.commercialPhoneNumber", Mask.PHONE);
					Mask.numberField("customer.branchPhone");
					// Executa Evento do campo
					try{
						Mask.runEvent = true;
						Consulte.runEvent($("customer.cellPhoneAreaCode"), "keyup");
						Consulte.runEvent($("customer.cellPhoneNumber"), "keyup");
						Consulte.runEvent($("customer.homePhoneAreaCode"), "keyup");
						Consulte.runEvent($("customer.homePhoneNumber"), "keyup");
						Consulte.runEvent($("customer.commercialPhoneAreaCode"), "keyup");
						Consulte.runEvent($("customer.commercialPhoneNumber"), "keyup");
					}finally{
						Mask.runEvent = false;
					}
				break;

				case "step3":
				break;

				case "filter":
					this.bindHealthInsurance("healthInsuranceName", healthInsurances);
					$("customerFilterForm").focusFirstElement();
					Mask.numberField("filter.scheduleDateBegin", Mask.DATE);
					Mask.numberField("filter.scheduleDateEnd", Mask.DATE);
					Mask.numberField("filter.cpf", Mask.CPF);
					this.controlForm = new ControlForm(document.customerFilterForm, this.showInvalidFilterMessage.bind(this));
					this.controlForm.initialize();
					Consulte.setBackOptions({
						url:window.contextPath+"/customer/list.action",
						hadBanner:true
					});

					Calendar.bindToField("filter.scheduleDateBegin");
					Calendar.bindToField("filter.scheduleDateEnd");
				break;
			}

			if(["step1", "step2", "step3"].include(step)){
				Consulte.toggleDimmer("dimmerCover", true);
				/*
				//posiciona cursor no primeiro campo
				if($F("customer.mode") == "edit" || ($("customer.street") != null && String.isEmpty($F("customer.street"))))
					$("customerForm").focusFirstElement();
				else if(step)
					$("customer.number").activate();
				*/
			}
			Consulte.enableGlossary();
		},

		step1: function(){
			var parameters = Form.serialize($("customerForm"), {hash:true});
			
			if($F("customer.step") == "2"){
				parameters = this.clearMask(parameters, "step2");
			}
			
			new Ajax.Updater("content", contextPath + "/customer/step1.action", {
				parameters:parameters,
				onComplete:function(response){
					$("customer.login").blur();
				}
			});
			
		},

		step2: function(){
			if(this.validateMandatoryFields("step1")){
				var parameters = Form.serialize($("customerForm"), {hash:true});
				parameters = this.clearMask(parameters, "step1");
				
				/*
				if($F("customer.mode") == "edit"){
					parameters["customer.graduation.id"] = $F("combo.graduation");
					parameters["customer.relationshipStatus.id"] = $F("combo.relationshipStatus");
				}*/

				new Ajax.Request(contextPath + "/customer/step2.action", {
					parameters:parameters,
					onComplete:function(response){
						if(Consulte.hasError(response) == false){
							$("content").innerHTML = response.responseText;
						}
					}
				});
			}
		},
		
		step3: function(){
			//FIXME: implement me!
		},

		save:function(){
			if(this.validateMandatoryFields("step2")){
				var parameters = Form.serialize($("customerForm"), {hash:true});
				parameters = this.clearMask(parameters, "step2");

				new Ajax.Request(contextPath + "/customer/save.action", {
					parameters:parameters,
					onComplete:function(response){
						if(Consulte.hasError(response) == false){
							if(response.responseText.strip() != ""){
								$("content").innerHTML = response.responseText;
							}else{
								Consulte.toggleDimmer("dimmerCover", false);
								Consulte.showErrorMessage(Bundle.getMessage("message.save.success.male", "txt.your.data"));
								location.href = contextPath;
							}
						}
					}
				});
				Consulte.toggleDimmer("dimmerCover", false);
			}
		},
		
		toggleMiniMenuSummary: function(menu){
			var obj = $("minimenu"+menu);
			if(obj.visible())
				 obj.hide();
			else obj.show();
		},
		
		toggleSchedulesList: function(customerId){
			var obj = $("sbo_"+customerId);
			var arrow = $("img_ordenar_"+customerId);

			if(obj.visible()){
				obj.hide();
				arrow.className = "img_mostrar";
			}else{
				obj.show();
				arrow.className = "img_esconder";
			}
		},
		
		verifyUserName:function(async, callback){
			var userId = (Consulte.isEmpty("customer.id")) ? null : $F("customer.id");
			Consulte.processingField("customer.login", "returnUserName", "validateUserName.action", {login:$F("customer.login"), userId:userId}, async, callback);
		},
		
		verifyCPF:function(async){
			Consulte.processingField("customer.cpf", "returnCPF", "validateCPF.action", {cpf:Mask.clear($F("customer.cpf")), userType:"customer"}, async);
		},
		
		clearMask:function(parameters, step){
			switch(step){
				case "step1":
					parameters["customer.cpf"] = Mask.clear(parameters["customer.cpf"]);
					parameters["customer.address.zipCode"] = Mask.clear(parameters["customer.address.zipCode"]);
				break;
				case "step2":
					parameters["customer.phoneNumbers.phone1.areaCode"] = Mask.clear(parameters["customer.phoneNumbers.phone1.areaCode"]);
					parameters["customer.phoneNumbers.phone1.number"]   = Mask.clear(parameters["customer.phoneNumbers.phone1.number"]);
					parameters["customer.phoneNumbers.phone2.areaCode"] = Mask.clear(parameters["customer.phoneNumbers.phone2.areaCode"]);
					parameters["customer.phoneNumbers.phone2.number"]   = Mask.clear(parameters["customer.phoneNumbers.phone2.number"]);
					parameters["customer.phoneNumbers.phone3.areaCode"] = Mask.clear(parameters["customer.phoneNumbers.phone3.areaCode"]);
					parameters["customer.phoneNumbers.phone3.number"]   = Mask.clear(parameters["customer.phoneNumbers.phone3.number"]);
				break;
			}
			return parameters;
		},

		
		cancel: function(){
			if(Consulte.showConfirmMessage(Bundle.getMessage("message.cancel.process"))){
				new Ajax.Request(contextPath + "/customer/cancel.action", {
					onComplete:function(response){
						Consulte.toggleDimmer("dimmerCover", false);
						if(Consulte.hasError(response) == false){
							if($F("customer.mode") == "edit"){
								$("content").innerHTML = response.responseText;
							}else{
								location.href = contextPath;
							}
						}
					}
				});
			}
		},
		
		validateMandatoryFields:function(step){
			try{
				switch(step){
					case "step1":
						Consulte.mandatory("customer.fullName", "label.full.name");
						Consulte.mandatory("customer.shortName", "label.short.name");
						
						//Valida Sexo
						var anyChecked = false;
						$("content").select("input[name='customer.gender.abbreviation']").each(function(obj){
							if(obj.checked){
								anyChecked = true;
								throw $break;
							}
						});
						if(!anyChecked){
							Consulte.showInfoMessage(Bundle.getMessage("message.mandatory.info"));
							Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.field", "label.gender"));
							throw Consulte.$error;
						}
						
						//if(Consulte.isNotEmpty("customer.cpf")){
						//if($F("customer.mode") == "new"){
						// Valida a data de nascimento informada
						Consulte.mandatory("customer.birthdate", "label.birthdate");
						if(this.verifyDate($F("customer.birthdate"))){
							var age = this.getAge();
							if((age != null && age >= this.minimunAgeCPF) || Consulte.isNotEmpty("customer.cpf")){
								//Valida CPF somente para maiores de 14
								Consulte.mandatory("customer.cpf", "label.cpf");
								Consulte.validateCPF("customer.cpf");
								if($("customer.cpf").readOnly == false){
									this.verifyCPF(false);
									if($("returnCPF").childNodes != null && $("returnCPF").childNodes.length > 0 && $("returnCPF").childNodes[0].nodeValue != ""){
										Consulte.showErrorMessage(Bundle.getMessage("message.exist.cpf", "txt.profile.customer"));
										throw Consulte.$error;
									}
								}
							}
						}else{
							Consulte.showErrorMessage(Bundle.getMessage("message.invalid.field", "label.birthdate"));
							throw Consulte.$error;
						}
						//}
						
						//Valida o CEP
						Consulte.mandatory("customer.zipCode", "label.cep");
						this.validateCep(false);
						
						//Valida userName
						Consulte.mandatory("customer.login", "label.user.name");
						Consulte.validateLogin("customer.login");
						this.verifyUserName(false);
						if($("returnUserName").childNodes != null && $("returnUserName").childNodes.length > 0 && $("returnUserName").childNodes[0].nodeValue != ""){
							Consulte.showErrorMessage(Bundle.getMessage("message.exist.username"));
							throw Consulte.$error;
						}
						
						//Valida Senha
						if($F("customer.mode") == "new"){
							Consulte.mandatory("customer.password", "label.password");
							Consulte.mandatory("customer.confirm", "label.confirm.password");
							Consulte.validatePassword("customer.password", "customer.confirm", {valuesAgainst: [$F("customer.birthdate"), $F("customer.identityNumber"), $F("customer.cpf")], clearMask:true});
						}
						
						//Valida a opção de avançar mantendo o cep informado
						if(!Consulte.userWantedToKeepInvalidCep("customer.invalidCepDiv", "customer.keepInvalidCep")){
							Consulte.showInfoMessage(Bundle.getMessage("message.cep.do.something"));
							throw Consulte.$error;
						}

					break;
					case "step2":
						//Valida Estado
						Consulte.mandatory("customer.state", "label.state");
						if($("customer.stateId").value == "" || $("customer.stateId").value == "0"){
							Consulte.showErrorMessage(Bundle.getMessage("message.invalid.field", Bundle.getMessage("label.state")));
							$("customer.state").activate();
							throw Consulte.$error;
						}
						
						//Valida Cidade
						Consulte.mandatory("customer.city", "label.city");
						if($("customer.cityId").value == "" || $("customer.cityId").value == "0"){
							Consulte.showErrorMessage(Bundle.getMessage("message.invalid.field", Bundle.getMessage("label.city")));
							$("customer.city").activate();
							throw Consulte.$error;
						}
						
						Consulte.mandatory("customer.neighborhood", "label.neighborhood");
						Consulte.mandatory("customer.street", "label.street");
						Consulte.mandatory("customer.number", "label.number");

						//Valida Telefones
						var found = false;
						var codes   = ["customer.cellPhoneAreaCode", "customer.homePhoneAreaCode", "customer.commercialPhoneAreaCode"],
						    numbers = ["customer.cellPhoneNumber", "customer.homePhoneNumber", "customer.commercialPhoneNumber"],
						    labels  = ["label.cell.phone", "label.home.phone", "label.commercial.phone"];

						for(var phoneIndex=0, length=codes.length; phoneIndex < length; phoneIndex++){
							var areaCode = $(codes[phoneIndex]), 
								number = $(numbers[phoneIndex]);

							if(Consulte.isNotEmpty(areaCode) || Consulte.isNotEmpty(number)){
								var c = Mask.clear(areaCode.value).strip(), 
									n = Mask.clear(number.value).strip();
								if(c.length != 2){
									Consulte.showErrorMessage(Bundle.getMessage("message.invalid.field", labels[phoneIndex]));
									areaCode.activate();
									throw Consulte.$error;
								}
								if(n.length < 8){
									Consulte.showErrorMessage(Bundle.getMessage("message.invalid.field", labels[phoneIndex]));
									number.activate();
									throw Consulte.$error;
								}
								found = true;
							}
						}
						if(!found){
							Consulte.showErrorMessage(Bundle.getMessage("message.no.phone"));
							$("customer.cellPhoneAreaCode").activate();
							throw Consulte.$error;
						}

						// Não tem celular, aparece aviso de que não receber mensagem:
						if(String.isEmpty($F("customer.cellPhoneAreaCode")) && !Consulte.showConfirmMessage(Bundle.getMessage("message.customer.schedule.no.cellPhone"))){
							$("customer.cellPhoneAreaCode").activate();
							throw Consulte.$error;
						}
						
						// Verifica se é um numero valido de celular
						if(!String.isEmpty($F("customer.cellPhoneNumber"))){
							var digit = $F("customer.cellPhoneNumber").substr(0, 1);
							if(digit < 6 && !Consulte.showConfirmMessage(Bundle.getMessage("message.invalid.cellPhone"))){
								$("customer.cellPhoneNumber").activate();
								throw Consulte.$error;
							}
						}

						//Valida email
						Consulte.mandatory("customer.email", "label.email");
						Consulte.validateEmail("customer.email", "label.email");
					break;
				}
				return true;
			}catch(e){
				if(e != Consulte.$error) throw e;
				return false;
			}
		},

		/* ----- DADOS CONVENIOS ---- */
		/* ------------------------------- */
		healthInsurance: function(){
			this.toggleMiniMenuSummary(1);
			var parameters = Form.serialize($("customerForm"), {hash:true});

			new Ajax.Request(contextPath + "/customer/healthInsurance.action", {
				parameters:parameters,
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
						this.healthInsuranceJSON = Consulte.getHeaderAsJSON(response, "X-Consulte-Customer-HealthInsurances");
					}
				}.bind(this)
			});
		},

		saveHealthInsurance: function(){
			if(this.newHealthInsuranceData != null && !this.confirmHealthInsurance()){
				return;
			}
			
			new Ajax.Request(contextPath + "/customer/saveHealthInsurance.action", {
				parameters:{
					"refreshCustomerHealthInsurances": Object.toJSON({values:$A(this.healthInsuranceJSON)})
				},
				onComplete:function(response){
				Consulte.toggleDimmer("dimmerCover", false);
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
						this.healthInsuranceJSON = null;
						if($("saveSuccessMessage") != null){
							$("saveSuccessMessage").show();
							$("topMessage").show();
						}
					}
				}
			});
		},
		
		newHealthInsurance: function(){
			this.newHealthInsuranceData = {
				id: null,
				name: "",
				"new": true
			};
			var html = $F("newHealthInsuranceTemplate").interpolate(this.newHealthInsuranceData);
			$("newHealthInsuranceTD").innerHTML = html;
			
			if(healthInsurances && jQuery){
				this.bindHealthInsurance("healthInsuranceName", healthInsurances);
			}
			$("tr.new.add").hide();
		},
		
		confirmHealthInsurance: function(){
			var id = this.healthInsuranceId;
			
			if(this.healthInsuranceJSON == null){
				this.healthInsuranceJSON = [];
			}

			if(!this.validateHealthInsurance()){
				return false;
			}

			var obj = this.newHealthInsuranceData;
			obj.id = id;
			obj.name = $F("healthInsuranceName");
			this.healthInsuranceJSON.push(obj);
			
			var html = $F("showHealthInsuranceTemplate").interpolate(obj);
			$("newHealthInsuranceTR").insert({before:html});
			
			var array = $$(".lineMessage");
			if(array.length > 0){
				array.first().hide();
			}
			$("tr.new.add").show();
			
			$("newHealthInsuranceTD").innerHTML = "";
			this.newHealthInsuranceData = null;
			this.showChangeFormMessage("healthInsurance");
			return true;
		},
		
		cancelHealthInsurance: function(){
			$("newHealthInsurance").remove();
			$("tr.new.add").show();
			this.newHealthInsuranceData = null;
			
		},
		
		deleteHealthInsurance: function(id){
			$("healthInsurance_"+id).remove();
			this._removeHealthInsurance(id);
			this.showChangeFormMessage("healthInsurance");
		},
		
		_removeHealthInsurance: function(id){
			this.healthInsuranceJSON = this.healthInsuranceJSON.reject(function(healthInsurance){
				if(healthInsurance.id == id){
					return true;
				}
				// Continua na lista:
				return false;
			});
		},
		
		validateHealthInsurance:function(){
			var healthInsuranceName = $("healthInsuranceName");

			// Nome do Convenio
			if(Consulte.isEmpty(healthInsuranceName)){
				Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.field", "label.health.insurance"));
				healthInsuranceName.activate();
				return false;
			}

			jQuery(healthInsuranceName).search();
			if(this.healthInsuranceId == null || String.isEmpty(String(this.healthInsuranceId))){
				Consulte.showErrorMessage(Bundle.getMessage("message.healthInsurance.not.registered"));
				healthInsuranceName.activate();
				return false;
			}
			
			// Verifica se ja nao existe o hospital selecionado na lista
			if($("healthInsurance_"+this.healthInsuranceId) != null){
				Consulte.showErrorMessage(Bundle.getMessage("message.exist.health.insurance.selected"));
				healthInsuranceName.activate();
				return false;
			}
			
			return true;
		},
		
		bindHealthInsurance: function(field, data) {
	   		Consulte.bindAutocomplete({
    			field: field,
    			id: "healthInsuranceId",
    			data: data,
    			onSelect: function(item){
	   				this.newHealthInsuranceData = {};
	   				Object.extend(this.newHealthInsuranceData, item||{});
           			this.healthInsuranceId = this.newHealthInsuranceData.id = item.id;
    			}.bind(this),
    			onClear: function(){
    				this.healthInsuranceId = null;
    			}.bind(this)
    		});        
        },

		listHealthInsurances: function(){
			jQuery($("healthInsuranceName")).showAll();
		},
		/* ------------------------------- */

		/* ----- DADOS HOSPITAIS ---- */
		/* ------------------------------- */
		hospital: function(){
			this.toggleMiniMenuSummary(1);
			var parameters = Form.serialize($("customerForm"), {hash:true});

			new Ajax.Request(contextPath + "/customer/hospital.action", {
				parameters:parameters,
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
						this.hospitalJSON = Consulte.getHeaderAsJSON(response, "X-Consulte-Customer-Hospitals");
					}
				}.bind(this)
			});
		},
		
		saveHospital: function(){
			if(this.newHospitalData != null && !this.confirmHospital()){
				return;
			}
			
			new Ajax.Request(contextPath + "/customer/saveHospital.action", {
				parameters:{
					"refreshCustomerHospitals": Object.toJSON({values:$A(this.hospitalJSON)})
				},
				onComplete:function(response){
				Consulte.toggleDimmer("dimmerCover", false);
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
						this.hospitalJSON = null;
						if($("saveSuccessMessage") != null){
							$("saveSuccessMessage").show();
							$("topMessage").show();
						}
					}
				}
			});
		},
		
		newHospital: function(){
			this.newHospitalData = {
				id: null,
				name: "",
				"new": true
			};
			var html = $F("newHospitalTemplate").interpolate(this.newHospitalData);
			$("newHospitalTD").innerHTML = html;
			
			if(states && jQuery){
				this.bindHospitalState("hospitalState", states);
				//this.checkHospitalState();
			}
			$("tr.new.add").hide();
		},
		
		confirmHospital: function(){
			var id = this.hospitalId;
			
			if(this.hospitalJSON == null){
				this.hospitalJSON = [];
			}

			if(!this.validateHospital()){
				return false;
			}

			var obj = this.newHospitalData;
			obj.id = id;
			obj.name = $F("hospitalName");
			this.hospitalJSON.push(obj);
			
			var html = $F("showHospitalTemplate").interpolate(obj);
			$("newHospitalTR").insert({before:html});
			
			var array = $$(".lineMessage");
			if(array.length > 0){
				array.first().hide();
			}
			$("tr.new.add").show();
			
			$("newHospitalTD").innerHTML = "";
			this.newHospitalData = null;
			this.showChangeFormMessage("hospital");
			return true;
		},
		
		cancelHospital: function(){
			$("newHospital").remove();
			$("tr.new.add").show();
			this.newHospitalData = null;
			
		},
		
		deleteHospital: function(id){
			$("hospital_"+id).remove();
			this._removeHospital(id);
			this.showChangeFormMessage("hospital");
		},
		
		_removeHospital: function(id){
			this.hospitalJSON = this.hospitalJSON.reject(function(hospital){
				if(hospital.id == id){
					return true;
				}
				// Continua na lista:
				return false;
			});
		},

		validateHospital:function(){
			var hospitalState = $("hospitalState");
			var hospitalCity = $("hospitalCity");
			var hospitalName = $("hospitalName");

			// Estado
			jQuery(hospitalState).search();
			if(String.isEmpty($F("hospitalState"))){
				Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.field", "label.state"));
				hospitalState.activate();
				return false;
			}

			jQuery(hospitalCity).search();
			if(String.isEmpty($F("hospitalCity"))){
				Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.field", "label.city"));
				hospitalCity.activate();
				return false;
			}

			// Nome do Hospital
			if(Consulte.isEmpty(hospitalName)){
				Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.field", "label.hospital.name"));
				hospitalName.activate();
				return false;
			}

			jQuery(hospitalName).search();
			if(this.hospitalId == null){
				Consulte.showErrorMessage(Bundle.getMessage("message.hospital.not.registered"));
				hospitalName.activate();
				return false;
			}
			
			// Verifica se ja nao existe o hospital selecionado na lista
			if($("hospital_"+this.hospitalId) != null){
				Consulte.showErrorMessage(Bundle.getMessage("message.exist.hospital.selected"));
				hospitalName.activate();
				return false;
			}
			
			return true;
		},
        
		bindHospitalState: function(field, data){
    		Consulte.bindAutocomplete({
    			field: field,
    			id: field+"Id",
    			itemProperty: "abbreviation",
    			resultProperty: "abbreviation",
    			width: 200,
    			data: data,
    			itemProperty: function(state){
    				return state.name + " ("+state.abbreviation+")";
    			},
    			onSelect: function(item){
    				$("hospitalCity").readOnly = false;
    				$("hospitalCity").removeClassName("disableColor");
    				$("hospitalCity").value = "";
					this.listHospitalCities(item.id);
    			}.bind(this),
    			onClear: function(){
    				$("hospitalCity").readOnly = true;
    				$("hospitalCity").addClassName("disableColor");
    				Consulte.bindAutocomplete({
    					field: "hospitalCity",
    					clearedText: Bundle.getMessage("txt.select.state"),
    					onlyRemove: true, clearValue:true
    				});

    				$("hospitalName").readOnly = true;
    				$("hospitalName").addClassName("disableColor");
    				Consulte.bindAutocomplete({
    					field: "hospitalName",
    					clearedText: Bundle.getMessage("txt.select.city"),
    					onlyRemove: true, clearValue:true
    				});
    				
    			}.bind(this)
    		});        
		},
        
		bindHospitalCity:function(field, data){
	   		Consulte.bindAutocomplete({
    			field: field,
    			id: field+"Id",
    			data: data,
    			onSelect: function(item){
	   				this.listHospital(item.id);
    			}.bind(this),
    			onClear: function(){
    				Consulte.bindAutocomplete({
    					field: "hospitalName",
    					clearedText: Bundle.getMessage("txt.select.city"),
    					onlyRemove: true, clearValue:true
    				});
    			}.bind(this)
    		});        
		},

		bindHospital:function(field, data){
	   		Consulte.bindAutocomplete({
    			field: field,
    			id: field+"Id",
    			data: data,
    			onSelect: function(item){
	   				Object.extend(this.newHospitalData, item||{});
           			this.hospitalId = this.newHospitalData.id = item.id;
    			}.bind(this),
    			onClear: function(){
    				this.hospitalId = null;
    			}.bind(this)
    		});        
		},
		
		listHospitalStates:function(){
			jQuery($("hospitalState")).showAll();
		},
		
		listHospitals:function(){
			jQuery($("hospitalName")).showAll();
		},
		
		listHospitalCities:function(state){
            new Ajax.Request(window.contextPath + "/cities.generatedJS", {
                parameters: { stateId: state },
                onComplete: function(response) {
                    eval(response.responseText);
                    if(typeof(cities) != "undefined"){
                        this.bindHospitalCity("hospitalCity", cities);
                    }
                }.bind(this)
            });
		},

		listHospital:function(city){
            new Ajax.Request(window.contextPath + "/hospitals.generatedJS", {
                parameters: { cityId: city },
                onComplete: function(response) {
                    eval(response.responseText);
                    if(typeof(hospitals) != "undefined"){
                    	if(hospitals != null && hospitals.length > 0){
                    		this.bindHospital("hospitalName", hospitals);
        					$("hospitalName").readOnly = false;
        					$("hospitalName").removeClassName("disableColor");
        					$("hospitalName").value = "";
                    	}else{
                    		Consulte.showErrorMessage(Bundle.getMessage("message.error.no.hospitals"));
                    	}
                    }
                }.bind(this)
            });
		},
		/* ------------------------------- */
		
		showChangeFormMessage: function(type){
			Consulte.showInfoMessage(Bundle.getMessage("message.data.no.save"), type+"TableMessage", type+"TxtMessage");
		},

		validateCep: function(async){
			Consulte.validateCep($F("customer.zipCode"), "customer.keepInvalidCep", "customer.invalidCepDiv", async);
		},

		suggestShortNameUserName: function(){
			Consulte.suggestShortNameUserName("customer.fullName", "customer.shortName", "customer.login", "returnUserName", this.verifyUserName.bind(this));			
		},

    	checkState: function() {
			if(this.enableCheckState){
				var state = $("customer.state");
				var city = $("customer.city");
	
				jQuery(state).search();
				if (state.value == "") {
					city.readOnly = true;
					city.addClassName("disableColor");
					city.value = Bundle.getMessage("txt.select.state");
				} else {
					city.readOnly = false;
					city.removeClassName("disableColor");
					
					if(city.value == Bundle.getMessage("txt.select.state"))
						city.value = "";
						
					city.activate();
				}
				this.checkCity();
			}
        },

        checkCity: function(){
			if(this.enableCheckState){
				var city = $("customer.city");
				var neighborhood = $("customer.neighborhood");
				var address = $("customer.street");
				var number = $("customer.number");
				var complement = $("customer.complement");
	
				jQuery(city).search();
				if(city.value == "" || city.value == Bundle.getMessage("txt.select.state")){
					neighborhood.readOnly = true;
					neighborhood.addClassName("disableColor");
					neighborhood.value = Bundle.getMessage("txt.select.city");
					
					address.readOnly = true;
					address.addClassName("disableColor");
					address.value = Bundle.getMessage("txt.select.city");
					
					complement.readOnly = true;
					complement.addClassName("disableColor");
					complement.value = Bundle.getMessage("txt.select.city");
					
					number.readOnly = true;
					number.addClassName("disableColor");
					number.value = Bundle.getMessage("txt.select.city");
				}else{
					neighborhood.readOnly = false;
					neighborhood.removeClassName("disableColor");
					if(neighborhood.value == Bundle.getMessage("txt.select.city")) neighborhood.value="";
					
					address.readOnly = false;
					address.removeClassName("disableColor");
					if(address.value == Bundle.getMessage("txt.select.city")) address.value="";
					
					complement.readOnly = false;
					complement.removeClassName("disableColor");
					if(complement.value == Bundle.getMessage("txt.select.city")) complement.value="";
					
					number.readOnly = false;
					number.removeClassName("disableColor");
					if(number.value == Bundle.getMessage("txt.select.city")) number.value="";
					
					neighborhood.activate();
				}
			}
        },

		clearDependedField:function(){	
			if($("customer.city").value == Bundle.getMessage("txt.select.state"))
            	$("customer.city").value = "";
				
			if($("customer.neighborhood").value == Bundle.getMessage("txt.select.city"))
            	$("customer.neighborhood").value = "";	
			
			if($("customer.street").value == Bundle.getMessage("txt.select.city"))
            	$("customer.street").value = "";
				
			if($("customer.number").value == Bundle.getMessage("txt.select.city"))
            	$("customer.number").value = "";		

			if($("customer.complement").value == Bundle.getMessage("txt.select.city"))
            	$("customer.complement").value = "";	

		},

		bindState:function(field, data){
			jQuery($(field)).autocomplete(data, {
				minChars: 0,
				delay: 100,
				width: 250,
				max:data.length,
				selectFirst: false,
				matchContains: true,
				autoFill: false,
				formatItem: function(row, i, max) {
					return row.name +" ("+ row.abbreviation +")";
				},
				formatMatch: function(row, i, max) {
					return row.name.replaceSpecialChars() +" "+ row.name + " " + row.abbreviation;
				},
				formatResult: function(row) {
					return row.abbreviation;
				}
			}).result(function(event, item){
				var id = (item != null) ? item.id : "";
				if(this.lastStateId != id){
					jQuery($("customer.city")).unautocomplete();
					$("customer.city").value = "";
					$("customer.city").readOnly = true;
					if(item != null){
						this.listCities(item.id);
						$("customer.city").readOnly = false;
					}
					this.lastStateId = id;
					$("customer.stateId").value = id;
				}
			}.bind(this));
		},
		
		bindCity:function(field, data){
            jQuery($(field)).autocomplete(data, {
                minChars: 3,
                delay: 500,
                width: 250,
                max: data.length,
                selectFirst: false,
                matchContains: true,
                autoFill: false,
                formatItem: function(row, i, max) {
                    return row.name;
                },
                formatMatch: function(row, i, max) {
                    return row.name.replaceSpecialChars() + " " + row.name;
                },
                formatResult: function(row) {
                    return row.name;
                }
            }).result(function(event, item){
            	var id = (item != null) ? item.id : "";
            	$("customer.cityId").value = id;
            });
		},
		
		listStates:function(){
			jQuery($("customer.state")).showAll();
		},
		
		listCities:function(state){
            new Ajax.Request(window.contextPath + "/cities.generatedJS", {
                parameters: { stateId: state },
                onComplete: function(response) {
                    eval(response.responseText);
                    if(typeof(cities) != "undefined"){
                        this.bindCity("customer.city", cities);
                    }
                }.bind(this)
            });
		},
		

		getAge: function(){
			return Consulte.calculateAge($F("customer.birthdate"));
		},
		
		verifyDate: function(date){
			var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
			
			if (date.match(expReg)){
				var dia = parseInt(date.substring(0,2),10);
				var mes = parseInt(date.substring(3,5),10)-1;
				var ano = parseInt(date.substring(6,10),10);
				var vdt = new Date(ano,mes,dia);
				
				if((dia == vdt.getDate()) && (mes == vdt.getMonth()) && (ano == vdt.getFullYear()))
					return true;
				else
					return false;
			} 
			else
				return false;
		},

		logon: function(){
			document.customerForm.action = window.contextPath + "/login.action";
			document.customerForm.submit();
		},

		/* Métodos da Tela de Pesquisa */
        showInvalidFilterMessage: function(){
		 	$('formModified').innerHTML = Bundle.getMessage('message.form.has.changed');
		 	if($("formModified").innerHTML != "&nbsp;")
		 		$("filtro_customer").select(".medico_pesquisa_paciente").first().setStyle({top:"38px"});
        },
		
		showHideFilter: function(){
			var objeto = $("filtro_customer");
            var seta = $("img_ocultar_filtros");
            var texto = $("txt_ocultar_filtros");
			var bordaFiltro = $("formModified");

            if (objeto.visible()) {
                objeto.hide();
				seta.className = "img_mostrar";
                texto.innerHTML = Bundle.getMessage('txt.filter.show');
				if(bordaFiltro){
					bordaFiltro.addClassName("modifyFilterHide");
					bordaFiltro.removeClassName("modifyHide");
				}
            } else {
                objeto.show();
				seta.className = "img_esconder";
                texto.innerHTML = Bundle.getMessage('txt.filter.hide');
				if(bordaFiltro){
					bordaFiltro.removeClassName("modifyFilterHide");
					bordaFiltro.addClassName("modifyFilter");
				}
            }
		},

		doResetFilters: function(){
			$("customerFilterForm").reset();
			$("healthInsuranceId").value = "";
		},

		doSearch: function(resetPageIndex){
			if(!this.validateSearchFilters()) return;

			if(resetPageIndex){
        		$("filter.pageIndex").value = 1;
        	}
			
			if(this.initialPage){
				//TODO: Modificar datas:
				Processing.show(true);
				var form = $("customerFilterForm");
				form.action = window.contextPath+"/customer/openSearch.action";
				form.appendChild(new Element("input", {name:"search", value:"true", type:"hidden"}));

				var begin = $("filter.scheduleDateBegin");
				var end = $("filter.scheduleDateEnd");

				if(!Consulte.isEmpty(begin)){
					var value = Date.parse_DDMMYYYY(begin.value).getTime();
					form.appendChild(new Element("input", {name:begin.name, value:value, type:"hidden"}));
					begin.disabled = true;
				}
				if(!Consulte.isEmpty(end)){
					var value = Date.parse_DDMMYYYY(end.value).getTime();
					form.appendChild(new Element("input", {name:end.name, value:value, type:"hidden"}));
					end.disabled = true;
				}

				form.submit();
			}else{
				var parameters = $("customerFilterForm").serialize({hash:true});
				parameters["filter.cpf"] = Mask.clear(parameters["filter.cpf"]);
				if(String.isNotEmpty(parameters["filter.scheduleDateBegin"])){
					parameters["filter.scheduleDateBegin"] = Date.parse_DDMMYYYY(parameters["filter.scheduleDateBegin"]).getTime();
				}
				if(String.isNotEmpty(parameters["filter.scheduleDateEnd"])){
					parameters["filter.scheduleDateEnd"] = Date.parse_DDMMYYYY(parameters["filter.scheduleDateEnd"]).getTime();
				}
				new Ajax.Request(window.contextPath+"/customer/list.action", {
					parameters: parameters,
					onComplete: function(response){
						if(!Consulte.hasError(response)){
							$("searchResults").innerHTML = response.responseText;
							this.controlForm.search();
							if($("formModified").innerHTML != "&nbsp;")
								$("filtro_customer").select(".medico_pesquisa_paciente").first().setStyle({top:"26px"});							
							$('formModified').innerHTML = "&nbsp;";
						}
					}.bind(this)
				});
				this.controlForm.initFormActual();
			}
		},

		validateSearchFilters: function(){
			try{
				var beginDate = $F("filter.scheduleDateBegin"), endDate = $F("filter.scheduleDateEnd");
				if(String.isNotEmpty(beginDate) ^ String.isNotEmpty(endDate)){
					Consulte.showErrorMessage(Bundle.getMessage("message.customer.search.both.dates.required"));
					throw Consulte.$error;
				}

				if(String.isNotEmpty(beginDate) && Date.parse_DDMMYYYY(beginDate) == null){
					Consulte.showErrorMessage(Bundle.getMessage("message.invalid.field", "label.care.date"));
					$("filter.scheduleDateBegin").activate();
					throw Consulte.$error;
				}
				if(String.isNotEmpty(endDate) && Date.parse_DDMMYYYY(endDate) == null){
					Consulte.showErrorMessage(Bundle.getMessage("message.invalid.field", "label.care.date"));
					$("filter.scheduleDateEnd").activate();
					throw Consulte.$error;
				}

				if(String.isNotEmpty($F("filter.cpf"))){
					Consulte.validateCPF($("filter.cpf"));
				}

				if(Consulte.isEmpty($("filter.customerName")) &&
				   Consulte.isEmpty($("filter.cpf")) &&
				   Consulte.isEmpty($("filter.scheduleDateBegin")) &&
				   Consulte.isEmpty($("healthInsuranceName"))){
					Consulte.showErrorMessage(Bundle.getMessage("message.no.filter"));
					throw Consulte.$error;
				}

				if(this.controlForm != null){
					this.controlForm.initFormActual();
				}

				return true;

			}catch(e){
				if(e != Consulte.$error) throw e;
				return false;
			}
		}

	};
}
