if(!window.WorkingPlace){
	window.WorkingPlace = {

		enableCheckState: true,
		healthInsuranceId: 0,
		procedureId: 0,
		LBSameAddress: null,
		LBDeactivateAllOwners: null,
		LBApproval: null,
		//errorState: false,
		//errorCity: false,

		init: function(step){
			var mode = $("workingPlace.mode").value;
			
			switch(step){
				/* STEP 1 */
				case "step1":
					Consulte.toggleDimmer("dimmerCover", false);
					//Consulte.toggleBanner(false);

					if(Consulte.isEmpty("operatorId")){
						if(states && jQuery){
							this.bindCRMState("crmState", states);
							this.checkCRMState();
						}
						Mask.numberField("crm");
						$("workingPlaceForm").focusFirstElement();
					}
					Consulte.setBackOptions({
						url:window.contextPath+"/workingPlace/list.action",
						hadBanner:true
					});
					
				break;
				
				/* STEP 2 */
				case "step2":
					Consulte.toggleDimmer("dimmerCover", true);
					//Consulte.toggleBanner(false);
					
				break;

				/* STEP 3 */
				case "step3":
					Consulte.toggleDimmer("dimmerCover", true);
					//Consulte.toggleBanner(false);
					$("workingPlaceForm").focusFirstElement();
					if(mode != "link"){
						Event.observe($("workingPlace.zipCode"), "blur", this.validateCep.bind(this));
						this.bindCompany("workingPlace.company", companies);
						
						// Define Mascara ao campo
						Mask.numberField("workingPlace.zipCode", Mask.CEP);
						Mask.numberField("workingPlace.phoneAreaCode1", Mask.AREACODE);
						Mask.numberField("workingPlace.phoneNumber1", Mask.PHONE);
						Mask.numberField("workingPlace.phoneAreaCode2", Mask.AREACODE);
						Mask.numberField("workingPlace.phoneNumber2", Mask.PHONE);
						Mask.numberField("workingPlace.phoneAreaCode3", Mask.AREACODE);
						Mask.numberField("workingPlace.phoneNumber3", Mask.PHONE);
						
						// Executa Evento do campo
						try{
							Mask.runEvent = true;
							Consulte.lastValidatedCep = "";
							Consulte.runEvent($("workingPlace.zipCode"), "blur");
							Consulte.runEvent($("workingPlace.phoneAreaCode1"), "keyup");
							Consulte.runEvent($("workingPlace.phoneNumber1"), "keyup");
							Consulte.runEvent($("workingPlace.phoneAreaCode2"), "keyup");
							Consulte.runEvent($("workingPlace.phoneNumber2"), "keyup");
							Consulte.runEvent($("workingPlace.phoneAreaCode3"), "keyup");
							Consulte.runEvent($("workingPlace.phoneNumber3"), "keyup");
						}finally{
							Mask.runEvent = false;
						}
					}else{
						$("workingPlace.name").activate();
					}
				break;

				/* STEP 4 */
				case "step4":
					Consulte.toggleDimmer("dimmerCover", true);
					//Consulte.toggleBanner(false);
					this.bindHealthInsurance("workingPlace.healthInsurancesCombo", healthInsurances);
					this.bindProcedure("workingPlace.proceduresCombo", medicalProcedures);
					if(mode != "link"){
						this.clearDependedField();
						if(String.isEmpty($("workingPlace.street").value) && states && jQuery){
							this.enableCheckState=true;	
							this.bindState("workingPlace.state", states);
							this.checkState();
						}else{
							this.enableCheckState=false;
						}

						Mask.numberField("workingPlace.number");
					}
				break;
			}
			Consulte.enableGlossary();
		},
		
		listByOrder: function(onlyActive){
			$("workingPlaceFilterForm.onlyActive").value = onlyActive;
			
			if(Consulte.isEmpty("operatorId")){
				this.list(); //medico acessando
			}else{
				this.listByOwnerId(); //operador acessando
			}
		},

		checkSelectOwner: function(field){
			$("ownerId").value = field.value;
		},
		
		listByOwnerId: function(){
			if(Consulte.isEmpty("ownerId")){
				Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.field", "txt.select.owner"));
				return;
			}
			var parameters = Form.serialize($("workingPlaceFilterForm"), {hash:true});
			parameters["ownerId"] = $F("ownerId");
			parameters["operatorId"] = $F("operatorId");
			new Ajax.Request(contextPath + "/workingPlace/list.action", {
				parameters:parameters,
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
					}
				}
			});
		},
		
		list:function(saveSuccess){
			var parameters = Form.serialize($("workingPlaceFilterForm"), {hash:true});
			new Ajax.Request(contextPath + "/workingPlace/list.action", {
				parameters:parameters,
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
						if(saveSuccess){
							$("topMessage").show();
							$("saveSuccessMessage").show();
						}
					}
				}
			});
		},
		
		basic: function(wpId){
			var mode = $("workingPlace.mode").value;
			var step = $("workingPlace.step").value;
			var parameters = {};
			
			if(Consulte.isEmpty("operatorId")){ //medico
				parameters = {
						"workingPlace.id":wpId, 
						"workingPlace.step":$("workingPlace.step").value, 
						"workingPlace.mode":$("workingPlace.mode").value,
						crm:$("crm").value
					};
				
				if(!String.isEmpty(mode) && mode != "link"){
					var parameters = Form.serialize($("workingPlaceForm"), {hash:true});
					parameters["workingPlace.retainedInsurances"] = this.getComboAsArray("workingPlace.healthInsurances");
					parameters["workingPlace.retainedProcedures"] = this.getComboAsArray("workingPlace.procedures");
				}
			}else{ //operador admin
				parameters = {
						"workingPlace.id":wpId, 
						"workingPlace.step":$("workingPlace.step").value, 
						"workingPlace.mode":$("workingPlace.mode").value,
						"ownerId":$F("ownerId"),
						"operatorId":$F("operatorId")
				};
			}
			
			new Ajax.Request(contextPath + "/workingPlace/basic.action", {
				parameters:parameters,
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
					}
				}
			});
		},
		
		detail: function(wpId){
			var mode = $("workingPlace.mode").value;
			var step = $("workingPlace.step").value;

			new Ajax.Request(contextPath + "/workingPlace/detail.action", {
				parameters:{
					"workingPlace.id":wpId, 
					"workingPlace.step":$("workingPlace.step").value, 
					"workingPlace.mode":$("workingPlace.mode").value,
					crm:$("crm").value,
					ownerId:$F("ownerId"),
					"crmState.id":$F("crmStateId")
				},
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
					}
				}
			});
		},

		saveOperators: function(){
			var parameters = Form.serialize($("workingPlaceForm"), {hash:true});
			new Ajax.Request(contextPath + "/workingPlace/save.action", {
				parameters:parameters,
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;

						if($("saveSuccessMessage") != null){
							Consulte.toggleDimmer("dimmerCover", false);
							$("saveSuccessMessage").show();
							if($("topMessage")) $("topMessage").show();
						}
					}
				}
			});
		},

		goManageOperators: function(){
			window.location.href = contextPath + "/operator/main.action";
		},
		
		save: function(){
			if(this.validateMandatoryFields("step4")){
				var parameters = Form.serialize($("workingPlaceForm"), {hash:true});
				parameters["workingPlace.retainedInsurances"] = this.getComboAsArray("workingPlace.healthInsurances");
				parameters["workingPlace.retainedProcedures"] = this.getComboAsArray("workingPlace.procedures");
				parameters["sendMailtoCustomers"] = this.askSendMailToCustomers();
				
				new Ajax.Request(contextPath + "/workingPlace/save.action", {
					parameters:parameters,
					onComplete:function(response){
						if(Consulte.hasError(response) == false){
							if(Consulte.getHeaderAsJSON(response, "X-Consulte-SameAddressWP") == true){
								this.LBSameAddress = new LightBox(response.responseText, {title:Bundle.getMessage("txt.warning")});
								this.LBSameAddress.show();
							}else{
								Consulte.showErrorMessage(Bundle.getMessage("message.warning.alter.workingPlace"));
								
								$("content").innerHTML = response.responseText;

								if($("saveSuccessMessage") != null){
									Consulte.toggleDimmer("dimmerCover", false);
									$("saveSuccessMessage").show();
									if($("topMessage")) $("topMessage").show();
								}
							}
						}
					}.bind(this)
				});
			}
		},
		
		closeLBSameAddress: function(){
			this.LBSameAddress.close();
		},
		
		unlinkOperator: function(field){
			if(!field.checked){
				if(Consulte.showConfirmMessage(Bundle.getMessage("message.confirm.unlink.operator.workingPlace"))){
					field.checked = false;
				}else{
					field.checked = true;
				}
			}
		},
		
		activate: function(){
			if(this.validateMandatoryFields("step4") &&
			   Consulte.showConfirmMessage(Bundle.getMessage("message.confirm.activate.workingPlace"))){

				var parameters = Form.serialize($("workingPlaceForm"), {hash:true});
				parameters["workingPlace.retainedInsurances"] = this.getComboAsArray("workingPlace.healthInsurances");
				parameters["workingPlace.retainedProcedures"] = this.getComboAsArray("workingPlace.procedures");
				parameters["sendMailtoCustomers"] = this.askSendMailToCustomers();

				new Ajax.Request(contextPath + "/workingPlace/activate.action", {
					parameters:parameters,
					onComplete:function(response){
						if(Consulte.hasError(response) == false){
							Consulte.showErrorMessage(Bundle.getMessage("message.warning.alter.workingPlace"));
							Consulte.toggleDimmer("dimmerCover", false);
							$("content").innerHTML = response.responseText;
						}
					}
				});
			}
		},

		deactivate: function(){
			if(Consulte.showConfirmMessage(Bundle.getMessage("message.confirm.deactivate.workingPlace"))){
				var flag = this.askSendMailToCustomers();
				new Ajax.Request(contextPath + "/workingPlace/deactivate.action", {
					parameters:{sendMailtoCustomers:flag},
					onComplete:function(response){
						if(Consulte.hasError(response) == false){
							if(Consulte.getHeaderAsJSON(response, "X-Consulte-OtherActiveOwners") == true){
								this.LBDeactivateAllOwners = new LightBox(response.responseText, {title:Bundle.getMessage("txt.warning")});
								this.LBDeactivateAllOwners.show();
							}else{
								Consulte.showErrorMessage(Bundle.getMessage("message.warning.alter.workingPlace"));
								Consulte.toggleDimmer("dimmerCover", false);
								$("content").innerHTML = response.responseText;
							}
						}
					}
				});
			}else{
				Consulte.showInfoMessage(Bundle.getMessage("message.warinig.deactivate.workingPlace"));
			}
		},
		
		deactivateAll: function(sendMailtoCustomers, removeAll){
			new Ajax.Request(contextPath + "/workingPlace/deactivate.action", {
				parameters:{sendMailtoCustomers:sendMailtoCustomers, removeAll:removeAll},
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						this.LBDeactivateAllOwners.close();
						Consulte.showErrorMessage(Bundle.getMessage("message.warning.alter.workingPlace"));
						Consulte.toggleDimmer("dimmerCover", false);
						$("content").innerHTML = response.responseText;
					}
				}
			});
		},
		
		askSendMailToCustomers: function(){
			var hasCustomerActive = false;
			new Ajax.Request(window.contextPath+"/hasCustomerActive.action", {
				asynchronous: false,
				parameters:{
					ownerId: $F("ownerId"),
					workingPlaceId: $F("workingPlace.id")
				},
				onComplete: function(response){
					hasCustomerActive = (String.interpret(response.responseText).strip().toLowerCase() == "true");
				}
			});
			return (hasCustomerActive && 
					Consulte.showConfirmMessage(Bundle.getMessage("message.confirm.send.mail.customers.workingPlace")) &&
					Consulte.showConfirmMessage(Bundle.getMessage("message.reconfirm.send.mail.customers.workingPlace")));
		},

		cancel: function(){
			if(Consulte.showConfirmMessage(Bundle.getMessage("message.cancel.process"))){
				Consulte.toggleDimmer("dimmerCover", false);
				var parameters = {};
				
				if($("operatorId") != null && !Consulte.isEmpty("operatorId")){ //operador admin
					parameters = {
						"ownerId":$F("ownerId"),
						"operatorId":$F("operatorId")
					};
				}
				
				new Ajax.Request(contextPath + "/workingPlace/cancel.action", {
					parameters:parameters,
					onComplete:function(response){
						if(Consulte.hasError(response) == false){
							$("content").innerHTML = response.responseText;
						}
					}
				});
			}
		},
		
		insert: function(){
			new Ajax.Request(contextPath + "/workingPlace/insert.action", {
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("content").innerHTML = response.responseText;
					}
				}
			});
		},
		
		approvePendingOwners: function(id){
			new Ajax.Request(contextPath + "/workingPlace/ownersApproval.action", {
				parameters:{id:id},
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						this.LBApproval = new LightBox(response.responseText, {title:Bundle.getMessage("txt.approval.disapproval.owners"), onClose:this.cancelLBApproval.bind(this)});
						this.LBApproval.show();
					}
				}.bind(this)
			});
		},
		
		cancelLBApproval: function(){
			this.list();
		},

		closeLBApproval: function(){
			this.LBApproval.close();
		},
		
		approval: function(id, flag){
			new Ajax.Request(contextPath + "/workingPlace/approval.action", {
				parameters:{
					id:$("workingPlaceId").value,
					ownerId:id, 
					approve:flag
				},
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("owner_"+id).remove();
						
						if($A($$("id^=owner_")).length < 1){
							$("workingPlace.owners.list").innerHTML = Bundle.getMessage("message.no.owners.to.approve");
							$("workingPlace.owners.list").show();
						}
					}
				}
			});
		},
		
		step2: function(){
			var mode = $("workingPlace.mode").value;
			var step = $("workingPlace.step").value;
			var parameters = {};
			
			if(step == "1" || step == "4"){
				parameters = {
					crm:$F("crm"),
					"crmState.id":$F("crmStateId")
				};
			}
			
			if(step == "4" || this.validateMandatoryFields("step1")){
				new Ajax.Request(contextPath + "/workingPlace/confirm.action", {
					parameters:parameters,
					onComplete:function(response){
						if(Consulte.hasError(response) == false){
							$("content").innerHTML = response.responseText;
						}
					}
				});
			}
		},
		
		step3: function(){
			var id = 0;
			var mode = $("workingPlace.mode").value;
			var step = $("workingPlace.step").value;
			
			if(step == 2){
				//Pega o consultorio, radio selecionado
				$$("#content .radioWorkingPlace").each(function(element){
					element = $(element);
					if(element.checked){
						id = element.value;
						throw $break;
					}
				});
			}else{
				if(mode != "new"){
					var id = $("workingPlace.id").value;
				}
			}
			
			if(id == 0 && mode != "new"){
				Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.select.workingPlace"));
			}else{
				if(mode == "link"){
					this.detail(id);
				}else{
					this.basic(id);
				}
			}
		},
		
		step4: function(){
			var mode = $("workingPlace.mode").value;
			var step = $("workingPlace.step").value;
			
			if(this.validateMandatoryFields("step3")){
				var parameters = Form.serialize($("workingPlaceForm"), {hash:true});
				parameters["workingPlace.address.zipCode"]              = Mask.clear(parameters["workingPlace.address.zipCode"]);
				parameters["workingPlace.phoneNumbers.phone1.areaCode"] = Mask.clear(parameters["workingPlace.phoneNumbers.phone1.areaCode"]);
				parameters["workingPlace.phoneNumbers.phone1.number"]   = Mask.clear(parameters["workingPlace.phoneNumbers.phone1.number"]);
				parameters["workingPlace.phoneNumbers.phone2.areaCode"] = Mask.clear(parameters["workingPlace.phoneNumbers.phone2.areaCode"]);
				parameters["workingPlace.phoneNumbers.phone2.number"]   = Mask.clear(parameters["workingPlace.phoneNumbers.phone2.number"]);
				parameters["workingPlace.phoneNumbers.phone3.areaCode"] = Mask.clear(parameters["workingPlace.phoneNumbers.phone3.areaCode"]);
				parameters["workingPlace.phoneNumbers.phone3.number"]   = Mask.clear(parameters["workingPlace.phoneNumbers.phone3.number"]);
				
				if(mode != "new"){
					parameters["workingPlace.retainedOwners"] = this.getComboAsArray("workingPlace.owners");
				}
				
				new Ajax.Request(contextPath + "/workingPlace/detail.action", {
					parameters:parameters,
					onComplete:function(response){
						if(Consulte.hasError(response) == false){
							$("content").innerHTML = response.responseText;
						}
					}
				});
			}
		},
		
		removeThis: function(num){
			var field = null;
			
			switch(num){
				case 1: 
					field = "workingPlace.owners";
					if($(field).selectedIndex >= 0 && !Consulte.showConfirmMessage(Bundle.getMessage("message.confirm.deactivate.workingPlace"))){
						return;
					}
				break;
				case 2: 
					field = "workingPlace.healthInsurances";
				break;
				case 3: 
					field = "workingPlace.procedures"; 
				break;
			}
			
			$A($(field).options).each(function(option){
				option = $(option);
				if(option.selected){
					if(option.text == "Particular"){
						$("removedParticular").value = "true";
					}
					option.remove();
				}
			});
		},
		
		validateMandatoryFields: function(step){
			try{
				switch(step){
					case "step1":
						Consulte.mandatory("crm", "label.crm", {showInfoMessage:false});
						Consulte.mandatory("crmState", "label.crm.uf", {showInfoMessage:false});
					break;
					
					case "step2":
					break;
					
					case "step3":
						Consulte.mandatory("workingPlace.name", "label.workingPlace.name");

						//Valida o CEP
						Consulte.mandatory("workingPlace.zipCode", "label.cep");
						this.validateCep(false);

						//Valida email
						if(!Consulte.isEmpty($("workingPlace.email"))){
							Consulte.validateEmail("workingPlace.email", "label.email");
						}
						
						//Valida Telefones
						var found = false;
						var isCell = false;
						var codes   = ["workingPlace.phoneAreaCode1", "workingPlace.phoneAreaCode2", "workingPlace.phoneAreaCode3"],
						    numbers = ["workingPlace.phoneNumber1", "workingPlace.phoneNumber2", "workingPlace.phoneNumber3"],
						    labels  = "label.phoneNumbers";

						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));
									areaCode.activate();
									throw Consulte.$error;
								}
								if(n.length < 8){
									Consulte.showErrorMessage(Bundle.getMessage("message.invalid.field", labels));
									number.activate();
									throw Consulte.$error;
								}
								found = true;
								if(phoneIndex == 0)
									isCell = true;
							}
						}
						
						if(!found){
							Consulte.showErrorMessage(Bundle.getMessage("message.no.phone"));
							$("workingPlace.phoneAreaCode1").activate();
							throw Consulte.$error;
						}

						//Valida a opção de avançar mantendo o cep informado
						if(!Consulte.userWantedToKeepInvalidCep("workingPlace.invalidCepDiv", "workingPlace.keepInvalidCep")){
							Consulte.showInfoMessage(Bundle.getMessage("message.cep.do.something"));
							throw Consulte.$error;
						}
					break;

					case "step4":
						Consulte.mandatory("workingPlace.state", "label.state");
						Consulte.mandatory("workingPlace.city", "label.city");
						Consulte.mandatory("workingPlace.neighborhood", "label.neighborhood");
						Consulte.mandatory("workingPlace.street", "label.street");
						Consulte.mandatory("workingPlace.number", "label.number");
						if($("workingPlace.healthInsurances").options.length < 1){
							Consulte.showInfoMessage(Bundle.getMessage("message.mandatory.info"));
							Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.select.insurance"));
							throw Consulte.$error;
						}

						/*
						//Verifica se estado digitado é valido
						if(this.errorState == true){
							Consulte.showErrorMessage(Bundle.getMessage("message.error.state"));
							throw Consulte.$error;
						}
						
						//Verifica se cidade digitada é valida
						if(this.errorCity == true){
							Consulte.showErrorMessage(Bundle.getMessage("message.error.city"));
							throw Consulte.$error;
						}
						*/
						
					break;
				}
				return true;
			}catch(e){
				if(e != Consulte.$error) throw e;
				return false;
			}
		},
		
		validateCep: function(async){
			Consulte.validateCep($F("workingPlace.zipCode"), "workingPlace.keepInvalidCep", "workingPlace.invalidCepDiv", async);
		},
		
		toggleListOrder: function(){
			var obj = $("ordenar_div");
			var arrow = $("img_ordenar");

			if(obj.visible()){
				obj.hide();
				arrow.className = "img_mostrar";
			}else{
				obj.show();
				arrow.className = "img_esconder";
			}
		},
		
		getComboAsArray: function(field){
			var removed = new Array();
			field = $(field);
			for(var i = 0; i < field.options.length; i++){
				removed.push(Object.toJSON({id:field.options[i].value, name:field.options[i].text}));
			}
			removed.push("");
			return removed;
		},
		
		/* AUTOCOMPLETE */
		/* ************ */
		
		// ESTADO
		bindCRMState: 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 : "";
				$("crmStateId").value = id;
			}.bind(this));
		},
		
		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($("workingPlace.city")).unautocomplete();
					if($("workingPlace.city").value == Bundle.getMessage("txt.select.state")){
						$("workingPlace.city").value = "";
					}
					$("workingPlace.city").readOnly = true;
					if(item != null){
						this.listCities(item.id);
						$("workingPlace.city").readOnly = false;
					}
					this.lastStateId = id;
					$("workingPlace.stateId").value = id;
					//this.errorState = (item == null);
				}
			}.bind(this));
		},
		listCRMStates:function(){
			jQuery($("crmState")).showAll();
		},
		listStates:function(){
			jQuery($("workingPlace.state")).showAll();
		},
		checkCRMState: function() {
			jQuery($("crmState")).search();
		},
    	checkState: function() {
			if(this.enableCheckState){
				var state = $("workingPlace.state");
				var city = $("workingPlace.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();
			}
        },
		
		// CIDADE
		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 : "";
            	$("workingPlace.cityId").value = id;
            	//this.errorCity = (item == null);
            });
		},
		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("workingPlace.city", cities);
                    }
                }.bind(this)
            });
		},
        checkCity: function(){
			if(this.enableCheckState){
				var city = $("workingPlace.city");
				var neighborhood = $("workingPlace.neighborhood");
				var address = $("workingPlace.street");
				var number = $("workingPlace.number");
				var complement = $("workingPlace.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();
				}
			}
        },
		
		// INSTITUICAO
		bindCompany:function(field, data){
            jQuery($(field)).autocomplete(data, {
                minChars: 3,
                delay: 500,
                width: 218,
                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 : "";
            	$("workingPlace.company.id").value = id;
            }.bind(this));
		},		
		listCompanies:function(){
			jQuery($("workingPlace.company")).showAll();
		},

		// CONVENIOS
		bindHealthInsurance:function(field, data){
            jQuery($(field)).autocomplete(data, {
                minChars: 3,
                delay: 500,
                width: 418,
                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 : 0;
            	this.healthInsuranceId = id;
            }.bind(this));
		},
		listHealthInsurances:function(){
			jQuery($("workingPlace.healthInsurancesCombo")).showAll();
		},
		checkHealthInsurance: function(){
			this.processCombo("workingPlace.healthInsurancesCombo", "workingPlace.healthInsurances", this.healthInsuranceId);
		},
		
		// PROCEDIMENTOS
		bindProcedure:function(field, data){
            jQuery($(field)).autocomplete(data, {
                minChars: 3,
                delay: 500,
                width: 418,
                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 : 0;
            	this.procedureId = id;
            }.bind(this));
		},
		listProcedures:function(){
			jQuery($("workingPlace.proceduresCombo")).showAll();
		},
		checkProcedure: function(){
			this.processCombo("workingPlace.proceduresCombo", "workingPlace.procedures", this.procedureId);
		},
		//--------------------------------------------
		
		clearDependedField:function(){	
			if($("workingPlace.city").value == Bundle.getMessage("txt.select.state"))
				$("workingPlace.city").value = "";

			if($("workingPlace.neighborhood").value == Bundle.getMessage("txt.select.city"))
            	$("workingPlace.neighborhood").value = "";

			if($("workingPlace.street").value == Bundle.getMessage("txt.select.city"))
            	$("workingPlace.street").value = "";

			if($("workingPlace.number").value == Bundle.getMessage("txt.select.city"))
            	$("workingPlace.number").value = "";

			if($("workingPlace.complement").value == Bundle.getMessage("txt.select.city"))
            	$("workingPlace.complement").value = "";
		},
		
		processCombo: function(combo, source, id){
			var target = new Array();
			source = $(source);
			combo = $(combo);
			
			if(id == 0){
				return;
			}
			
			// Le todo o select,
			// compara se existe o valor selecionado na combo,
			// se existir, ignora processamento,
			// salva num array
			for(var i = 0; i < source.options.length; i++){
				var option = source.options[i];
				if(option.value == id){
					return;
				}
				target.push(option);
			}

			if(combo.value == "Particular"){
				$("removedParticular").value = "false";
			}
			
			// Salva o  valor selecionado na combo
			target.push(new Option(combo.value, id));
			// Ordena o array
			target.sort(function(opt1, opt2){
				return opt2.text < opt1.text;
			});
			// Limpa o select
			source.options.length = 0;
			// Grava o array no select
			for(var i = 0; i < target.length; i++){
				source.options[i] = target[i];
			}
		}
		
	};
}

