if(!window.Report){
	window.Report = {

		init: function(){
			var reportForm= $("reportFilterForm");
			var report = $("report").value;

			switch(report){
				case "customerList":
				case "scheduleList":
				case "schedulesByHealthInsurance":
				case "schedulesByActivity":
				case "schedulesByStatus":
				case "schedulesByMonth":
				case "schedulesTiming":
				case "customerProfile":
					if(reportForm != null){
						var begin = reportForm.select("input[name=filter.scheduleBegin]").first();
						Calendar.bindToField(begin);
						Mask.numberField(begin, Mask.DATE);
						
						var end = reportForm.select("input[name=filter.scheduleEnd]").first();
						Calendar.bindToField(end);
						Mask.numberField(end, Mask.DATE);
						
						this.workingPlaces = $F("ownerWorkingPlaces.json").evalJSON();
						this.bindWorkingPlaces();
						
						this.healthInsurances = this.getHealthInsurances();
						this.bindHealthInsurance(null);
						
						this.selectProcedure("A");
					}
				break;
			}
					
			Consulte.enableGlossary();
			Consulte.setBackOptions({parameters:{"filter.ownerId":$F("filter.ownerId")}}, 1);
		},
		
		getHealthInsurances: function(){
			var hash = $H();
			var target = new Array();
			var source = this.workingPlaces;
				
			for(var i =0; i < source.length; i++){
				for(var j = 0; j < source[i].healthInsurances.length; j++){
					if(hash.get(source[i].healthInsurances[j].id) != true){
						hash.set(source[i].healthInsurances[j].id, true);
						target.push(source[i].healthInsurances[j]);
					}
				}
			}
			
			target.sort(function(opt1, opt2){
				return opt2.name < opt1.name;
			});
			
			return target;
		},
		
		getActivities: function(){
			var hash = $H();
			var target = new Array();
			var source = this.workingPlaces;
				
			for(var i =0; i < source.length; i++){
				for(var j = 0; j < source[i].activities.length; j++){
					if(hash.get(source[i].activities[j].id) != true){
						hash.set(source[i].activities[j].id, true);
						target.push(source[i].activities[j]);
					}
				}
			}
			
			target.sort(function(opt1, opt2){
				return opt2.name < opt1.name;
			});
			
			return target;
		},
		
		getProcedures: function(){
			var hash = $H();
			var target = new Array();
			var source = this.workingPlaces;
				
			for(var i =0; i < source.length; i++){
				for(var j = 0; j < source[i].procedures.length; j++){
					if(hash.get(source[i].procedures[j].id) != true){
						hash.set(source[i].procedures[j].id, true);
						target.push(source[i].procedures[j]);
					}
				}
			}
			
			target.sort(function(opt1, opt2){
				return opt2.name < opt1.name;
			});
			
			return target;
		},

		search: function(){
			if(!this.validateSearch()) return;

			var statusDesc = $("filter.statusDesc");
			if(statusDesc != null){
				var array = [];
				var options = $A($("filter.status").options);
				options.each(function(opt){
					if(opt.selected){
						array.push(opt.text);
						if(opt.value == "") throw $break;
					}
				});
				statusDesc.value = array.join(", ");
			}

			var parameters = Form.serialize($("reportFilterForm"), {hash:true});
			new Ajax.Request(contextPath + "/report/list.action", {
				parameters:parameters,
				onComplete:function(response){
					if(Consulte.hasError(response) == false){
						$("reportResult").innerHTML = response.responseText;
					}
				}
			});
		},

		validateSearch: function(){
			try{
				switch($("report").value){
					case "schedulesByMonth":
						var scheduleBegin = $("filter.scheduleBegin"), scheduleEnd = $("filter.scheduleEnd");
						var begin = Date.parse_DDMMYYYY(scheduleBegin.value);
						var end = Date.parse_DDMMYYYY(scheduleEnd.value);

						if(begin == null && end == null){
							Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.field.xor", "label.schedule.at", "label.schedule.to"));
							throw Consulte.$error;
						}

						if(begin != null ^ end != null){
							if(begin != null){
								end = begin.addDay(365);
							}
							if(end != null){
								begin = end.addDay(-365);
							}
							scheduleBegin.value = Date.format_DDMMYYYY(begin);
							scheduleEnd.value = Date.format_DDMMYYYY(end);
						}

						if(begin != null && end != null){
							var diff = (end.getTime() - begin.getTime()) / (1000*60*60*24);
							if(diff > 365){
								Consulte.showErrorMessage(Bundle.getMessage("message.report.schedule.month.year.max"));
								throw Consulte.$error;
							}
						}
					break;
					
					case "schedulesTiming":
						if(Consulte.isEmpty("filter.tolerance")){
							Consulte.showErrorMessage(Bundle.getMessage("message.mandatory.field", "label.report.tolerance"));
							$("filter.tolerance").activate();
							throw Consulte.$error;
						}
					break;
				}
			}catch(e){
				if(e != Consulte.$error) throw e;
				return false;
			}
			return true;
		},

		generatePDF: function(reportName){
			Processing.show(true);

			var form = $("pdfReportForm");
			form.descendants().each(Element.remove);

			if($(reportName) != null){
				form.appendChild(new Element("input", { type:"hidden", name:"images", value:$(reportName).getImages() }));

			} else if(reportName == "schedulesByMonth"){
				var images = {};
				$("content").select("*[id^=schedulesByMonth]").each(function(swf){
					Object.extend(images, swf.getImages().evalJSON());
				});
				form.appendChild(new Element("input", { type:"hidden", name:"images", value:Object.toJSON(images) }));
			}
			
			form.submit();

			Processing.hide.bind(Processing).defer();
		},
		
		/*
		 * COMBO CONSULTORIO
		 */
		bindWorkingPlaces: function(){
			Consulte.bindAutocomplete({
				field: "filter.workingPlace.name",
				id: "filter.workingPlace.id",
				clearedText: Bundle.getMessage("label.all"),
				autoSelectFirstIfOne: true,
				configureImage: true,
				data: this.workingPlaces,
				onSelect: this.selectWorkingPlace.bind(this),
				onClear: this.clearWorkingPlace.bind(this)
			});
			if(String.interpret($F("filter.workingPlace.id")).strip() == ""){
				this.clearWorkingPlace();
			}
		},
		
		selectWorkingPlace: function(wp){
			this.selectProcedure(Consulte.getRadioValue("filter.activityType", "content"));
			this.bindHealthInsurance(wp);
		},

		clearWorkingPlace: function(){
			this.bindHealthInsurance(null);
			this.selectProcedure(Consulte.getRadioValue("filter.activityType", "content"));
		},
		
		/*
		 * CONVENIOS
		 */
		bindHealthInsurance: function(wp){
			if(wp != null){
				this.healthInsurances = wp.healthInsurances;
			}else{
				this.healthInsurances = this.getHealthInsurances();
			}
			Consulte.bindAutocomplete({
				field: "filter.healthInsurance.name",
				id: "filter.healthInsurance.id",
				clearedText: Bundle.getMessage("label.all"),
				autoSelectFirstIfOne: true,
				configureImage: true,
				data: this.healthInsurances,
				onSelect: function(){}.bind(this)
			});
		},

		selectProcedure: function(type, event){
			var flag = (type == "A") ? null	:
				       (type == "P") ? true : false;

			if(event != null){
				var elem = Event.element(event);
				if(elem != null && elem.tagName.toLowerCase() == "span"){
					elem.select("input[type=radio]").first().checked = true;
				}
			}

			var wpId = $F("filter.workingPlace.id");
			var wp = null;
			if(String.isNotEmpty(wpId)){
				wp = this.workingPlaces.detect(this.findById.curry(wpId));
			}
			
			if(flag == null){
				this.enable(false);
			}else{
				this.enable(true);
				Consulte.bindAutocomplete({
					field: "filter.activity.name",
					id: "filter.activity.id",
					clearedText: Bundle.getMessage("label.all"),
					autoSelectFirstIfOne: true,
					configureImage: true,
					data: (flag ? (wp != null ? wp.procedures : this.getProcedures()) : (wp != null ? wp.activities : this.getActivities())),
					onSelect: function(){}.bind(this),
					onClear: function(){}.bind(this)
				});
			}
		},

		enable: function(flag){
			var activity = this.enableAutoComplete("filter.activity.name", flag);
			if($("filter.activityType.all").checked){
				activity.value = Bundle.getMessage("label.all");
				$("filter.activity.id").value = "";
			}
			activity.disabled = !flag;

			var healthInsurance = $("filter.healthInsurance.name");
			healthInsurance.value = Bundle.getMessage("label.all");
			$("filter.healthInsurance.id").value = "";
		},
		
		enableAutoComplete: function(field, flag){
			field = $(field);
			var image = field.next("img.comboImage");
			if(image != null && image.previous("input[type=text]") === field){
				image.setStyle({
					visibility: flag ? "visible" : "hidden"
				});
			}
			return field;
		},
		
		findById: function(id, obj){
			return (obj!=null && obj.id==id);
		},

		changeTab: function(tabName){
			// Esconde todas:
			$("tabHealthInsurance", "tabActivity", "tabStatus").invoke("removeClassName", "label");
			$("tabHealthInsurance", "tabActivity", "tabStatus").invoke("setStyle", "background-color:#fff");
			$("contentHealthInsurance", "contentActivity", "contentStatus").invoke("hide");

			// Mostra a selecionada:
			$("tab"+tabName).addClassName("label");
			$("content"+tabName).show();
			$("tab"+tabName).setStyle("background-color:#d6d6d6");

			this.selectedTabName = tabName;
		}
	};
}

