 /***************************************************************
  * @authot : Randrianarivelo Tiana
  * @Date ! 10/06/08
  * @version : 0.1
  * SensorDialog 
  * Function lists :
  */
 SensorDialog = {
  //Public Attributes
	id : "default_id",  // Sensor Dialog ID
	id_sensor : "", // Current Sensor ( System ) ID
	url : "http://192.168.6.34/SOServer/SOService",  // Service URL
	date_begin : "",
	date_end : "",
	sc : null,
	//Private attributes
	models : [],
	observationTemplates : [],
	observationTemplates_valid : [],
	components : [],
	components_valid : [],
	dijits_tab : [],
	//Public methodes
	
	getFeatureinfo : function(id,url){
		console.debug("getFeatureinfo : "+id+" et " +url);
		this.id_sensor = id;
		this.url=url;
		var return_value = {"service_url" : url,"id_sensor" :id};
		this.initializeSensorDialog(return_value);  
	},
  
	/* initializeSensorDialog : */
	/*   @param parameter : Feature Info result */
	initializeSensorDialog : function(id,url){
		console.debug("initializeSensorDialog : ");
		this.waitMessage("swe_messagelog",true);
		this.initializeVars(id,url);
		this.initializeDialogTemplate();
		this.createSensorList();
		this.ajax_createComponentList_call(this.id_sensor);        	
	},
	
	initializeVars : function(id,url){
		this.id_sensor = id;
		this.url=url;
		this.chart = [];
		this.date_begin = this.getCurrentDateMinus() ;
		this.date_end = this.getCurrentDate();
		this.models = [];
		this.observationTemplates =[];
		this.observationTemplates_valid =[];
		this.components = [];
		this.components_valid = [];
		this.sc = null;
		this.sc = sensorchart;
		this.sc.initializeSensorChart();
		this.sc.sampling_time ={"begin":this.parseDateToString(this.date_begin),"end":this.parseDateToString(this.date_end)};
		this.dijits_tab= [
			"swe_date_begin_input",
			"swe_date_end_input",
			"swe_chart_update_button"
			];
		
	},
	getCurrentDate : function(){
		return new Date();
	},
	
	getCurrentDateMinus : function(){
		var date = new Date();
		date.setDate(date.getDate()-8);
		return date;
	},

	initializeDialogTemplate : function(){
		document.getElementById("swe_infos").style.display="none";
	},
	clean : function(){
		for(var i=0;i<this.dijits_tab.length;i++){
			if (dijit.byId(this.dijits_tab[i])){
				dijit.byId(this.dijits_tab[i]).destroy();
			}
		}
	},
	
	ajax_createComponentList_call: function(sensor){
		console.debug("ajax_createComponentList_call : "+sensor);
		var describe_request = sosrequest.createSOAPDescribeSensor(sensor);
		var url = this.url;
		var handleAs = "xml";
		var obj=this;
		var ajax_createComponentList_callBack = function(response,ioargs){
			obj.ajax_createComponentList_callBack(response);
		}
		dojo.rawXhrPost({
			url: url,
			handleAs: handleAs,
			headers:{"SOAPAction":""},
			postData:describe_request,
			contentType: "text/xml;charset=utf-8",
			sync: false,
			load: ajax_createComponentList_callBack,
			error: function(response, ioArgs) {
				console.error("HTTP status code: ", ioArgs.xhr.status);
			}
		});
	},
	ajax_createComponentList_callBack: function(response){
		//console.debug("ajax_createComponentList_callBack : "+sensor);
		var system= sensorinfos.getSystemInfos(response);
		this._ajax_for_called=0;
		this._ajax_system=system;
		for(var i =0;i<system.components.length;i++){
			var componentid = system.components[i];
			this.ajax_getComponentDetails_call(componentid);
		}
	},
	ajax_getComponentDetails_call : function(componentid){
		var describe_request = sosrequest.createSOAPDescribeSensor(componentid);
		var obj = this;
		var ajax_getComponentDetails_callBack = function(response,ioargs){
			obj.ajax_getComponentDetails_callBack(response,componentid);
		}
		var url = this.url;
		var handleAs = "xml";
		dojo.rawXhrPost({
			url: url,
			handleAs: handleAs,
			headers:{"SOAPAction":""},
			postData:describe_request,
			contentType: "text/xml;charset=utf-8",
			sync: false,
			load: ajax_getComponentDetails_callBack,
			error: function(response, ioArgs) {
				console.error("HTTP status code: ", ioArgs.xhr.status);
			}
		});
	},
	
	ajax_getComponentDetails_callBack : function(response,componentid){
		var component = sensorinfos.getComponentInfos(response);
		var i  = this._ajax_for_called;
		this.components[i]={};			
		this.components[i].sensorid=componentid;
		this.components[i].description=component.description;
		this.components[i].phenomenon=component.phenomenon;
		this.components[i].units=component.units;
		this.components[i].show=false;
		this.components[i].firstAdd=true;
		this.components[i].model={};
		this.components[i].model.describeModel={};
		this.components[i].model.describeModel.output=component.phenomenon;
		this.components[i].model.describeModel.units=component.units;
		
		
		this.components_valid[i]={};
		this.components_valid[i].sensorid=sensorinfos.getIdValid(componentid);
		this.components_valid[i].description=component.description;
		this.components_valid[i].phenomenon=component.phenomenon;
		this.components_valid[i].units=component.units;
		this.components_valid[i].show=false;
		this.components_valid[i].firstAdd=true;
		this._ajax_for_called+=1;	
		
		if(this._ajax_for_called==this._ajax_system.components.length){
			this.ajax_createComponentList();
		}
	},
	
	ajax_createComponentList : function(){
		var innerhtml='';
		var components = this.components;
	 	for(i=0;i<components.length;i++){
			innerhtml+=' <input id="'+components[i].sensorid+'" dojoType="dijit.form.CheckBox" name="'+components[i].description+'"  value="off" type="checkbox" />'+
				' <label for="'+components[i].sensorid+'"> '+components[i].description+' </label>';
	 	}
	 	dojo.byId('swe_sensor_components').innerHTML=innerhtml;
		for(var i=0;i<components.length;i++){
			var foo = dojo.connect(dojo.byId(components[i].sensorid), 'onclick',this,this.componentEvent);
		}
		
		this.ajax_initChart_call();
	},
	
	deActivateAllExcept : function(dijit_id){
		for(var i=0;i<this.dijits_tab.length;i++){
			if(dijit.byId(this.dijits_tab[i])){
				if(this.dijits_tab[i].indexOf(dijit_id) ==-1 ) {
					dijit.byId(this.dijits_tab[i]).setDisabled(true);
				}	
			}
		}
	},
	deActivateAll : function(){
		for(var i=0;i<this.dijits_tab.length;i++){
			if(dijit.byId(this.dijits_tab[i])){
					dijit.byId(this.dijits_tab[i]).setDisabled(true);
			}
		}
	},
	
	activateAll : function(){
		for(var i=0;i<this.dijits_tab.length;i++){
			if(dijit.byId(this.dijits_tab[i])){
					dijit.byId(this.dijits_tab[i]).setDisabled(false);
			}
		}
	},
	ajax_initChart_call : function(){
		var component = {};
		var component_valid = {};
		
		this._ajax_forchart_called_string=0;
		this._ajax_forchart_called_valid=0;
		
		for(var i=0;i<this.components.length;i++){
			var getobs_request = sosrequest.createSOAPGetObservation(this.components[i]);
			var getobs_request_valid = sosrequest.createSOAPGetObservation(this.components_valid[i]);
			
			this.observationTemplates[i] = sensorinfos.getObservationTemplate(sosrequest.doSOAPRequest(getobs_request,this.url,"xml"));
			this.observationTemplates_valid[i] = sensorinfos.getObservationTemplate(sosrequest.doSOAPRequest(getobs_request_valid,this.url,"xml"));
			
			this.observationTemplates[i] = this.observationTemplates[i].replace(/\s+/g,'');
			this.observationTemplates_valid[i] = this.observationTemplates_valid[i].replace(/\s+/g,'');
			
			var sampling_time ={"begin":this.parseDateToString(this.date_begin),"end":this.parseDateToString(this.date_end)};
			
			var getresult_request = sosrequest.createSOAPGetResult(sampling_time,this.observationTemplates[i]);
			var getresult_request_valid = sosrequest.createSOAPGetResult(sampling_time,this.observationTemplates_valid[i]);
			
			var url = this.url;
			var handleAs = "xml";
			var obj = this;
			
			var ajax_initChart_callBack_string = function(response,ioargs){
				obj.ajax_initChart_callBack_string(response);
			}
			var ajax_initChart_callBack_valid = function(response,ioargs){
				obj.ajax_initChart_callBack_valid(response);
			}
			
			dojo.rawXhrPost({
				url: url,
				handleAs: handleAs,
				headers:{"SOAPAction":""},
				postData:getresult_request,
				contentType: "text/xml;charset=utf-8",
				sync: false,
				load: ajax_initChart_callBack_string,
				error: function(response, ioArgs) {
					alert("error");
					console.error("HTTP status code: ", ioArgs.xhr.status);
				}
			});
			dojo.rawXhrPost({
				url: url,
				handleAs: handleAs,
				headers:{"SOAPAction":""},
				postData:getresult_request_valid,
				contentType: "text/xml;charset=utf-8",
				sync: false,
				load: ajax_initChart_callBack_valid,
				error: function(response, ioArgs) {
					console.error("HTTP status code: ", ioArgs.xhr.status);
					alert("error");
				}
			});

		}
	},
	ajax_initChart_callBack_string : function(response){
		var i = this._ajax_forchart_called_string;
		this.components[i].model.string=""+sensorinfos.getResult(response);
		this._ajax_forchart_called_string+=1;
		if(this._ajax_forchart_called_valid == this.components.length && this._ajax_forchart_called_string==this.components.length){
			this.ajax_initChart_callBack_end();
		}
		
	},
	ajax_initChart_callBack_valid : function(response){
		var i = this._ajax_forchart_called_valid;
		this.components[i].model.valid=""+sensorinfos.getResult(response);
		this._ajax_forchart_called_valid+=1;
		if(this._ajax_forchart_called_valid== this.components.length && this._ajax_forchart_called_string== this.components.length){
			this.ajax_initChart_callBack_end();
		}
		
	},
	
	ajax_initChart_callBack_end : function(){
		this.waitMessage("swe_messagelog",false);
		this.waitMessage("swe_infos",true);
	},
	

	/* createSensorList : */
	createSensorList : function(){
		console.debug("createSensorList : ");
		var id_sensor=this.id_sensor;
		dojo.byId('swe_sensor_list').innerHTML='<input type="radio" name="sensor" id="'+id_sensor+'" value="'+id_sensor+'" dojoType="dijit.form.RadioButton" checked="checked">'+
			'<label for="'+id_sensor+'">Station  '+id_sensor+'</label>';
			//'<input type="radio" name="sensor" id="'+id_sensor+'_valid" value="'+id_sensor+'_valid" dojoType="dijit.form.RadioButton"/>'+
			//'<label for="'+id_sensor+'_valid'+'">Station  '+id_sensor+'_valid ( <a href="" >Infoterre fiche</a> )</label><br/>'+
			
		var foo1 = dojo.connect(dojo.byId(id_sensor), 'onclick',this,this.componentEvent);	
	
	},

	getFiche : function(id){
		var describe_request = sosrequest.createSOAPDescribeSensor(id);
		var response = sosrequest.doSOAPRequest(describe_request,this.url,"text");
		var newpage=open("",'popup','width=400,height=400,toolbar=no,scrollbars=no,resizable=no');
		newpage.document.write(response);
	},

	componentEvent : function(evt){
		console.debug("componentEvent : ");
		var sc = sensorchart;
		var component = ""+evt.target.id;
		var components = this.components;
		var i = 0;

		while(components[i].sensorid !=component && i < components.length) {i++;}

		if (components[i].show==false){
			components[i].show=true;
			if (components[i].firstAdd == true ) {
				components[i].firstAdd=false;
				sc.addComponent(components[i]);
				dijit.byId("swe_date_begin_input").setValue(this.date_begin);
				dijit.byId("swe_date_end_input").setValue(this.date_end);
			}
			sc.showComponent(components[i].sensorid);
		}
		else{
			components[i].show=false;
			sc.hideComponent(components[i].sensorid);
		}
		this.components = components;
	},

	/**updateChart **/
	updateChart : function(){
		this.validateSamplingTime();
		this.ajax_getData_callBack_count=0;
		this.ajax_getData_call_count=0;		
		for(var i=0;i<this.components.length;i++){
			if(this.components[i].show==true){
				this.ajax_getData_call(i);
			}
		}
	},
	
	validateSamplingTime : function(){
		if(this.sc.compareDate(this.date_begin,this.date_end)>-1){
			temp=new Date(this.date_begin.getFullYear() ,this.date_begin.getMonth(), this.date_begin.getDate(),0,0,0);
			this.date_begin=new Date(this.date_end.getFullYear() ,this.date_end.getMonth(), this.date_end.getDate(),0,0,0);;
			this.date_end=new Date(temp.getFullYear() ,temp.getMonth(), temp.getDate(),0,0,0);;
		}
	},
	
	searchComponent : function(sensorid){
		var i =0;
		var j =-1;
		while( i < this.components.length){
			if(sensorid==this.components[i].sensorid ){
				var j= i;
				i=this.components.length;
			}
			i++;
		}
		return j;
	},
	
	parseDateToString : function(date){
		var month = date.getMonth()+1;
		var day=date.getDate();
		if (month<10) month="0"+month;
		if (day<10) day="0"+day;
		return ""+date.getFullYear()+"-"+month+"-"+day+"T00:00:00";
	},
	
	ajax_getData_call : function(i){
		this.waitMessage("swe_chart_fieldset",false);
		this.waitMessage("swe_messagelog_chart",true);
		this.deActivateAll();
		var sampling_time ={"begin":this.parseDateToString(this.date_begin),"end":this.parseDateToString(this.date_end)};
		var getresult_request = sosrequest.createSOAPGetResult(sampling_time,this.observationTemplates[i]);
		var getresult_request_valid = sosrequest.createSOAPGetResult(sampling_time,this.observationTemplates_valid[i]);
		var url = this.url;
		var handleAs = "xml";
		var obj = this;
		this.ajax_getData_call_count+=1;
		
		var ajax_getData_callBack_valid = function(response,ioargs){
			obj.ajax_getData_callBack(i,response,true);
		}
		var ajax_getData_callBack_raw= function(response,ioargs){
			obj.ajax_getData_callBack(i,response,false);
		}
		dojo.rawXhrPost({
			url: url,
			handleAs: handleAs,
			headers:{"SOAPAction":""},
			postData:getresult_request,
			contentType: "text/xml;charset=utf-8",
			sync: false,
			load: ajax_getData_callBack_raw,
			error: function(response, ioArgs) {
				console.error("HTTP status code: ", ioArgs.xhr.status);
			}
		});
		dojo.rawXhrPost({
			url: url,
			handleAs: handleAs,
			headers:{"SOAPAction":""},
			postData:getresult_request_valid,
			contentType: "text/xml;charset=utf-8",
			sync: false,
			load: ajax_getData_callBack_valid,
			error: function(response, ioArgs) {
				console.error("HTTP status code: ", ioArgs.xhr.status);
			}
		});
		
	},
	sosrequest_doSOAPRequest : function(url,handleAs,postData,callback_function){
		dojo.rawXhrPost({
			url: url,
			handleAs: handleAs,
			headers:{"SOAPAction":""},
			postData:postData,
			contentType: "text/xml;charset=utf-8",
			sync: false,
			load: callback_function,
			error: function(response, ioArgs) {
				console.error("HTTP status code: ", ioArgs.xhr.status);
			}
		});
	},
		
	ajax_getData_callBack :function(i,response,valid){
		this.ajax_getData_callBack_count+=1;
		if (valid){
			this.components[i].model.valid=""+sensorinfos.getResult(response);
			}
		else {
			this.components[i].model.string=""+sensorinfos.getResult(response);
		}
		if (this.ajax_getData_callBack_count==2*this.ajax_getData_call_count){
			this.waitMessage("swe_chart_fieldset",true);
			for(var i=0;i<this.components.length;i++){
				if(this.components[i].show==true){
					this.sc.updateComponent(this.components[i]);
				}
			}
			this.waitMessage("swe_messagelog_chart",false);
			this.activateAll();
			
		}
	},
	updateGrapheBegin : function(value){
		this.date_begin = new Date(value);
		this.sc.sampling_time.begin= this.parseDateToString(this.date_begin);
		console.debug(this.date_begin);
	},
	updateGrapheEnd : function(value){
		this.date_end  = new Date(value);
		this.sc.sampling_time.end=  this.parseDateToString(this.date_end);
		console.debug(this.date_end);
	},
	
	showHideSeries : function(name,obj){
		var value = obj.value;
		if (value.indexOf("on") !=-1) this.sc.showSeries(name);
		else this.sc.hideSeries(name);
	},
	
	waitMessage : function(divid,show){
		if(show) {
			dojo.byId(divid).style.display="block";
		}
		else {
			dojo.byId(divid).style.display="none";
		}
	}
}