// JavaScript Document
// JavaScript Document
console.log("idot_correlation-loaded");
//multivariate_vis.html?map=stamen
//script_manager(["https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js","assets/js/utility/svm/svm.js","assets/js/dss_app/iowa_culvert/surveyed_result/extensions/survey_nested_mean.js"]);

$('head').append([		
		'<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>',				
		'<script src="assets/js/utility/svm/svm.js"></script>',
		'<script src="assets/js/dss_app/iowa_culvert/surveyed_result/extensions/survey_nested_mean.js"></script>',
	    '<script src="assets-examples/js/som_package/som_backage/som.js"></script>',
		'<script src="assets-examples/js/som_package/culvert_vis_analysis_som.js"></script>',
		'<script src="assets-examples/js/som_package/pcp_label_conversion.js"></script>'		
	].join('\n'));

if(!window.hasOwnProperty("idot_correlation_data")){
	window["idot_correlation_data"]={"pcp":[], };
};

 var dss_app_settings_idot_correlation={
	 "sidebar_ui_html":"<div id='planningdss-idot_correlation_panel' class='panel-collapse collapse in'> <div class='panel-body'><div> <ul class='list-group'><div> <p style='color:#0493d3; font-weight: bold ' ><div class='panel panel-default'> <div class='panel-heading'><h5 class='dot_subtitle_txt'>Objectives<button class='btn btn-xs btn-default pull-right' type='button' data-toggle='collapse' data-target='#idot_correlation_choose_scenario'><i class='glyphicon glyphicon-list'></i></button></h5 ></div> <div id='idot_correlation_choose_scenario' class='panel-collapse collapse'> <div class='panel-body'> <form role='form' class='form dot_panel_txt'> <p> <select class='form-control dot_panel_txt ' id='idot_correlation_dropdown'> <option value='null' selected='selected' disabled='disabled'>Select Criteria</option> <option value='sed_ratio_h'>Sedimentation (upstream) </option> <option value='sed_ratio_n'>Total Blockage (upstream) </option> <option value='sed_ratio_n_exp'>Total Blockage (exp) </option>  </select> </p> <p id='idot_correlation_para_container'><input id='idot_correlation_para' 'disabled'='true' type='checkbox' name='idot-route-checkbox' data-size='mini' data-on-text='ON' data-off-text='OFF' > &nbsp; Show Analysis Results</p> <div class='idot_mcda_2nd' style='display: none;'> <p><div id='idot_correlation_sideplot' style='width:190px'></div> </p> <br> <p><input type='button' style='margin-top: 3px;' class='form-control btn btn-primary dot_panel_txt' id='idot_correlation_trees' value='Analysis Algorithm'></p><p><input type='button' style='margin-top: 3px;' class='form-control btn btn-primary dot_panel_txt' id='idot_correlation_scattering_plot_btn' value='Data Distribution'></p><p><select  id='idot_correlation_para_ave' class='form-control dot_panel_txt'> <option value='default' selected='selected' >Original Data</option> <option value='class_average'>Show Average </option> <option value='norm_data'>Normalize Data</option> <option value='landform_mean'>Landform Region Mean</option> </select></p></div> </form> </div></div> <br> <div class='panel-heading'> <h5 class='dot_subtitle_txt'>Analysis Parameter Mapping<button class='btn btn-xs btn-default pull-right' type='button' data-toggle='collapse' data-target='#idot_correlation_factor'><i class='glyphicon glyphicon-list'></i></button></h5 > </div> <div id='idot_correlation_factor' class='panel-collapse collapse'> <div class='panel-body'> <form role='form' class='form'> <p><input type='button' class='wms_trigger form-control btn btn-primary dot_panel_txt' id='culvert_sed-hrlc' value='Landuse'></p> <br> <p><input type='button' class='wms_trigger form-control btn btn-primary dot_panel_txt' id='culvert_sed-forests' value='Forestry'></p> <br> <p><input type='button' class='wms_trigger form-control btn btn-primary dot_panel_txt' id='culvert_hydraulics-runoff_potential' value='Runoff Potential'></p> <br> <p><input type='button' class='wms_trigger form-control btn btn-primary dot_panel_txt' id='culvert_sed-rusle' value='Erosion Potential'></p> <br> <p><input type='button' class='wms_trigger form-control btn btn-primary dot_panel_txt' id='culvert_sed-fullws' value='Full watershed'></p> </form> </div> </div> </div></p></div> </ul> </div></div></div>",
	 "sidebar_ui_title":"<span class='dot_title_txt'>Multi-criteria Decision Analysis <font size='2'><i>(existing culverts)</i></font></span>",
	 "sidebar_ui_html_confined":"<div class='panel-body'> <form role='form' class='form dot_panel_txt'> <p> <select class='form-control dot_panel_txt ' id='idot_correlation_dropdown'> <option value='null' selected='selected' disabled='disabled'>Select Criteria</option> <option value='sed_ratio_h'>Sedimentation (upstream) </option> <option value='sed_ratio_n'>Total Blockage (upstream) </option> <option value='sed_ratio_n_exp'>Total Blockage (exp) </option>  </select> </p> <p id='idot_correlation_para_container'><input id='idot_correlation_para' 'disabled'='true' type='checkbox' name='idot-route-checkbox' data-size='mini' data-on-text='ON' data-off-text='OFF' > &nbsp; Show Analysis Results</p> <div class='idot_mcda_2nd' style='display: none;'> <p><div id='idot_correlation_sideplot' style='width:190px'></div> </p> <br> <p><input type='button' style='margin-top: 3px;' class='form-control btn btn-primary dot_panel_txt' id='idot_correlation_trees' value='Analysis Algorithm'></p><p><input type='button' style='margin-top: 3px;' class='form-control btn btn-primary dot_panel_txt' id='idot_correlation_scattering_plot_btn' value='Data Distribution'></p><p><select  id='idot_correlation_para_ave' class='form-control dot_panel_txt'> <option value='default' selected='selected' >Original Data</option> <option value='class_average'>Show Average </option> <option value='norm_data'>Normalize Data</option> <option value='landform_mean'>Landform Region Mean</option> </select></p></div> </form> </div>",
	  "app_btn_id":"visual_analysis",
	 "app_leaflet_layer":"visual_analysis"
	 //window["script_temp_data"]+"_leaflet_layers",
 }
 
window["idot_correlation_parameter_coverter"] ={				
				"sed_ratio_h_f":"Sedimentation (%)",
				"sed_ratio_n":"Sedimentation degree",
				"stc_n":"Stream/culvert ratio",
				  "sed_area_h":"Sediment area",
				  "stc":"Stream/culvert ratio",
				  "sed_ratio_h":"Sedimentation",
				  "blockage":"Total blockage",
				  "pctcolluvsedcat":"Colluvial sediment",
				  "pcteolcrscat":"Eolian sediment",
				  "pctow2006catrp100":"Open water corridor-cat",
				  "pctconif2006catrp100":"Evergreen forest",
				  "pctow2006wsrp100":"Open water corridor",
				  "pctconif2006wsrp100":"Evergreen forest Corridor",
				  "pctshrb2006wsrp100":"Shrub/scrub",
				  "pctow2006cat":"Open water",
				  "pctbl2011cat":"Barren landcover",				  
				  "total_blockage":"Culvert blockage",
				  "total_blockage_area":"Culvert blockage area",				
				  "stc_sd":"Stream/culvert ratio",				  
				  "pctshrb2006catrp100":"shrub/scrub corridor",
				  "pctgrs2006catrp100":"Grass land corridor",				 
				  "pcthbwet2011cat":"herbaceous wetland",
				  "popden2010ws":"",
				  "angle":"Angle of incidence",
				  "up_local_sinuosity":"Upstream sinuosity",
				  "cur":"Sharp entrance curve",
				  "year_built":"Built year",
				  "culvert_length":"Structure length",
				  "culvert_width":"Structure width", 
				  "immediate_curv":"Upstream curve", 
				  "divergence":"divergence",
				  "upstrea_stru_m":"Upstream structure",
				  "down_local_sinuosity":"Downstream sinuosity",
				  "claycat":"Clay (%)",
				  "sandcat":"Sand (%)",
				  "pctdecid2006wsrp100":"Forest(cat)",
				  "pctconif2006wsrp100": "Evergreen (cat)",  
				  "damdenscat":"Dam density",
				  "pctag2006slp20cat":"Agriculture on slopes 20% (corridor)",
				  "pctimp2006cat":"Mean imperviousness (Cat)",
				  "bfiws":"Baseflow (%)",
				  "runoffws":"Runoff",
				  "q100":"Design discharge (cfs)",
				  "Q100_n":"Design discharge (cfs)",
				  "q200":"200-yr Discharge (cfs)",
				  "q500":"500-yr Discharge (cfs)",
				  "q50":"50-yr Discharge (cfs)",
				  "q25":"25-yr Discharge (cfs)",
				  "q10":"10-yr Discharge (cfs)", 
				  "nhdslope":"Channel slope", 
				  "precipws":"30-yr mean precip (mm)",
				  "culvert_to_stream":"Culvert to Stream Angle (degree)",
				  "pcteolcrsws":"Eolian Sediment",
				  "pctcolluvsedws":"Colluvial Sediment",
				  "waterway_adequacy":"waterway_adequacy",
				  "tree_cd":"Corridor Tree (%)",
				  "tall_tree_cd":"Corridor Forest (%)",
				  "grass_cd":"Corridor Grass (%)",
				  "agc_cd":"Corridor Agr-land (%)",
				  "agland_fullws_perc":"Watershed Agr-land (%)",
				  "grass_fullws_prec":"Watershed Grass (%)",
				  "rusle_mean":"Mean soil loss (local watershed)",  
				  "rusle_majo":"Major soil loss",
				  "ruslesum_fullws_val":"Mean soil loss (full watershed)",
				  "ruslesum_fullws_val":"Sum soil loss (full watershed)",
				  "area_km":"watershed area (km)",			  
						
						'sed_n_id':'culvert_id',
						'culvert_sed-ratio-n-key':'Sediment degree',
						'culvert_stc-n':'SCW ratio',						
						'culvert_sed-ratio-n':'Sediment degree',
						'culvert_sed-ratio-n-key':'Sediment degree',
						'culvert_sed-class-n':'Sed Class',
						'agc_cd_n':'Ag-land(%)',
						'rusle_mean_n':'RUSLE',
						'rusle_sum_n':'RUSLE',
						'sed_ratio_n_max':'Min blockage',
						'sed_ratio_n_min':'Max blockage',
						'sed_n_description':'Culvert description',
						'culvert_sed-n-sus-design':'Sustainable design',
						'culver_id_':'culvert_id',
						'culvert_x':'x',
						'culvert_y':'y',
						'culvert_year-built':'build year',
						'culvert_id':'culvert_id',
						'dbf_file_name':'culvert_id',
						'up2500_100mb_area':'LULC area(%)',
						'up2500_100mb_urban':'Urban land(%)',
						'up2500_100mb_barren':'Barren land(%)',
						'up2500_100mb_ag':'Ag-land(%)',
						'up2500_100mb_ag-n':'Corridor ag-land(%)',
						'up2500_100mb_grass':'Grass land(%)',  
						'up2500_100mb_forest':'Corridor forestry (%)',
						'up2500_100mb_wetland':'Wetland(%)',
						'up2500_100mb_water':'Water(%)',
						'up2500_100mb_decisuous':'Decisuous woods(%)',
						'up2500_100mb_coniferous':'Coniferous woods(%)',
						'up2500_100mb_rusle-count':'RUSLE count',
						'up2500_100mb_rusle-area':'RUSLE area',
						'up2500_100mb_rusle-mean':'RUSLE mean',
						'up2500_100mb_rusle-std':'RUSLE STD',
						'up2500_100mb_rusle-sum':'RUSLE sum',
						'up2500_100mb_rusle-majority':'RUSLE majority',
						'up2500_100mb_rusle-median':'RUSLE median',
						'up2500_100mb_area_km':'area(km)',
						'up2500_100mb_channel-density':'Local channel density(%)',
						'fl_100mb_area':'LULC area',
						'fl_100mb_urban':'Urban land(%)',
						'fl_100mb_barren':'Barren land(%)',  
						'fl_100mb_ag':'Ag-land(%)',
						'fl_100mb_grass':'Grass land(%)',
						'fl_100mb_forest':'Forestry (%)',
						'fl_100mb_wetland':'Wetland(%)',
						'fl_100mb_water':'Water(%)',
						'fl_100mb_decisuous':'Decisuous woods(%)',
						'fl_100mb_coniferous':'Coniferous woods(%)',
						'fl_100mb_rusle-count':'RUSLE counts',
						'fl_100mb_rusle-area':'RUSLE area',
						'fl_100mb_rusle-mean':'RUSLE mean',
						'fl_100mb_rusle-majority':'RUSLE majority',
						'fl_100mb_rusle-median':'RUSLE median',
						'fl_100mb_rusle-std':'RUSLE STD',
						'fl_100mb_rusle-sum':'RUSLE sum',
						'fl_100mb_area_km':'area(km)',
						'fl_100mb_channel-density':'Full channel density(%)',
						'up2500_500mb_forest':'Forestry (%)',
						'fl_ws_culvert-id':'Culvert ID',
						'fl_ws_area-acre':'Watershed area(ac)',
						'fl_ws_area-km':'Watershed area(km)',
						'fl_ws_rusle-count':'RUSLE cell',
						'fl_ws_rusle-area':'RUSLE area',
						'fl_ws_rusle-mean':'RUSLE mean',
						'fl_ws_rusle-std':'RUSLE STD',
						'fl_ws_rusle-sum':'RUSLE sum',
						'fl_ws_rusle-majority':'RUSLE majority',
						'fl_ws_rusle-median':'RUSLE median',
						'fl_ws_area':'LULC area',
						'fl_ws_urban':'Urban land (%)',
						'fl_ws_barren':'Barren land (%)',
						'fl_ws_ag':'Ag land (%)',
						'up2500_100mb_ag_n':'Ag land (%)',						
						'fl_ws_grass':'Grass (%)',						
						'fl_ws_forest':'Forestry (%)',
						'up2500_100mb_forest':'Forestry (%)',
						'fl_ws_wetland':'Wetland (%)',
						'fl_ws_water':'Water (%)',
						'fl_ws_decisuous':'Decisuous woods(%)',
						'fl_ws_coniferous':'Coniferous woods(%)',
						'culvert_id':'culvert_id',
						'slope_full':'Full channel slope',
						'upstream_length_full':'Full channel length',
						'slope_local':'Local channel slope',
						'slope_1km_upstream':'Channel slope (1km upstream)',
						'slope_5km_upstream':'Channel slope (2km upstream)',
						'error':'error notes',
						'fl_100mb_lsfactor-mean':'LS factor',
						'fl_100mb_kfactor-mean':'Soil erodibility',		
						'up2500_500mb_channel-density':'Channel density',
						'Q500_n':'Design discharge (cfs)',
						'Q100_n':'Design discharge (cfs)',
						'Q200_n':'Design discharge (cfs)',
						'landform_region':'Landform regions',						
						'fl_ws_channel_density':'Drainage density',
						'sinuosity': 'Stream sinuosity',
						"stream_width": 'Stream width (m)',	
						'cluster_id':'Clusters'
			};
							
			
			// pcteolcrsws  pctcolluvsedws
			
var pcpdata = []; 

$("#sidebar").css('width', '270px');
loading_sidebar( dss_app_settings_idot_correlation);
$("[name='idot-route-checkbox']").bootstrapSwitch(); 



		var DSS_idot_correlation_styles ={	

		"surveyed_culvert":{
		"default":{	radius: 12,	fillColor: "#ff0000",color: "#ff0000 ",weight: 1,opacity: 0.01,	fillOpacity: 0.01},
		"hover":{radius: 12,weight: 1,	opacity: 1,	fillOpacity: 0.01},
		"default_invisible":{	radius: 4,	fill: false , stroke:false , fillColor: "#FF99FF",color: "#000 ",weight: 1,	opacity: 1,	fillOpacity: 1},
		"find_usgs_streamflow_highlight":{radius: 5,	fillColor: "#FFFF00 ",	color: "#FF0000 ",	weight: 2,	opacity: 1,	fillOpacity: 1         },
		"visible":{	fill: true , stroke:true , },
		"invisible":{	fill: false , stroke:false, weight: 5,radius: 4,opacity: 1 },
		},
		"sub_basin":{
		"default":{	weight: 2, opacity: 1, color: 'white',  dashArray: '3',  fillOpacity: 0.3,stroke:true,	fill:true},	
		"default_invisible":{	stroke:false,fill:false	},	
		},
		};

		var DSS_correlation_layer_features={
		"surveyed_culvert_sens":{
		"default_style":DSS_idot_correlation_styles.surveyed_culvert["invisible"],
		"default_layer":"yes",
		"geometery_type":"circular_marker",
		"layer_group":dss_app_settings_idot_correlation["app_leaflet_layer"],
		//"bringtofront":"yes",
		"url":"assets-examples/js/new_culvert_analysis.json",
		"onEachFeature":function (feature, layer){

		}
		},
		"surveyed_culvert_sens_2":{
		"default_style":DSS_idot_correlation_styles.surveyed_culvert["invisible"],
		"default_layer":"yes",
		"geometery_type":"circular_marker",
		"layer_group":dss_app_settings_idot_correlation["app_leaflet_layer"], 
		//"bringtofront":"yes",
		"url":'assets-examples/data/new_data_417sites.json',
		//"url":"assets/php/iowa_culvert/real_time_survey_data.php?type=get_result",  
		"onEachFeature":function (feature, layer){
			$("#idot_correlation_dropdown").prop("disabled", false); 
		}
		},

		"surveyed_culvert_ws_full":{
		"default_style":DSS_idot_correlation_styles.surveyed_culvert["invisible"],
		"default_layer":"no",
		"geometery_type":"regular",
		"layer_group":dss_app_settings_idot_correlation["app_leaflet_layer"], 
		//"bringtofront":"yes",
		"url":'data/dss/IDOT/state_data/geo_json/culvert_surveyed/full_shp_rusle_lulc.json',
		//"url":"assets/php/iowa_culvert/real_time_survey_data.php?type=get_result",  
		"onEachFeature":function (feature, layer){ 
			$("#idot_correlation_dropdown").prop("disabled", false); 			
		}
		},
		//----corridor--layer
		

};// end of feature layer object

//leaflet_map_control.Layer_initialization(map,DSS_correlation_layer_features["surveyed_culvert_ws_full"]);
//leaflet_map_control.Layer_initialization(map,DSS_correlation_layer_features["full_lc_layer"]); 
//

	var corridor_layers={	
			"lc_layer":{ 
				"default_style":{  fill:true,stroke:"#ff9933",weight: 1,opacity: 0.6,color: '#ff9933',fillOpacity: 0.1},
				"default_layer":"load_not_add", //load_not_add yes  no
				"geometery_type":"regular",
				"layer_group":dss_app_settings_idot_correlation["app_leaflet_layer"], 
				//"bringtofront":"yes",
				"url":'assets-examples/js/culvert_upstream_lc_corridor.json', 
				//"url":"assets/php/iowa_culvert/real_time_survey_data.php?type=get_result",  
				"onEachFeature":function (feature, layer){
					$("#idot_correlation_dropdown").prop("disabled", false); 			
				}
			},
			"full_corridor_layer":{ 
				"default_style":{  fill:true,stroke:"#F80303",weight: 1,opacity: 0.5,color: '#F80303',fillOpacity: 0.05},
				"default_layer":"load_not_add", //load_not_add yes  no
				"geometery_type":"regular",
				"layer_group":dss_app_settings_idot_correlation["app_leaflet_layer"], 
				//"bringtofront":"yes",
				"url":'assets-examples/js/culvert_upstream_full_corridor.json', 
				//"url":"assets/php/iowa_culvert/real_time_survey_data.php?type=get_result",  
				"onEachFeature":function (feature, layer){
					$("#idot_correlation_dropdown").prop("disabled", false); 			
				}
			},
			"full_watershed_layer":{ 
				"default_style":{  fill:true,stroke:"#ffff99",weight: 1,opacity: 0.5,color: '#ffff99',fillOpacity: 0.05},
				"default_layer":"load_not_add", //load_not_add yes  no
				"geometery_type":"regular",
				"layer_group":dss_app_settings_idot_correlation["app_leaflet_layer"], 
				//"bringtofront":"yes",
				"url":'assets-examples/js/culvert_upstream_full_watershed.json', 
				//"url":"assets/php/iowa_culvert/real_time_survey_data.php?type=get_result",  
				"onEachFeature":function (feature, layer){
					$("#idot_correlation_dropdown").prop("disabled", false); 			
				}
			},
			"lc_corridor_layer_500":{ 
				"default_style":{  fill:true,stroke:"#66ff33",weight: 1,opacity: 0.5,color: '#66ff33',fillOpacity: 0.05},
				"default_layer":"load_not_add", //load_not_add yes  no
				"geometery_type":"regular",
				"layer_group":dss_app_settings_idot_correlation["app_leaflet_layer"], 
				//"bringtofront":"yes",
				"url":'assets-examples/js/culvert_upstream_lc_corridor_500.json', 
				//"url":"assets/php/iowa_culvert/real_time_survey_data.php?type=get_result",  
				"onEachFeature":function (feature, layer){
					$("#idot_correlation_dropdown").prop("disabled", false); 			
				}
			},
			"landforms":{ 
				
					"default_style":{  fill:false,stroke:"#ff9933",weight: 3,opacity: 1,color: '#ff9933',fillOpacity: 0.1},
					"default_layer":"load_not_add", //load_not_add yes  no
					"geometery_type":"regular",
					"layer_group":dss_app_settings_idot_correlation["app_leaflet_layer"], 
					//"bringtofront":"yes",
					"url":'assets-examples/js/culvert_upstream_landform.json ',      
					//"url":"assets/php/iowa_culvert/real_time_survey_data.php?type=get_result",  
					"onEachFeature":function (feature, layer){
						color_coding_landform(layer,feature);
							
					}
				}
			//
	};// end of feature layer object
	
	
	
	$('#culvert_sed-landforms').click(function() { 
		setTimeout(function(){	 }, 1000); 
	});	
	function color_coding_landform(layer,feature){ 
		var region_name=feature.properties['LANDFORM_R'];
		var region_color={
			"Southern Iowa Drift Plain":"#E9FF63",
			"Iowa-Cedar Lowland":"#7DFF63",
			"Mississippi River Alluvial Plain":"#63F8FF",
			"Missouri River Alluvial Plain":"#99FF63",			
			"Des Moines Lobe":"#41a9f4",
			"East-Central Iowa Drift Plain":"#FFC263",
			"Iowan Surface":"#ac41f4",
			"Loess Hills":"#FF8E63",
			"Northwest Iowa Plains":"#FF6464",
			"Paleozoic Plateau":"#FF7563"		
		};
		layer.setStyle(	{"color":region_color[region_name]});
	}
	
	leaflet_map_control.Layer_initialization(map,corridor_layers);
	
	

$("#idot_correlation_dropdown").prop("disabled", true);

var HRLC_landuse_full = L.tileLayer.wms("http://s-iihr32.iihr.uiowa.edu:8080/geoserver/Iowa_Watershed/wms", 
						{layers: 'Iowa_Watershed:hrlc_2009_3m1', format: 'image/gif', version: '1.1.0', transparent: true, srs:32615, attribution: "", tiled:true, styles:"HRLC_landuse_forest_grass_ag_urban" })

var culvert_mcda_mws={
	"HRLC_landuse_full":L.tileLayer.wms("http://s-iihr32.iihr.uiowa.edu:8080/geoserver/Iowa_Watershed/wms", 
						{layers: 'Iowa_Watershed:hrlc_2009_3m1', format: 'image/gif', version: '1.1.0', transparent: true, srs:32615, attribution: "", tiled:true, styles:"HRLC_landuse_forest_grass_ag_urban" }),
	"RUSLE_ls_factor":L.tileLayer.wms("http://s-iihr32.iihr.uiowa.edu:8080/geoserver/Iowa_Watershed/wms", 
                        {layers: 'huc_12_rusle_26915', format: 'image/gif', version: '1.1.0', transparent: true, srs:26915, attribution: "", tiled:true, styles:"huc_12_rusle_26915_ls_factor" }),
	"RUSLE_k_factor":L.tileLayer.wms("http://s-iihr32.iihr.uiowa.edu:8080/geoserver/Iowa_Watershed/wms", 
                        {layers: 'huc_12_rusle_26915', format: 'image/gif', version: '1.1.0', transparent: true, srs:26915, attribution: "", tiled:true, styles:" huc_12_rusle_26915_k_factor" })	
}				

			//culvert_mcda_mws['RUSLE_ls_factor']
			//culvert_mcda_mws['RUSLE_k_factor']		
						
leaflet_map_control.Layer_initialization(map,DSS_correlation_layer_features);
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_hydraulics-runoff_potential","layer":[DSS_culvert_wms["SSURGO_HydroSoil"]],"new_btn_text":"Runoff Potential (Turn Off)","legend":[[["Low",'#ffebd6'],["Med",'#eba988'],["High",'#d65d45'],["Very high",'#c40a0a']],"<p>Runoff Potential</p><p></p>",'','']}); 
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_sed-rusle","layer":[DSS_culvert_wms["RESUL"]],"new_btn_text":"Erosion Potential (Turn Off)"});
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_sed-forests","layer":[DSS_culvert_wms["HRLC"]],"new_btn_text":"Forestry (Turn Off)","legend":[[["Coniferous Forest",'#99ff33'],["Deciduous Short",'#00ff00'],["Deciduous Medium",'#33cc33'],["Deciduous Tall",'#009900']],"<p>Forestry Map</p><p></p>",{"type":"discrete"},'']});
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_sed-hrlc","layer":[HRLC_landuse_full],"new_btn_text":"Landuse (Turn Off)","legend":[[["Water",'#00ccff'],["Wetland",'#66ffcc'],["Forest",'#307800'],["Grass",'#99ff99'],["Hay",'#ffeb99'],["Corn",'#ffe066'],["Soybeans",'#ffcc00'],["Urban",'#666699']],"<p>Forestry Map</p><p></p>",{"type":"discrete"},'']});
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_sed-fullws","layer":[HRLC_landuse_full],"new_btn_text":"Landuse (Turn Off)"});
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_corridor_lc","layer":[window['visual_analysis']['lc_layer']],"new_btn_text":"Local Corridor (Turn Off)"});
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_corridor_full","layer":[window['visual_analysis']['full_corridor_layer']],"new_btn_text":"Full Corridor (Turn Off)"});
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_watershed_full","layer":[window['visual_analysis']['full_watershed_layer']],"new_btn_text":"Full Watershed (Turn Off)"});
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_corridor_lc_500","layer":[window['visual_analysis']['lc_corridor_layer_500']],"new_btn_text":"Full Watershed (Turn Off)"});  
leaflet_map_control.show_leaflet_layer({"button_id":"culvert_sed-landforms","layer":[window['visual_analysis']['landforms']],"new_btn_text":"Landforms (Turn Off)"});	
	
 leaflet_map_control.show_leaflet_layer({"button_id":"culvert_sed-rusle_ls","layer":[culvert_mcda_mws['RUSLE_ls_factor']],"new_btn_text":"RUSLE Slope-length (Turn Off)"});	
 leaflet_map_control.show_leaflet_layer({"button_id":"culvert_sed-rusle_k","layer":[culvert_mcda_mws['RUSLE_k_factor']],"new_btn_text":"RUSLE Soil Erodibility(Turn Off)"});	 


function idot_correlation_dropdown(action_type,render_doms){
		 /* render_doms{ 'scatter'=false,'map'=false,'pie'=false   } */
		var actions={		
				//var options={"attNames":["sed_ratio_h","stc","built_year","culvert_length","rusle_mean","up_local_sinuosity","rusle_majo","divergence","immediate_curv","upstrea_stru_m","down_local_sinuosity","pctgrs2006catrp100"],	
			"sed_ratio_h":function(){	
				var options={
					"attNames":["sed_ratio_h","stc","culvert_to_stream","nhdslope","q100","claycat","rusle_mean","agc_cd","grass_cd","tall_tree_cd"], 	   
					//"attNames":["sed_ratio_h","stc","rusle_mean","rusle_majo","pctimp2006cat","pctag2006slp20cat","damdenscat"],	
					//tree_cd  tall_tree_cd  grass_cd  agc_cd 
					"paracor_title":{} 					
				}; 
				$("#idot_correlation_para").bootstrapSwitch('disabled',false);
				
				point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_full"]["json"],value,"display_bars",options,render_doms); 
			},
			"sed_ratio_n_exp":function(){	//not in use
				var options={
					"attNames":["sed_ratio_n","stc_n","area_km","rusle_mean","ruslemean_fullws_val","ruslesum_fullws_val","agland_fullws_perc","agc_cd","grass_fullws_prec","grass_cd","tall_tree_cd"],  	   				
					"paracor_title":{},
					"key":"sed_ratio_n",		
				}; 
				$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
				point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_full"]["json"],"sed_ratio_n","display_bars",options,render_doms); 
			},	
			"sed_ratio_n":function(){	// in use    
				var options={
					"attNames":["sed_ratio_n","stc_n","area_km","nhdslope","q100","claycat","rusle_mean","agc_cd","grass_cd","tall_tree_cd"],  	   				
					"paracor_title":{},
					"key":"sed_ratio_n",		
				}; 
				$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
				point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_full"]["json"],"sed_ratio_n","display_bars",options,render_doms); 
			
			},
			
			"null":function(){  //not in use
				point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_full"]["json"],"","hide_bars"); 
				$("#idot_correlation_para").bootstrapSwitch('disabled',true);
				
			},
			//-----------------new sensitivity analysis-----------------
					"test1":function(){	// in use    
						var options={
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','up2500_100mb_wetland'],  	   				
							"paracor_title":{},
							"key":"culvert_sed-ratio-n-key",		
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_sens"]["json"],"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					},
					"up2500_100mb":function(){	// in use     up2500_100mb_channel-density
						var options={
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','up2500_100mb_area_km','up2500_100mb_urban','up2500_100mb_ag-m','up2500_100mb_forest','up2500_100mb_coniferous','up2500_100mb_grass-m','up2500_100mb_rusle-mean','up2500_100mb_rusle-sum','up2500_100mb_water','landform_region'],  	   				
							// up2500_100mb_ag
							"paracor_title":{},
							"key":"culvert_sed-ratio-n-key",		
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_sens"]["json"],"culvert_sed-ratio-n-key","display_bars",options,render_doms); 		
					
					},
					"up2500_500mb":function(){	// in use     
						var options={
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','up2500_500mb_channel-density','up2500_500mb_urban','up2500_500mb_ag','up2500_500mb_forest','up2500_500mb_coniferous','up2500_500mb_grass','up2500_500mb_rusle-mean','up2500_500mb_rusle-sum','up2500_500mb_water','landform_region'],  	   				
							// up2500_100mb_ag
							"paracor_title":{},
							"key":"culvert_sed-ratio-n-key",		
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_sens"]["json"],"culvert_sed-ratio-n-key","display_bars",options,render_doms); 		
					
					},
					"fl_100mb":function(){	// in use    
						var options={
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','fl_100mb_channel-density','fl_100mb_urban','fl_100mb_ag-m','fl_100mb_forest','fl_100mb_coniferous','fl_100mb_grass-m','fl_100mb_rusle-mean','fl_100mb_rusle-sum','fl_100mb_water','landform_region'],   	   				
							"paracor_title":{},
							"key":"culvert_sed-ratio-n-key",		
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_sens"]["json"],"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					},	//
					"fl_ws":function(){	// in use    
						var options={  //
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_area-km','fl_ws_urban','fl_ws_ag','fl_ws_forest','fl_100mb_coniferous','fl_ws_grass','fl_ws_rusle-mean','fl_ws_rusle-sum','fl_ws_water','landform_region'],  	   				
							"paracor_title":{},
							"key":"culvert_sed-ratio-n-key",	
							//up2500_100mb_grass  fl_100mb_grass  fl_ws_grass		//fl_100mb_barren  up2500_100mb_barren fl_ws_barren			
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_sens"]["json"],"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					},
					"best_selection":function(){	// in use    
						var options={  //
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','up2500_100mb_ag-n','up2500_100mb_forest','fl_ws_grass','up2500_500mb_channel-density','Q500_n','fl_100mb_lsfactor-mean','landform_region'],    	   				
							"paracor_title":{}, 
							"key":"culvert_sed-ratio-n-key",	//, fl_100mb_kfactor-mean  fl_100mb_lsfactor-mean
							//up2500_100mb_grass  fl_100mb_grass  fl_ws_grass		//fl_100mb_barren  up2500_100mb_barren fl_ws_barren		 'up2500_500mb_forest',	  fl_100mb_coniferous
							//'culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_area-km','up2500_100mb_ag','up2500_100mb_forest','fl_ws_grass','claycat','Q500_n','fl_100mb_lsfactor-mean'
							
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						point_bar_visualization(DSS_correlation_layer_features["surveyed_culvert_sens"]["json"],"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					},
					"feature_selection":function(){	// not in use    
						var options={  //
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_ag','up2500_100mb_forest','fl_ws_grass','up2500_500mb_channel-density','Q500_n','fl_100mb_lsfactor-mean','landform_region'],    	   				
							"paracor_title":{}, 
							"key":"culvert_sed-ratio-n-key",	//, fl_100mb_kfactor-mean  fl_100mb_lsfactor-mean
							//up2500_100mb_grass  fl_100mb_grass  fl_ws_grass		//fl_100mb_barren  up2500_100mb_barren fl_ws_barren		 'up2500_500mb_forest',	  fl_100mb_coniferous
							//'culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_area-km','up2500_100mb_ag','up2500_100mb_forest','fl_ws_grass','claycat','Q500_n','fl_100mb_lsfactor-mean'
							
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						
						$.getJSON( "assets-examples/js/new_culvert_analysis.json", function( data ) {
							point_bar_visualization(data,"culvert_sed-ratio-n-key","display_bars",options,render_doms);  
					
						});
					},		//surveyed_culvert_sens_2
					"feature_selection_full_watershed":function(){	// in use    
						var options={  //
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_ag','up2500_100mb_forest','fl_ws_grass','Q500_n','landform_region'],    	   				
							"paracor_title":{},  
							"key":"culvert_sed-ratio-n-key",	//, fl_100mb_kfactor-mean  fl_100mb_lsfactor-mean
							//up2500_100mb_grass  fl_100mb_grass  fl_ws_grass		//fl_100mb_barren  up2500_100mb_barren fl_ws_barren		 'up2500_500mb_forest',	  fl_100mb_coniferous
							//'culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_area-km','up2500_100mb_ag','up2500_100mb_forest','fl_ws_grass','claycat','Q500_n','fl_100mb_lsfactor-mean'
							
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						
						$.getJSON( "assets-examples/data/new_data_417sites.json", function( data ) {
							console.log(data); 
							console.log("console_data"); 
							point_bar_visualization(data,"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					
						});
					},
					
					"feature_selection_full_stream":function(){	// in use    
						var options={  //
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','upstream_length_full','','up2500_500mb_channel_density','sinuosity',"stream_width",'fl_100mb_lsfactor-mean','landform_region'],    	   				
							"paracor_title":{},  
							"key":"culvert_sed-ratio-n-key",	
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						
						$.getJSON( "assets-examples/data/new_data_417sites.json", function( data ) {
							console.log(data); 
							console.log("console_data"); 
							point_bar_visualization(data,"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					
						});
					},
					"feature_selection_full_urban":function(){	// in use    
						var options={  //
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_urban','fl_100mb_urban','fl_ws_barren','fl_100mb_barren','fl_ws_forest','fl_100mb_forest','Q100_n','landform_region'],    	   				
							"paracor_title":{},  
							"key":"culvert_sed-ratio-n-key",	
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						
						$.getJSON( "assets-examples/data/new_data_417sites.json", function( data ) {
							console.log(data); 
							console.log("console_data"); 
							point_bar_visualization(data,"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					
						});
					},//'fl_100mb_area_km','up2500_500mb_area_km','up2500_100mb_area_km'
					"feature_selection_full_area":function(){	// in use    
						var options={  ////slope_full		slope_local	slope_1km_upstream	slope_5km_upstream

							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_area_km','fl_100mb_area_km','up2500_500mb_area_km','up2500_100mb_area_km','landform_region'],    	   				
							"paracor_title":{},  
							"key":"culvert_sed-ratio-n-key",	
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						
						$.getJSON( "assets-examples/data/new_data_417sites.json", function( data ) {
							console.log(data); 
							console.log("console_data"); 
							point_bar_visualization(data,"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					
						});
					},
					
					"feature_selection_full_slope":function(){	// in use    
						var options={  ////slope_full		slope_local	slope_1km_upstream	slope_5km_upstream

							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','upstream_length_full','slope_full','slope_local','slope_1km_upstream','slope_5km_upstream','landform_region'],    	   				
							"paracor_title":{},  
							"key":"culvert_sed-ratio-n-key",	
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						
						$.getJSON( "assets-examples/data/new_data_417sites.json", function( data ) {
							console.log(data); 
							console.log("console_data"); 
							point_bar_visualization(data,"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					
						});
					},
						
					
					"feature_selection_full":function(){	// in use     
						var options={  //
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_ag','fl_100mb_forest','fl_ws_grass','sinuosity',"stream_width",'Q500_n','fl_100mb_lsfactor-mean','landform_region'],    	   				
							"paracor_title":{},   
							"key":"culvert_sed-ratio-n-key",	//, fl_100mb_kfactor-mean  fl_100mb_lsfactor-mean
							//up2500_100mb_grass  fl_100mb_grass  fl_ws_grass		//fl_100mb_barren  up2500_100mb_barren fl_ws_barren		 'up2500_500mb_forest',	  fl_100mb_coniferous
							//'culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_area-km','up2500_100mb_ag','up2500_100mb_forest','fl_ws_grass','claycat','Q500_n','fl_100mb_lsfactor-mean'
							
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						
						$.getJSON( "assets-examples/data/new_data_417sites.json", function( data ) {
							console.log(data); 
							console.log("console_data"); 
							point_bar_visualization(data,"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					
						});
					},
					"feature_selection2_full":function(){	// in use     
						var options={  //
							"attNames":['culvert_sed-ratio-n-key','culvert_stc-n','up2500_100mb_ag_n','up2500_100mb_forest',"fl_ws_area_m",'sinuosity','stream_width','q500','fl_100mb_lsfactor-mean','landform_region'],    	   				
							"paracor_title":{},   
							"key":"culvert_sed-ratio-n-key",	//, fl_100mb_kfactor-mean  fl_100mb_lsfactor-mean
							//up2500_100mb_grass  fl_100mb_grass  fl_ws_grass		//fl_100mb_barren  up2500_100mb_barren fl_ws_barren		 'up2500_500mb_forest',	  fl_100mb_coniferous
							//'culvert_sed-ratio-n-key','culvert_stc-n','fl_ws_area-km','up2500_100mb_ag','up2500_100mb_forest','fl_ws_grass','claycat','Q500_n','fl_100mb_lsfactor-mean'
							
						}; 
						$("#idot_correlation_para").bootstrapSwitch('disabled',false);				
						
						$.getJSON( "assets-examples/data/new_data_417sites.json", function( data ) {
							console.log(data); 
							console.log("console_data"); 
							point_bar_visualization(data,"culvert_sed-ratio-n-key","display_bars",options,render_doms); 
					
						});
					}
					
		};
		
		$("#idot_correlation_dropdown").unbind();
		$("#idot_correlation_dropdown").on('change', function() {
			var value=this.value;  //set initial value
			console.log(value);
			$(".idot_correlation_panel").remove();
			//$('#idot_correlation_para').bootstrapSwitch('setState', false);
			//$(".parcoords").remove();
			
			try { 		
				if($('#idot_correlation_para').bootstrapSwitch('state')==false){
					$('#idot_correlation_para').bootstrapSwitch('setState', false);
				}		
			}
			catch(err) {			
			}
			
			console.log("?");
			actions[this.value]();		
	});
	typeof(action_type)!='undefined' ? actions[action_type]() : console.log("no pre-defined display");
	
}



 


//function for watershed search
function idot_correlation_ifis_trace(layer,feature,style){
	layer.on('mouseover', function (e) {
		var lng = feature.geometry.coordinates[0];
		var lat = feature.geometry.coordinates[1];
	  ifis_ws_search(map,style,lat, lng, 90,"fix","9x9"); 

	});
	
	layer.on('mouseout', function (e) {
		window["ifis_search_result"].clearLayers();

	});	
//instant_watershed(e.latlng.lat,e.latlng.lng,500,"");
}



//this is a leaflet function
function GEN_change_layer_style_externally(input_layer,style_obj){   
var obj=input_layer["_layers"];
for(var key in obj) {   
  obj[key].setStyle(style_obj);
}
}
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------*/




function point_bar_visualization(collection,scenario_name,display_setting,options,render_doms_input){	
        
		var render_doms = render_doms_input || {};		
		console.log("ss1");
		var dss_panel_holder_id= dss_app_settings_idot_correlation["app_btn_id"]+"_panel";		
		var frame_class=dss_panel_holder_id+"frame_bar"; 
		var value_class=dss_panel_holder_id+"value_bar"; 
		
		
		if(display_setting=="hide_bars"){
				$( "."+frame_class ).remove();
				$( "."+value_class ).remove();
				//$( "."+dss_panel_holder_id ).hide();
				return false;				
		}		
		//layer.setstyle(DSS_idot_correlation_styles .usgs_streamflow['default_invisible']); //map.removeLayer(usgs_streamflow_loaction);
		$( "."+frame_class ).remove();
		$( "."+value_class ).remove();		
		var value_percentage_name=scenario_name;
		var total_bar_height=30;
		// d3.json(datalink, function(collection) {  //import data from other sources
		  // Add a LatLng object to each item in the dataset		  	
		//var collection=input_json;	       
			//console.log(value_percentage_name);
			//console.log(collection.features || collection);
		
		var recolorMap = colorScale(collection.features,value_percentage_name); /* if this code doesn't work, might be the color code hash value not defined*/
		/* if this code doesn't work, console show:   TypeError: t is undefined[Learn More]d3.min.js:2:25624 , go to color hash table add the parameter key */
		
		var key;		
		if(options.hasOwnProperty("key")){
			key=options["key"];
		}else{
			key= "sed_ratio_h"; //used for each geom id
		}	 
			//add Iowa regions geometry to map
			var transform = d3.geo.transform({point: projectPoint}),
			path = d3.geo.path().projection(transform);			
		var max_y_axis_val=0;
		collection.features.forEach(function(d) {	
		      d.LatLng = new L.LatLng(d.geometry.coordinates[1],
			  d.geometry.coordinates[0])	
			  if(d.properties[value_percentage_name]>max_y_axis_val){
				  max_y_axis_val=d.properties[value_percentage_name];
			  }
			  
		  })
		
		console.log("22")
		
		var collection2= jQuery.extend(true, {}, collection);  // must copy like this
		var collection3= jQuery.extend(true, {}, collection);  // must copy like this
		var collection4= jQuery.extend(true, {}, collection);  // must copy like this
		attNames=options["attNames"];
		console.log(attNames);
		paracor_title=["paracor_title"];
		
		//prepare parallel coordinate data and plots
		var parced_data=paracoord_data_preparation(collection2,attNames,paracor_title,scenario_name); //data prepatation 	
		window["idot_correlation_data"]["full_data_for_som"]=parced_data; //parepare the full data for later reverse normlization
		
		paracoord(parced_data,attNames,paracor_title,scenario_name,key,render_doms);		
		idot_data_preparation_scattering_plot(collection4,scenario_name, jQuery.extend(true, {},attNames),render_doms); 
				
		
		
		
		//below starts to draw bar data on the map
				//var value,bar;
				
				
				console.log(render_doms['map']+"  "+render_doms['map']!=false);
				if(render_doms['map']!=false){					
					console.log("map_s");					
					dot_representation();			
						
						function dot_representation(){
							if(window.hasOwnProperty("d3_circular_culvert") ){
					
							}else{
							
								window['d3_circular_culvert']="";
							}
							
							var svg = d3.select("#map").select("svg");	
							/*var g_circule_culvert = svg.append("g").attr("class", value_class+" function_panel leaflet-zoom-hide "+dss_panel_holder_id);		
							let transform=d3.geo.transform({point: projectPoint}),
							path = d3.geo.path().projection(transform);
							 
							d3_circular_culvert = g_circule_culvert.selectAll(".regions")
							.data(collection.features)
							.enter().append("path")
							//.attr("class", "regions") //assign class for styling
							.attr("id", function(d) {
							return "id"+d.properties[key]})
							  .attr("d", path) //project data as geometry in svg
							  .style("fill", function(d) { //color enumeration units
								 return choropleth(d, recolorMap,value_percentage_name);
							  })
							  .on("mouseover", function(d){
								ifis_ws_search(map,{fill:false,stroke:"#F80303",weight: 2,opacity: 0.6,	color: '#F80303',fillOpacity: 0.1},d["geometry"]["coordinates"][1],d["geometry"]["coordinates"][0],90,"no_fit","9x9","full_ws"); 
							
							});*/
							var g_circule_culvert = svg.append("g").attr("class", value_class+" function_panel leaflet-zoom-hide "+dss_panel_holder_id);		
							let transform=d3.geo.transform({point: projectPoint}),
							path = d3.geo.path().projection(transform);
							 
							 
							d3_circular_culvert = g_circule_culvert.selectAll("circle")
							.data(collection.features)
							.enter().append("circle")
							.attr("r", 6)
							//.attr("class", "regions") //assign class for styling
								.attr("id", function(d) {
								return "id"+d.properties[key]})
							  //.attr("d", path) //project data as geometry in svg
							  .style("fill", function(d) { //color enumeration units
								 return choropleth(d, recolorMap,value_percentage_name);
							  })
							  .on("mouseover", function(d){
								ifis_ws_search(map,{fill:false,stroke:"#F80303",weight: 2,opacity: 0.6,	color: '#F80303',fillOpacity: 0.1},d["geometry"]["coordinates"][1],d["geometry"]["coordinates"][0],90,"no_fit","9x9","full_ws"); 
							
							}).on("mouseout", function(d){
								window["ifis_search_result"].clearLayers();
							}).on("click", function(d){
								var data_for_pcp_highlight = paracoord_data_preparation([d],attNames,paracor_title,scenario_name);							
								console.log(data_for_pcp_highlight[0]);  
								for(var each in window["idot_correlation_data"]["pcp"]){							
									//window["idot_correlation_data"]["pcp"][each].dehighlight();								
									window["idot_correlation_data"]["pcp"][each].highlight([data_for_pcp_highlight[0]]);								
								}
								console.log(d["properties"]["culvert_id"]);
								//alert(d["properties"]["culvert_id"]);
								
							}).on("dblclick", function(d){
								var data_for_pcp_highlight = paracoord_data_preparation([d],attNames,paracor_title,scenario_name);							
								console.log(data_for_pcp_highlight[0]);  
								for(var each in window["idot_correlation_data"]["pcp"]){							
									//window["idot_correlation_data"]["pcp"][each].dehighlight();								
									window["idot_correlation_data"]["pcp"][each].highlight([data_for_pcp_highlight[0]]);								
								}
								console.log(d["properties"]["culvert_id"]);
								//alert(d["properties"]["culvert_id"]);
								window.open("../../../culvert/IowaWS/iowa_culvert.html?project=IDOT&ws_route=state&culvert_id="+d["properties"]["culvert_id"].replace("#", ""), "blanks");
								window.open("../../../culvert/IowaWS/culvert_time_series/index.html?id="+d["properties"]["culvert_id"].replace("#", ""), "blanks");
							});
							
							
						}
						function bar_representation(){
							if(window.hasOwnProperty("value") && window.hasOwnProperty("bar")){
					
							}else{
								window['value']="";
								window['bar']="";							
							}
							var svg = d3.select("#map").select("svg");		
							var g_frame = svg.append("g").attr("class", frame_class+" function_panel leaflet-zoom-hide "+dss_panel_holder_id);
							var g_value = svg.append("g").attr("class", value_class+" function_panel leaflet-zoom-hide "+dss_panel_holder_id);		
							
							bar = g_frame.selectAll("rect")
						   .data(collection.features)
						   .enter().append("rect")
						   .attr("id", function(d) {
								return "frame_"+d.properties[key]})			
						   .attr("width",5)
						   .attr("height",total_bar_height)		  
						   .attr("fill","white")	   
						   .attr("stroke-width", 1)
						   .on("click", function(d){
								var data_for_pcp_highlight = paracoord_data_preparation([d],attNames,paracor_title,scenario_name);							
								console.log(data_for_pcp_highlight[0]);  
								for(var each in window["idot_correlation_data"]["pcp"]){							
									//window["idot_correlation_data"]["pcp"][each].dehighlight();								
									window["idot_correlation_data"]["pcp"][each].highlight([data_for_pcp_highlight[0]]);								
								}
								console.log(d["properties"]["culvert_id"]);
							})
							.on("mouseover", function(d){							
								ifis_ws_search(map,{fill:false,stroke:"#F80303",weight: 2,opacity: 0.6,	color: '#F80303',fillOpacity: 0.1},d["geometry"]["coordinates"][1],d["geometry"]["coordinates"][0],90,"no_fit","9x9","full_ws"); 
							
							}).on("mouseout", function(d){
								window["ifis_search_result"].clearLayers();
							}).on("click", function(d){
								var data_for_pcp_highlight = paracoord_data_preparation([d],attNames,paracor_title,scenario_name);							
								console.log(data_for_pcp_highlight[0]);  
								for(var each in window["idot_correlation_data"]["pcp"]){							
									//window["idot_correlation_data"]["pcp"][each].dehighlight();								
									window["idot_correlation_data"]["pcp"][each].highlight([data_for_pcp_highlight[0]]);								
								}
								console.log(d["properties"]["culvert_id"]);
								//alert(d["properties"]["culvert_id"]);
								window.open("../../../culvert/IowaWS/iowa_culvert.html?project=IDOT&ws_route=state&culvert_id="+d["properties"]["culvert_id"].replace("#", ""), "blanks");
								window.open("../../../culvert/IowaWS/culvert_time_series/index.html?id="+d["properties"]["culvert_id"].replace("#", ""), "blanks");
							
							});						
						   
						  // console.log(max_y_axis_val);
							value = g_value.selectAll("rect")
						   .data(collection.features)
						   .enter().append("rect")
						   .attr("id", function(d) {
							return "id"+d.properties[key]})
						   .attr("width",3)
						   .attr("d", path) //project data as geometry in svg 
						   .attr("height",function(d) { 
									//console.log(total_bar_height*d.properties[value_percentage_name]);				
								if(d.properties[value_percentage_name]<1){
									return total_bar_height*d.properties[value_percentage_name];
								}else{
									return total_bar_height*d.properties[value_percentage_name]/max_y_axis_val;
								}
							   })			   
							.attr("fill", function(d) { //color enumeration units
								
							  return choropleth(d, recolorMap,value_percentage_name);
							}).on("click", function(d){
								var data_for_pcp_highlight = paracoord_data_preparation([d],attNames,paracor_title,scenario_name);							
								console.log(data_for_pcp_highlight[0]);  
								for(var each in window["idot_correlation_data"]["pcp"]){							
									//window["idot_correlation_data"]["pcp"][each].dehighlight();								
									window["idot_correlation_data"]["pcp"][each].highlight([data_for_pcp_highlight[0]]);								
								}
								console.log(d["properties"]["culvert_id"]);
								//alert(d["properties"]["culvert_id"]);
								window.open("../../../culvert/IowaWS/iowa_culvert.html?project=IDOT&ws_route=state&culvert_id="+d["properties"]["culvert_id"].replace("#", ""), "blanks");
								window.open("../../../culvert/IowaWS/culvert_time_series/index.html?id="+d["properties"]["culvert_id"].replace("#", ""), "blanks");
							})
							.on("mouseover", function(d){
								ifis_ws_search(map,{fill:false,stroke:"#F80303",weight: 2,opacity: 0.6,	color: '#F80303',fillOpacity: 0.1},d["geometry"]["coordinates"][1],d["geometry"]["coordinates"][0],90,"no_fit","9x9","full_ws"); 
							
							})
							.on("mouseout", function(d){
								window["ifis_search_result"].clearLayers();
							})							
							;						
							//.on("mouseover", test)
							//.on("mouseout", dehighlight);
							 /*  
						   .attr("fill",function(d) { 		   
						  return getColor_double_variables(d.properties[value_percentage_name],visualization_variable);   
						   });*/
						   console.log("n");
						} // end of bar representation
				}
		   
		   function test(){
			   console.log(this);			   
		   }
		   
		   function highlight_trace(){		
				//console.log(feature);
				var lng = feature.geometry.coordinates[0];
				var lat = feature.geometry.coordinates[1];
				ifis_ws_search(map,DSS_idot_layer_styles.sub_basin["default"],lat, lng, 500,"fit","9*9");
				if($("#watershed_search").bootstrapSwitch('state')==true){
					iowa_culvert_cal_discharge({'layer':window["ifis_search_result"],'display_id':"discharge_result"});	
				}	
			}
			 function de_highlight_trace(){
				window["ifis_search_result"].clearLayers();
				window["idot"]["culvert_mask"].setStyle({radius: 8,	weight: 2,	opacity: 0.01,	fillOpacity: 0.01});
			}
		  
		  map.on("viewreset", update);  //handel map movement
		  update();  //when map move, this will update and translate coordinate
		  
		  
		  
		  //var recolorMap = colorScale(jsonData.features);		 
		var format = d3.format(".4n"), scale = d3.scale.linear().domain(
			[ -10, 20, 1000 ]).range([ 0, 800, 1000 ]);		
		
		 
	    function idot_data_preparation_scattering_plot(input_json,expressed,attNames,render_doms){ 				
				if(render_doms["scatter"]==false){  //decide if scatter plot should be draw from API
					return false;
				}
				scatter_id = render_doms["scatter"] || "#idot_correlation_scattering_plot";
				var recolorMap = colorScale(input_json.features,expressed);
				var extracting_properties=[]
				input_json.features.forEach(function(d) {			  
						d.properties["expressed_color_value"]=choropleth(d, recolorMap,expressed)
						extracting_properties.push(d.properties);
				})
				var csv_data_conversion=json_to_csv(extracting_properties); 
				console.log(csv_data_conversion);

				function json_to_csv(json){				
						var fields = Object.keys(json[0])
						var replacer = function(key, value) { 
						if(!isNaN(value)){
							value=Number(value);
						}
						return value === null ? '' : value } 
						var csv = json.map(function(row){
						  return fields.map(function(fieldName){
							return JSON.stringify(row[fieldName], replacer)
						  }).join(',')
						})
						csv.unshift(fields.join(',')) // add header column
						return csv.join('\r\n')
						//console.log(csv.join('\r\n'))
				}
				generating_scattering_window(input_json,expressed,attNames,key,scatter_id);
				
				function generating_scattering_window(data_input,expressed,attNames,key,scatter_id){
					//scatter_id = render_doms["scatter"] || "#idot_correlation_scattering_plot";
					$('#idot_correlation_scattering_plot_btn').unbind();
					//$("#scattering_container").append("<div id='idot_correlation_scattering_plot_window_container' class='scattering' style='width:100%; 100%'></div>");  
					var each_options=""
							for(var i in attNames){
								if(window["idot_correlation_parameter_coverter"].hasOwnProperty(attNames[i])){
									each_options+="<option value='"+attNames[i]+"'>" +window["idot_correlation_parameter_coverter"][attNames[i]]+"</option>"
								}
							};
							var dropdown_class=scatter_id.replace("#",".dropdown_for_");
							var downdown_ids=[scatter_id+'_scatter_var1', scatter_id+'_scatter_var2'];
							var scattering_options="<select id='"+downdown_ids[0].replace("#","")+"' class='"+dropdown_class.replace(".","")+"'>"+each_options+"</select><select id='"+downdown_ids[1].replace("#","")+"' class='"+dropdown_class.replace(".","")+"'>"+each_options+"</select>";
							$(dropdown_class).remove();
							$(scatter_id+"_window_content").prepend(scattering_options);
							
							
							$.getScript("assets/js/utility/d3js_scatter/d3_scattering.js", function( data, textStatus, jqxhr ){
								$("#idot_correlation_scattering_plot_window_container").empty();
								d3_scattering__initialize({"key":key ,"input_data_csv":csv_data_conversion,"expressed":expressed,"analytical_attr":downdown_ids,"container_id":scatter_id+"_window_container",color_coding_value:"expressed_color_value","variable_name_dict": window["idot_correlation_parameter_coverter"]});
									
								$(dropdown_class).unbind();
								$(dropdown_class).change(function() {	
									$(scatter_id+"_window_container").empty();								
									d3_scattering__initialize({"key":key ,"input_data_csv":csv_data_conversion,"expressed":expressed,"analytical_attr":downdown_ids,"container_id":scatter_id+"_window_container",color_coding_value:"expressed_color_value","variable_name_dict": window["idot_correlation_parameter_coverter"]});
								 });	    
							});
					
					/*
					$('#idot_correlation_scattering_plot_btn').click(function() { //clicking event 
							//$(document).on('click','#idot_correlation_trees',function(){
							if($("#idot_correlation_scattering_plot_window").length==0){	
							idot_create_modal_window ("idot_correlation_scattering_plot_window",{"title":"Scattering Plot","style":"position:absolute; width:46%; height:40%; right:0%; top:2%","no_background":true});
							    $("#idot_correlation_scattering_plot_window_content").empty();
								$("#idot_correlation_scattering_plot_window_content").append("<div id='idot_correlation_scattering_plot_window_container' class='scattering' style='width:100%; 100%'></div>");  
							    
							}else{						
								$("#idot_correlation_scattering_plot_window").modal("show");						
							}
							
							var each_options=""
							for(var i in attNames){
								if(window["idot_correlation_parameter_coverter"].hasOwnProperty(attNames[i])){
									each_options+="<option value='"+attNames[i]+"'>" +window["idot_correlation_parameter_coverter"][attNames[i]]+"</option>"
								}
							};
							var scattering_options="<select id='idot_correlation_scatter_var1' class='idot_correlation_scatter_var'>"+each_options+"</select><select id='idot_correlation_scatter_var2' class='idot_correlation_scatter_var'>"+each_options+"</select>";
							$(".idot_correlation_scatter_var").remove();
							$("#idot_correlation_scattering_plot_window_content").append(scattering_options);
							$.getScript("assets/js/utility/d3js_scatter/d3_scattering.js", function( data, textStatus, jqxhr ){
								$("#idot_correlation_scattering_plot_window_container").empty();
								d3_scattering__initialize({"key":key ,"input_data_csv":csv_data_conversion,"expressed":expressed,"analytical_attr":["#idot_correlation_scatter_var1","#idot_correlation_scatter_var2"],"container_id":"#idot_correlation_scattering_plot_window_container",color_coding_value:"expressed_color_value","variable_name_dict": window["idot_correlation_parameter_coverter"]});
									
								$('.idot_correlation_scatter_var').unbind();
								$('.idot_correlation_scatter_var').change(function() {	
									$("#idot_correlation_scattering_plot_window_container").empty();								
									d3_scattering__initialize({"key":key ,"input_data_csv":csv_data_conversion,"expressed":expressed,"analytical_attr":["#idot_correlation_scatter_var1","#idot_correlation_scatter_var2"],"container_id":"#idot_correlation_scattering_plot_window_container",color_coding_value:"expressed_color_value","variable_name_dict": window["idot_correlation_parameter_coverter"]});
								 });
							
							
							});
						 setTimeout(function(){ $(".modal-backdrop").remove(); }, 1000);
						
					});//end of click event	*/				
				}//end of generating window				
		}
		
		
		//starts to draw paralle coordinates
		function paracoord_data_preparation(paracor_data_input,attNames,paracor_title,expressed){
			$("#idot_correlation_para").unbind('switchChange.bootstrapSwitch');									
					var pcpdata=[];	
					console.log(attNames);	
					var paracor_data= paracor_data_input["features"] || paracor_data_input;
					paracor_data.forEach(function(d){
					  //attribute names are derived from properties of the first json object
					  // so that the dropdown list could be populated					  
					    var temp={};
						var temp1=jQuery.extend(true, {}, temp); 
						d = d.properties || d;
						var sustainable_design = d["sed_n_sus_design"] || d["culvert_sed-n-sus-design"];
						
						for (var i in attNames){							
							if(d.hasOwnProperty(attNames[i]) && Number(sustainable_design)<1  ){  								
								temp1[attNames[i]]=d[attNames[i]];								
							}
							/*if(["Des Moines Lobe","East-Central Drift Plain","Iowan Surface","Northwest Iowa Plains","Paleozoic Plateau","Southern Iowa Drift Plain"].indexOf(d["landform_region"])==-1){
								console.log(d['sed_n_id']+"not good");
							}*/ //testing landform region
						}					
						d=temp1=jQuery.extend(true, {}, temp1); 					  
					  /*
					  for (var k in d.properties){							
						  if(attNames.indexOf(k) == -1){
							 delete d.properties[k] 
						  }
						  k=paracor_title[k];
							}	*/						 
					  tempProperties = d;
					  pcpdata.push(d);
					});					
					return pcpdata;
					//console.log(expressed);
		}
		
		function paracoord(pcpdata,attNames,paracor_title,expressed,key_id,render_dom){ 
			console.log("--------------------------------------------------");
					
					
					if(!render_dom.hasOwnProperty("pcp")){
						render_dom["pcp"]="#pcp_plot_contain";
					}
					if(!render_dom.hasOwnProperty("pie")){
						render_dom["pcp"]="#idot_correlation_sideplot";
					}
					
					window["idot_correlation_data"][render_dom["pcp"].replace("#","")]={}
					window["idot_correlation_data"][render_dom["pcp"].replace("#","")]['parced_data_default']=pcpdata;
					console.log(window["idot_correlation_data"]);
					//$("#idot_correlation_para_ave").unbind();
			$("#idot_correlation_para_ave").on('change', function(){
						var action=$(this).val();
						$(render_dom["pcp"]).empty();						
			
						var action_list={
							"default":function(render_dom){						
								
								paracoord_draw(pcpdata,expressed,attNames,render_dom);
							},
							"class_average":function(render_dom){
								var new_data = paralle_averaging_function(pcpdata,expressed,attNames,"class_average",key_id,render_dom); //for testing only
								console.log(new_data);
											
								paracoord_draw(new_data,expressed,attNames,render_dom);
							},
							"class_average_landform":function(render_dom){
								var new_data = paralle_averaging_function(pcpdata,"landform_region",attNames,"class_average_field",key_id,render_dom); //for testing only
								console.log(new_data);
											
								paracoord_draw(new_data,expressed,attNames,render_dom);
							},	
							"norm_data":function(render_dom){
								var new_data = paralle_averaging_function(pcpdata,expressed,attNames,"norm_data",key_id); //for testing only
								console.log(new_data);
								paracoord_draw(new_data,expressed,attNames,render_dom);
							},
						}
						action_list[action](render_dom);
				});
				
				
					/*-----the code below triggers the multi-variate clustering SOM ------*/	
				
				/* function (pcpdata) {
							if($(".pcd_btns pcd_zoom_btns").length()==0){
								return pcpdata;								
							}else{
								return window["idot_correlation_data"]["selected_data_from_pcp"] || pcpdata;
							}
							}*/
				$("#trigger_som").unbind();
				$("#old_som").unbind();
				
				
				$("#trigger_som").click(function() {
					
					send_request_to_som();
					//if(Number($("#max_key_range").html())>0.530){	
					//}
					
					function send_request_to_som(){
						
						var data_input = pcpdata;
						if(window["idot_correlation_data"].hasOwnProperty("zoomed_data_for_som")){
							data_input = window["idot_correlation_data"]["zoomed_data_for_som"];
							
						}
						var feature_oprtions_input={	
						"key":"culvert_sed-ratio-n-key", 
						"data_url": jQuery.extend(true, {},data_input),						
						"features":	attNames.slice(0,-1),			
						//['culvert_sed-ratio-n-key','culvert_stc-n','up2500_100mb_ag-m','up2500_100mb_grass','up2500_100mb_forest','fl_ws_area-km','q100'],			
						//['culvert_sed-ratio-n-key','culvert_stc-n','up2500_100mb_ag-m','up2500_100mb_grass','up2500_100mb_forest','fl_ws_area-km','q100'],  			
						"log_ln_field":["fl_ws_area-km",'up2500_100mb_channel-density','fl_100mb_urban','up2500_100mb_coniferous',],  //'culvert_stc-n'
						"optimal_neuron":[3,3]	
					};				  
					 
						let pcp_som_data_collection = culvert_vis_analysis_som(feature_oprtions_input); 						
						pcp_som_data_collection["pcp_container_id"]=render_dom["pcp"] || "#pcp_plot_contain";
						pcp_som_data_collection["recolorMap"] = colorScale(pcpdata,expressed);
						//console.log(pcp_som_data_collection);	
						pcp_som_data_collection["som_container_id"]=render_dom["pie"] || "#idot_correlation_sideplot";	
						//culvert_vis_analysis_som__draw_som_grids(pcp_som_data_collection); 
						
						
						$.getScript( "http://d3js.org/d3.hexbin.v0.min.js", function( data, textStatus, jqxhr ){								
							//console.log(pcp_som_data_collection); 
							
							//if($("#pcp_real_data_vs_normal").val()=='real'){
							/*reverse norm*/								
							/*	var pcp_som_data_collection2= jQuery.extend(true, {}, pcp_som_data_collection)
								pcp_databundle_reverse_norm=reverse_norm(pcp_som_data_collection['som_pcp_data'],pcp_som_data_collection['som_main_setting'],pcp_som_data_collection['edge_bundle_data']);
								pcp_som_data_collection2['som_pcp_data']=pcp_databundle_reverse_norm['row_data_with_cluster'];		
								pcp_som_data_collection2['edge_bundle_data']=pcp_databundle_reverse_norm['edge_bundle_data'];
							    culvert_vis_analysis_som__draw_edgebundle_pcp(pcp_som_data_collection2);	
								culvert_vis_analysis_som__draw_som_hex(pcp_som_data_collection2); 
							*/	  
							//}// if we choose to visualzie in real
							
							//if($("#pcp_real_data_vs_normal").val()=='norm'){							
								culvert_vis_analysis_som__draw_edgebundle_pcp(pcp_som_data_collection);	
								culvert_vis_analysis_som__draw_som_hex(pcp_som_data_collection);
							   
							//}// if we choose to visualzie in real
							
							
						});
					}
								
						
				});
				
				
				
				$("#old_som").click(function() { 
			
					var url= $("#previous_work_files").val() || "assets-examples/js/som_package/som_good_cluster/feature_selection/cluster3_15x15_050.json";
					$.getJSON( url , function(data) { 
							let pcp_som_data_collection = data; 
							pcp_som_data_collection["pcp_container_id"]=render_dom["pcp"] || "#pcp_plot_contain";
							pcp_som_data_collection["recolorMap"] = colorScale(pcpdata,expressed);
							pcp_som_data_collection["som_container_id"]=render_dom["pie"] || "#idot_correlation_sideplot";
							console.log(pcp_som_data_collection);							
							
							$(".legend_container").empty();
							//culvert_vis_analysis_som__draw_som_grids(pcp_som_data_collection); 
							$.getScript( "http://d3js.org/d3.hexbin.v0.min.js", function( data, textStatus, jqxhr ){
								
								
								for(var each_cluster in pcp_som_data_collection['edge_bundle_data']['cluster_info']){  //get sample size
									let raw_data=pcp_som_data_collection['edge_bundle_data']['cluster_info'][each_cluster]['data'];
									for (var each_field in raw_data){
										pcp_som_data_collection['edge_bundle_data']['cluster_info'][each_cluster]["sample_size"]=raw_data[each_field].length;
									}
								}
								
								if($("#pcp_real_data_vs_normal").val()=='real'){
								/*reverse norm*/								
									var pcp_som_data_collection2= jQuery.extend(true, {}, pcp_som_data_collection)
									pcp_databundle_reverse_norm=reverse_norm(pcp_som_data_collection['som_pcp_data'],pcp_som_data_collection['som_main_setting'],pcp_som_data_collection['edge_bundle_data']);
									pcp_som_data_collection2['som_pcp_data']=pcp_databundle_reverse_norm['row_data_with_cluster'];		
									pcp_som_data_collection2['edge_bundle_data']=pcp_databundle_reverse_norm['edge_bundle_data'];
									culvert_vis_analysis_som__draw_edgebundle_pcp(pcp_som_data_collection2);	
									culvert_vis_analysis_som__draw_som_hex(pcp_som_data_collection2);  
									  
								}// if we choose to visualzie in real
								
								if($("#pcp_real_data_vs_normal").val()=='normal'){							
									culvert_vis_analysis_som__draw_edgebundle_pcp(pcp_som_data_collection);	
									culvert_vis_analysis_som__draw_som_hex(pcp_som_data_collection);
								   
								}// if we choose to visualzie in real
							
								
							});						
					});
				});
				
				function reverse_norm(row_data_with_cluster,init_settings_input,edge_bundle_data_input){
								let raw_full_hash={},join_key=init_settings_input["join_key"],reverse_norm_data_with_cluster=[],
								min_set={},max_set={}, edge_bundle_data_output= jQuery.extend(true, {}, edge_bundle_data_input);
								
								for(var each_dataset in window["idot_correlation_data"]["full_data_for_som"]){
									var each_dataset_join_key=window["idot_correlation_data"]["full_data_for_som"][each_dataset][join_key];
									raw_full_hash[each_dataset_join_key]= window["idot_correlation_data"]["full_data_for_som"][each_dataset];
									
								}								
											
								for(var each_item_index in row_data_with_cluster){
										let each_item_key=row_data_with_cluster[each_item_index][join_key];					
										
										
										if(raw_full_hash.hasOwnProperty(each_item_key)){
											delete raw_full_hash[each_item_key]['landform_region'];
											raw_full_hash[each_item_key]['cluster_id']=row_data_with_cluster[each_item_index]['cluster_id'];						
											reverse_norm_data_with_cluster.push(raw_full_hash[each_item_key]);	 					
											for(var each_variable in raw_full_hash[each_item_key]){
												if(!min_set.hasOwnProperty(each_variable)){
													max_set[each_variable]=-9999;
													min_set[each_variable]=9999;
												}
												max_set[each_variable]= Number(raw_full_hash[each_item_key][each_variable])>=max_set[each_variable]?Number(raw_full_hash[each_item_key][each_variable]):Number(max_set[each_variable]);
												min_set[each_variable]= Number(raw_full_hash[each_item_key][each_variable])<=min_set[each_variable]?Number(raw_full_hash[each_item_key][each_variable]):Number(min_set[each_variable]);				
											}	
										
										}//end of if				
								}
								
								for (var each_class in edge_bundle_data_output['cluster_info']){
									let each_class_mean=edge_bundle_data_output['cluster_info'][each_class]['mean'];
									for(var each_field in each_class_mean){
										if(each_field!='cluster_id' && each_field!=join_key){ 
											each_class_mean[each_field]=(Number(each_class_mean[each_field])*(Number(max_set[each_field])-Number(min_set[each_field]))+Number(min_set[each_field]));
											if(isNaN(each_class_mean[each_field])){
												console.error(each_class_mean[each_field]+" "+each_field);
												console.error(each_class_mean[each_field]+" "+max_set[each_field]+" "+min_set[each_field]);
											}	
										}//if statement
									}//end of for	

									let each_class_cluster_to_full_data=edge_bundle_data_output['cluster_info'][each_class]['cluster_to_full_data'];
									for(var each_group in each_class_cluster_to_full_data){
										let each_cluster_to_full_data=each_class_cluster_to_full_data[each_group];
										for(var each_field in each_cluster_to_full_data){
										if(each_field!='cluster_id' && each_field!=join_key){ 
											each_cluster_to_full_data[each_field]=(Number(each_cluster_to_full_data[each_field])*(Number(max_set[each_field])-Number(min_set[each_field]))+Number(min_set[each_field]));
											if(isNaN(each_cluster_to_full_data[each_field])){
												console.error(each_cluster_to_full_data[each_field]+" "+each_field);
												console.error(each_cluster_to_full_data[each_field]+" "+max_set[each_field]+" "+min_set[each_field]);
											} 	
										}//if statement 
									}//end of for	 								
									}
									
									
								}

								
								console.log("main data setting");
								console.log(init_settings_input);
								console.log(edge_bundle_data_output);
								//cluster_to_full_data
								
								return {"row_data_with_cluster":reverse_norm_data_with_cluster,"edge_bundle_data":edge_bundle_data_output};
								
								
								
							}
		
					
					
				//codes below handels brushing events	PCP display
				$("#idot_correlation_para").on('switchChange.bootstrapSwitch', function(event, state){
					//state  ?  $(".idot_mcda_2nd").show() :   $(".idot_mcda_2nd").hide()  ;  
					if(state==true){
						paracoord_draw(pcpdata,expressed,attNames);	 
						$(".idot_mcda_2nd").show()
									
					}else{
						$(".idot_correlation_panel").remove();
						$(".idot_mcda_2nd").hide()
					}
				});
		/*the block of code here is only for experiment*/
		
		$(document).ready(function(event, state){
			setTimeout(function(){ 
				paracoord_draw(pcpdata,expressed,attNames,render_dom);	
				$(".idot_mcda_2nd").show();				
			}, 100);
			
		});
		
		
			
		function paralle_averaging_function(data_input,expressed,attNames,action_type,key_id,render_dom){
//[render_dom["pcp"].replace("#","")]
			if(!window.hasOwnProperty('parced_data_averging_id_cluster')){
				window["idot_correlation_data"]['parced_data_averging_id_cluster']={};
			}
		
			var actions = {
				"proto":function(data_input){
					data_input.map(function(d) {				
						var mcda_attri_list={};
						for(each_attr in attNames){
						mcda_attri_list[attNames[each_attr]]=d[attNames[each_attr]];
						}			
						return {"resp_var":d[expressed],"color_gp":recolorMap(d[expressed]),"inde_var":mcda_attri_list };
					});
					
				}, //end of one action 
				"class_average":function(data_input){  //averaging data to calculate mean based on different classification classes
					/* inputdata will be in the form of {[],[],[]}*/
					var mcda_attri_sum_list={};  //will be a hash table of different color coded value
					data_input.map(function(d) {  // go through the entire data
						var color_label=recolorMap(d[expressed]); //color value						
						if(!mcda_attri_sum_list.hasOwnProperty(color_label)){  //if the catagory of color doesn't exit
							mcda_attri_sum_list[color_label]={};
							for(each_attr in attNames){  
								mcda_attri_sum_list[color_label][attNames[each_attr]]=Number(d[attNames[each_attr]]);  //first value of the sum, for calculating average later
							}
							mcda_attri_sum_list[color_label]["sample_population"]=1;
							mcda_attri_sum_list[color_label]["map_components_id_group"]=["same_as_color_coding",d[key_id]];   //first value of the id group array, this is for enabling brushing during averaging state
						}else{
							mcda_attri_sum_list[color_label]["sample_population"]+=1;
							for(each_attr in attNames){
								mcda_attri_sum_list[color_label][attNames[each_attr]]+=Number(d[attNames[each_attr]]);  //calculating sum for each attribute								
							}
							mcda_attri_sum_list[color_label]["map_components_id_group"].push(d[key_id]);  //add value of the id group array, this is for enabling brushing during averaging state
							}
					});				
					var result=[];
					for(var each_color in mcda_attri_sum_list){
						var intermediate_for_averaging={};
						for(each_attr in attNames){
							intermediate_for_averaging[attNames[each_attr]]=mcda_attri_sum_list[each_color][attNames[each_attr]]/mcda_attri_sum_list[each_color]["sample_population"];
							}							
							window["idot_correlation_data"]['parced_data_averging_id_cluster'][String(intermediate_for_averaging[key_id])]=mcda_attri_sum_list[each_color]["map_components_id_group"]
							/*code above push value to a window object that match cluster id with individual id*/							
							result.push(intermediate_for_averaging);
							
					}
					console.log(window["idot_correlation_data"]['parced_data_averging_id_cluster']);
					return result;
				},//end of one action 
				"class_average_field":function(data_input){  //averaging data to calculate mean based on different classification classes
					/* inputdata will be in the form of {[],[],[]}*/
					var mcda_attri_sum_list={};  //will be a hash table of different color coded value
					data_input.map(function(d) {  // go through the entire data
						var class_label=d[expressed]; //color value						
						if(!mcda_attri_sum_list.hasOwnProperty(class_label)){  //if the catagory of color doesn't exit
							mcda_attri_sum_list[class_label]={};
							for(each_attr in attNames){  
								mcda_attri_sum_list[class_label][attNames[each_attr]]=Number(d[attNames[each_attr]]);  //first value of the sum, for calculating average later
							}
							mcda_attri_sum_list[class_label]["sample_population"]=1;
							mcda_attri_sum_list[class_label]["map_components_id_group"]=["same_as_color_coding",d[key_id]];   //first value of the id group array, this is for enabling brushing during averaging state
						}else{
							mcda_attri_sum_list[class_label]["sample_population"]+=1;
							for(each_attr in attNames){
								mcda_attri_sum_list[class_label][attNames[each_attr]]+=Number(d[attNames[each_attr]]);  //calculating sum for each attribute								
							}
							mcda_attri_sum_list[class_label]["map_components_id_group"].push(d[key_id]);  //add value of the id group array, this is for enabling brushing during averaging state
							}
					});				
					var result=[];
					for(var each_class_label in mcda_attri_sum_list){
						var intermediate_for_averaging={};
						for(each_attr in attNames){
							
								if(attNames[each_attr]!=expressed){ 
									intermediate_for_averaging[attNames[each_attr]]=mcda_attri_sum_list[each_class_label][attNames[each_attr]]/mcda_attri_sum_list[each_class_label]["sample_population"];
								}else{
									intermediate_for_averaging[attNames[each_attr]]=each_class_label;  
								}
							}							
							window["idot_correlation_data"]['parced_data_averging_id_cluster'][String(intermediate_for_averaging[key_id])]=mcda_attri_sum_list[each_class_label]["map_components_id_group"]
							/*code above push value to a window object that match cluster id with individual id*/							
							result.push(intermediate_for_averaging);
							
					}
					//console.log(result);
					console.log(window["idot_correlation_data"]['parced_data_averging_id_cluster']);
					return result;
					
					function isAlpha(ch){
					  return typeof ch === "string" && ch.length === 1
							 && (ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z");
					}
				},//end of one action 
				"norm_data":function(data_input){  //using nested mean for classification
						var log_ln_field = [
											'up2500_100mb_channel-density','fl_100mb_channel-density','up2500_500mb_channel-density',"fl_ws_area-km",
											'up2500_100mb_urban','fl_100mb_urban','up2500_500mb_urban',"fl_ws_urban",
											'up2500_100mb_coniferous','fl_100mb_coniferous','up2500_500mb_coniferous',"fl_ws_coniferous",				
											]; 
						
						//fl_ws_area-km fl_ws_water  up2500_500mb_water  fl_100mb_barren up2500_100mb_urban
							var result=data_normalization(data_input,attNames,log_ln_field,expressed);
							//survey_nested_mean(data_input,3);
							console.log(result); 
								return result;				
							
					
				}//end of one action 
			}; //end of actions
			return actions[action_type](data_input);
			
			
			
		}//end of averaging	

					
		}//end of paral coord
		
		function data_normalization(data,attNames,log_ln_field,key){ 
		
			let getMean = function (data) {
				return data.reduce(function (a, b) {
					return Number(a) + Number(b);
				}) / data.length;
			};
			let getSD = function (data) {
				let m = getMean(data);
				return Math.sqrt(data.reduce(function (sq, n) {
						return sq + Math.pow(n - m, 2);
					}, 0) / (data.length - 1));
			};			
			var data_feature=data["features"] || data;
			var max_value_set={}, min_value_set={},dataset_for_stats={},normalized_results=[],stats_set={};
			for(var i in data_feature){						
						var each_item=data_feature[i]["properties"] || data_feature[i];					
						//console.log(each_item["site_id"]);
						var each_site_id = each_item[key];	
							for(var eachfeature in attNames){
								if( log_ln_field.indexOf(attNames[eachfeature])!=-1){	

											//let value = 
											//-Infinity
										if(Math.log10(Number(each_item[attNames[eachfeature]]))==-Infinity){
											each_item[attNames[eachfeature]]=0; 
										}else{
											each_item[attNames[eachfeature]]=Math.log10(Number(each_item[attNames[eachfeature]])); 									
										}
									 							
								}
							
								if(!max_value_set.hasOwnProperty(attNames[eachfeature])){
									max_value_set[attNames[eachfeature]]=-99999;
									min_value_set[attNames[eachfeature]]=99999;
									dataset_for_stats[attNames[eachfeature]]=[];
								}
								dataset_for_stats[attNames[eachfeature]].push(Number(each_item[attNames[eachfeature]]))
								if(Number(each_item[attNames[eachfeature]])>=max_value_set[attNames[eachfeature]]){
									max_value_set[attNames[eachfeature]]=Number(each_item[attNames[eachfeature]]);									
								}
								if(Number(each_item[attNames[eachfeature]])<=min_value_set[attNames[eachfeature]]){
									min_value_set[attNames[eachfeature]]=Number(each_item[attNames[eachfeature]]);									
								}								
								//text_features_training+="'"+attNames[eachfeature]+"':Number("+(each_item[attNames[eachfeature]])+"),"								
							}
					} //end of for loop
					for(var eachfeature in attNames){
						let eachfield = attNames[eachfeature];
						stats_set[eachfield]={  
							"mean": getMean(dataset_for_stats[eachfield]),
							"std": getSD(dataset_for_stats[eachfield]) };
					}
			
						
			for(var i in data_feature){						
						var each_item=data_feature[i]["properties"] || data_feature[i];						
						let temp_for_each={};
						//var each_site_id = each_item[key];						
							for(var eachfeature in attNames){							
								
									//each_item[attNames[eachfeature]]=(each_item[attNames[eachfeature]]-stats_set[attNames[eachfeature]]["mean"])/stats_set[attNames[eachfeature]]["std"];
									if(attNames[eachfeature]=="up2500_100mb_coniferous"){ 
										//console.log('('+Number(each_item[attNames[eachfeature]])+'-'+min_value_set[attNames[eachfeature]]+')/('+max_value_set[attNames[eachfeature]]+'-'+min_value_set[attNames[eachfeature]]+')');
									}
									if(attNames[eachfeature]!=key){
										temp_for_each[attNames[eachfeature]]=(Number(each_item[attNames[eachfeature]])-min_value_set[attNames[eachfeature]])/(max_value_set[attNames[eachfeature]]-min_value_set[attNames[eachfeature]]);
										}else{
											temp_for_each[attNames[eachfeature]]=Number(each_item[attNames[eachfeature]]);
										}
									
									//each_item[attNames[eachfeature]]=temp_for_each[attNames[eachfeature]];									
								
								
								//text_features_training+="'"+attNames[eachfeature]+"':Number("+(each_item[attNames[eachfeature]])+"),"								
							}
						normalized_results.push(temp_for_each);
					} //end of for loop
			//console.log(normalized_results);
			
			return normalized_results;		
		}//end of normalized
		
		function paracoord_draw(pcpdata,expressed,attNames,render_dom){			
			
					var pcp_contain=render_dom["pcp"] || "#pcp_plot_contain";
					var pie_id=render_dom["pie"] || "#idot_correlation_sideplot";					
					var pcp_id=pcp_contain+"_plot";
					
								
			      var recolorMap = colorScale(pcpdata,expressed);
			      $(".idot_correlation_panel").remove();
				  //leaflet_l("<div id='paracoord'  class='parcoords' style='500px;height:220px'></div>","","idot_correlation_panel function_panel "+dss_panel_holder_id); 		
					$(pcp_contain).append("<div id='"+pcp_id.replace("#","")+"'  class='parcoords' style='height:"+$(pcp_contain).parent().height()+"px;width:"+($(pcp_contain).width()+40)+"px'></div>");
					setTimeout(function(){ 
						$('.bottom_container').css("bottom","0");
					}, 100);
									
				
					$.getScript( "assets/js/leaflet_extension/d3.parcoords.js", function( data, textStatus, jqxhr ){						
								
								if(!window["idot_correlation_data"].hasOwnProperty("pcp")){
									window["idot_correlation_data"]["pcp"]={};
								}								
								
								//var pcp 
								window["idot_correlation_data"]["pcp"][pcp_id] = d3.parcoords()(pcp_id).data(pcpdata).color(function(d) {
								  //if value exists, assign it a color; otherwise assign gray
								  if (d[expressed]) {
									return recolorMap(d[expressed]); //recolorMap holds the colorScale generator
								  } else {
									return "#ccc";
								  };
								}).render().brushable().on("brush", function(items) {	
										   //console.log("a");
										  var selected_cluster_to_individual=""
										  var selected = items.map(function(d) {		//for single value selection
											if(window["idot_correlation_data"].hasOwnProperty("parced_data_averging_id_cluster")){
											  //if(window["idot_correlation_data"][render_dom["pcp"].replace("#","")]['parced_data_averging_id_cluster'].hasOwnProperty(String(d[key]))){
											  selected_cluster_to_individual+= ","+window["idot_correlation_data"]['parced_data_averging_id_cluster'][String(d[key])].join(",");
										     //console.log(selected_cluster_to_individual); 
											 //selected_cluster_to_individual+= ","+window["idot_correlation_data"][render_dom["pcp"].replace("#","")]['parced_data_averging_id_cluster'][String(d[key])].join(",");
											 //}
											 }//accumlting clustering id	
											return d[key]; //selected value from brushing (non-cluster case)											
										  });
										  
										  var selected2 = jQuery.extend(true, {}, selected); 	
										  idot_mcda_side_plot(brushsideplot(items,expressed,attNames),pie_id,window["idot_correlation_data"]["pcp"][pcp_id]);
										
										  
										  var tree_data_brush=filer_based_on_key(pcpdata,selected,key);  //generate_clipped_data_for_tree
										  
										  prapare_for_zoomed_pcd(tree_data_brush,expressed,attNames,pcp_contain,render_dom);  //generate button and events for zooming in selected value										  
											window["idot_correlation_data"]["selected_data_from_pcp"] = tree_data_brush; 
										  //[String(intermediate_for_averaging[key_id])]
										  //console.log(selected.join(","));
										if(window.hasOwnProperty('value')){
											window['value'].style("opacity", 0.05).filter(function(d) {	
												//console.log("S:"+selected_cluster_to_individual+"  dkey:"+d.properties[key]);
												return selected.indexOf(d.properties[key]) > -1 || (selected_cluster_to_individual.split(",")).indexOf(d.properties[key]) > -1;
												  //if there it is in the slected  value
											 }).style("opacity", 1);	
										}
										if(window.hasOwnProperty('bar')){
											window['bar'].style("opacity", 0.05).filter(function(d) {											
												return selected.indexOf(d.properties[key]) > -1 || (selected_cluster_to_individual.split(",")).indexOf(d.properties[key]) > -1  //if there it is in the slected  value
											  }).style("opacity", 1);
										}												   
										if(window.hasOwnProperty('d3_circular_culvert')){											
											window['d3_circular_culvert'].style("opacity", 0.05).filter(function(d) {											
												return selected.indexOf(d.properties[key]) > -1 || (selected_cluster_to_individual.split(",")).indexOf(d.properties[key]) > -1  //if there it is in the slected  value
											 }).style("opacity", 1);
										}
										
										  
										  
										  if(typeof(window["idot_coorelation_scattering"])!="undefined"){   //filtering dots on scattering plots
												//console.log("hidder sctpoint2");
												window["idot_coorelation_scattering"].style("opacity", 0.05).filter(function(d) {
													  return selected.indexOf(d[key]) > -1;
													}).style("opacity", 1);												
											}
											
								});
								
								//change_paracord_label();
								pcp_label_conversion();
								idot_mcda_side_plot(brushsideplot(pcpdata,expressed,attNames),pie_id,window["idot_correlation_data"]["pcp"][pcp_id]);  //draw prescentage plot								
								//$(".shadows").css("background-color", "#B2B2B2");
								$("#pcp_plot_contain5_plot").css("background-color", "#B2B2B2");
								
								
								/*$(".shadows").height(Number($(".shadows").css("margin-top").replace("px",""))+$(".shadows").height()+10);
								$(".shadows").css("margin-top",0); 
								$(".shadows").css("background-color", "#B2B2B2");*/
								//console.log(pcpdata);
								//console.log(JSON.stringify(pcpdata));
						
						
					});//end of script 
			  }//end of para_draw
		
		
		function prapare_for_zoomed_pcd(data,expressed,attNames,pcp_id,render_dom){
			//paracoord  .retote_vertical
			//console.log(data.length>1);
			var btn_zoom_id=render_dom["pcp"]+"zoom_btn";
			var btn_res_id=render_dom["pcp"]+"restor_btn"
			console.log($(".pcd_zoom_btns").length); 
			
			if(data.length>0 && $(btn_zoom_id).length==0 && $(btn_res_id).length==0){
				//console.log(pcp_id);
				$(pcp_id).prepend('<button type="button" id="'+btn_zoom_id.replace("#","")+'" class = "retote_vertical pcd_btns pcd_zoom_btns" style="position: absolute;z-index: 999;">Zoom on selected</button>');
			     				 
			}
			$(btn_zoom_id).unbind();
			
			$(btn_zoom_id).click(function() {
				$(render_dom["pcp"]).empty();
				//console.log('zoomed in');
				window["idot_correlation_data"]["zoomed_data_for_som"]=data;
				paracoord_draw(data,expressed,attNames,render_dom);				
				$(pcp_id).prepend('<button type="button" id="'+btn_res_id.replace("#","")+'" class = "retote_vertical pcd_btns pcd_restore_btns" style="position: absolute;z-index: 999;">Full data</button>');
			    $(btn_zoom_id).remove();
				$(btn_res_id).click(function() {
				$(render_dom["pcp"]).empty();
				//console.log('zoomed out');
				//console.log(render_dom["pcp"]);	
				window["idot_correlation_data"]["zoomed_data_for_som"]=window["idot_correlation_data"][render_dom["pcp"].replace("#","")]['parced_data_default'];
				paracoord_draw(window["idot_correlation_data"][render_dom["pcp"].replace("#","")]['parced_data_default'],expressed,attNames,render_dom);
				$(btn_res_id).unbind();
				$(btn_res_id).remove();
				
			    });				
				});
			
				
				
			
		}
		
		function filer_based_on_key(data,filter_keys,key_field){
			
					if(data.hasOwnProperty("features")){
						var data_copy=jQuery.extend(true, {}, data); 
								data_copy.features=[];
								data.features.forEach(function(d){
							 	//console.log(key_field);
								//console.log(filter_keys); 
								//console.log(d.properties[key_field]);
								if(filter_keys.indexOf(d.properties[key_field])!=-1){									
									data_copy.features.push(d); 
								}
							});
							//console.log(data_copy.length);
							return data_copy;
					}else{						 
								var data_copy=[];
								data.forEach(function(d){							 
								if(filter_keys.indexOf(d[key_field])!=-1){									
									data_copy.push(d); 
								}
							});
							//console.log(data_copy.length);
							return data_copy;						
					}	
					} 
		
		function brushsideplot(items,expressed,attNames){			
				var selected_express = items.map(function(d) {					
					return [d[expressed],recolorMap(d[expressed]),d];
				});					
				window["idot_correlation_data"]["group_count"]={};			
				var result={};
				for(var i in selected_express){		
							var color_name=selected_express[i][1];
							//console.log(selected_express[i]); 
							if(result.hasOwnProperty(color_name)){
								result[color_name]["population"]+=1;
								result[color_name]["children_data"].push(selected_express[i][2]);
							}else{
								result[color_name]={"children_data":[selected_express[i][2]] ,"population":1};
						}
				}
				//console.log("---------------");
				//console.log(result);
				return result;
		}//end of function		
		
		//side bar percentage plot
		function idot_mcda_side_plot(input_data,pie_continer_id,pcp){
				var translate={
						"#0D9FFF":"Clean",
						"#4778FF":"Low",
						"#8051FF":"Med",
						"#C323FF":"High",
						"#F203FF":"Very high",
						
						"#ff9999":"Clean",
						"#ff4d4d":"Low",
						"#ff0000":"Med",
						"#b30000":"High",
						
						"#fed98e":"Clean",
						"#fecc5c":"Low",
						"#fd8d3c":"Med",
						"#f03b20":"High",
						"#bd0026":"Very high",	 
						
						"#fdd0a2":"Clean",
						"#fdae6b":"Low",
						"#FF8E3C":"Med",
						"#e6550d":"High",
						"#a63603":"Very high",
						
						"#fcc5c0":"Clean",
						"#fa9fb5":"Low",
						"#f768a1":"Med",
						"#c51b8a":"High",
						"#7a0177":"Very high",
						
						"#dadaeb":"Clean",
						"#bcbddc":"Low",
						"#9e9ac8":"Med",
						"#756bb1":"High",
						"#54278f":"Very high",
						
						"#1a9641":"Clean",
						"#a6d96a":"Low",
						"#ffffbf":"Med",
						"#fdae61":"High",
						"#d7191c":"Very high"
						
						
						
						
						
					};
				
				var data=[];
				var color_code=[];
				var count=0;
				for(var tag in translate){
					for(var i in input_data){
						if(tag==i){
							data.push({"population":input_data[i]['population'],"group":i,"children_for_highlight":input_data[i]['children_data']});
							color_code.push(i);
							count+=input_data[i]['population'];						 
						}						
					}
				};

				
				 //pie_continer_id = pie_continer_id || "#idot_correlation_sideplot";
			
				$(pie_continer_id).empty();
			//var inputdata="group,population\n<5,2704659\n5-13,4499890\n14-17,2159981";
				var svg_id=pie_continer_id+"_idot_correlation_test";
				var svg = d3.select(pie_continer_id).append("svg").attr("id",svg_id).attr("width", ($(pie_continer_id).width())).attr("height", ($(pie_continer_id).height()));		
				
				d3.select(pie_continer_id).style("width", ($(pie_continer_id).width())).style("height", ($(pie_continer_id).height()));				
				//$(pie_continer_id).height( 180 );				
				$(pie_continer_id).prepend("<p>Sample Population: "+count+"</p>"); 
				width = ($(pie_continer_id).width()), //190
				height = ($(pie_continer_id).height()), //190
				//radius = Math.min(width, height) / 2,
				radius = height	<width ?   height/2.3 :  width/2, 				
				console.log(height+" "+width+" "+radius);
				g = svg.append("g").attr("transform", "translate(" + width/2 + "," + height/2 + ")");
				//["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]
				var color = d3.scale.ordinal().range(color_code);

				var pie = d3.layout.pie()
					.sort(null)
					.value(function(d) { return d.population; });

				var path = d3.svg.arc()
					.outerRadius(radius - 10)
					.innerRadius(0);

				var label = d3.svg.arc()
					.outerRadius(radius - 40)
					.innerRadius(radius - 40);

				//d3.csv("test.csv", function(d) {
				//  d.population = +d.population;
				//  return d;
				//}, function(error, data) {
				  //if (error) throw error;
					//console.log(data);
				  var arc = g.selectAll(".arc")
					.data(pie(data))
					.enter().append("g")
					  .attr("class", "arc");
					  
				  arc.append("path")
					  .attr("d", path)
					  .attr("fill", function(d) { 
							//console.log(d);
							return color(d.data.group); })
					  //.on("click", mover)
					  .on("mouseout", pie_mout)
					  .on("mouseover", pie_mover);				  
					  
				
				  arc.append("text")
					  .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
					  .attr("pointer-events", "none")
					  .attr("dy", "0.15em")
					  .attr("dx", "-1em")
					  .text(function(d) { return side_plot_text(d.data); }); 
					  
				  arc.append("text")
					  .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
					  .attr("pointer-events", "none")
					  .attr("dy", "1.55em")
					  .attr("dx", "-1em")
					  .text(function(d) { 	console.log(d)
											let precent=100*(d['value']/count);
											return precent.toFixed(0)+"%";										
										}); 
					  
				//});
				function side_plot_text(data){		
					 let text=data.group
					if(translate.hasOwnProperty(text)){
						return translate[text];  // translate color code into "class"
					}else{
						return text;						
					}					
				}
				function pie_mout(d) { 
					var el = d3.select(this)
					   .transition()
					   .duration(100)
					   .style("fill-opacity", 1);
					   pcp.unhighlight();
					   //.style("stroke", "white")
					   //.style("stroke-width", 1);					  
					  //$("#chart_info").html(""); 
				};
				function pie_mover(d) { 
						   var el = d3.select(this)
							.transition()
							.duration(10)	
							.style("fill-opacity", 0.3);
							
							//console.log(d['data']['children_for_highlight']);
							pcp.highlight(d['data']['children_for_highlight']);
							//console.log("for_high_light");
							//console.log(d['data']['children_for_highlight'][0]);
							//.style("stroke", "red")
							//.style("stroke-width", 5)
							//;		
						//console.log(this.id); 
						   //var cluster_name = this.id.replace("hid","")
							//console.log(init_settings["data"]);
						   //var group=init_settings["data"][cluster_name];
						   //var group_neighbour=init_settings["neighbour"][cluster_name];	     
						   
							//index 
							/*if(window.hasOwnProperty('som_pcp') && init_settings.hasOwnProperty('pcp_data')){
								var highlight_list=[];
								
								init_settings['pcp_data'].forEach((item, index) => {
									  if(item['cluster_id']==cluster_name){
										  highlight_list.push(item);
									  }				  
									});
								window['som_pcp'].highlight(highlight_list);
							}*/
								
					}
		}
		
		function change_paracord_label(){		

			$(".label").each(function(){
					var old_v=$(this).html();
					if(idot_correlation_parameter_coverter.hasOwnProperty(old_v)){
						//$(this).parent().append("<div>"+idot_correlation_parameter_coverter[old_v]+"</div>");
						$(this).text(idot_correlation_parameter_coverter[old_v]);
					}
				});
			$(".label").css({
				fontSize: 13 
			});
			$(".tick").css({
				fontSize: 13 
			});
			
			
			
			$(".dimension").find( "text" ).each(function(){
					var old_v=$(this).html(); 
					
					if((old_v).length>8){
						//$(this).parent().append("<div>"+idot_correlation_parameter_coverter[old_v]+"</div>");
						
						$(this).css({
								fontSize: 10
							});
						$(this).css("font-weight", "bold");
					}
				});
				
				
		}
		
       
		  
		  
		function reset() {
        var bounds = path.bounds(jsonData),
        topLeft = bounds[0],
        bottomRight = bounds[1];

        svg.attr("width", bottomRight[0] - topLeft[0])
        .attr("height", bottomRight[1] - topLeft[1])
        .style("left", topLeft[0] + "px")
        .style("top", topLeft[1] + "px");

        g.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");

       
      }

      // Use Leaflet to implement a D3 geometric transformation.
      function projectPoint(x, y) {
        var point = map.latLngToLayerPoint(new L.LatLng(y, x));
        this.stream.point(point.x, point.y);
      }
	 

    function colorScale1(features,expressed){
			//console.log(features);
			//console.log(expressed);
		  //create quantile classes with color scale

		  var color = d3.scale.quantile() //designate quantile scale generator
		  .range(initialColors);
			//console.log("step2");
		  //build array of all currently expressed values for input domain
		  var domainArray = [];

		  for (var a=0; a<features.length; a++){
			
			if(features[a].hasOwnProperty("properties")){
				domainArray.push(Number(features[a].properties[expressed]));
			}else{
				domainArray.push(Number(features[a][expressed]));
			}
			
			
		  }

		  //pass array of expressed values as domain
		  color.domain(domainArray);

		  return color;	 //return the color scale generator
    };
	
	
	

    function choropleth(d, recolorMap){
      //get data value
      var value = d.properties[expressed];
	  
      //if value exists, assign it a color; otherwise assign gray
      if (value) {	
        return recolorMap(value); //recolorMap holds the colorScale generator
      } else {
        return "#ccc";
      };
    };
	
	

	
	/*
    function changeAttribute(attribute, jsonData){
      //change the expressed attribute
      expressed = attribute;
      var recolorMap = colorScale(jsonData.features);

      //recolor the map
      d3.selectAll(".regions")//select every region
      .style("fill", function(d) { //color enumeration units
        return choropleth(d, recolorMap); //->
      }).style("opacity", 1)
      .select("desc") //replace the color text in each region's desc element
      .text(function(d) {
        return choropleth(d, recolorMap); //->
      });

      //remove the previous pcp so that they are not drawn on top of each other
      d3.select("#paracoord").selectAll("*").remove();
      var pcp = d3.parcoords()("#paracoord").data(pcpdata).color(function(d) {
        //if value exists, assign it a color; otherwise assign gray
        if (d[expressed]) {
          return recolorMap(d[expressed]); //recolorMap holds the colorScale generator
        } else {
          return "#ccc";
        };
      }).render().brushable().on("brush", function(items) {
        var selected = items.map(function(d) {
          return d[key];
        });
        value.style("opacity", 0.2).filter(function(d) {
          return selected.indexOf(d.properties[key]) > -1;
        }).style("opacity", 1);
		
		if(typeof(window["idot_coorelation_scattering"])!="undefined"){
			console.log("hidder sctpoint");
			window["idot_coorelation_scattering"].style("opacity", 0.2).filter(function(d) {
				  return selected.indexOf(d[key]) > -1;
				}).style("opacity", 1);
			
		}
		
		
		
      });

    };*/ //not in use

    function format(value){
      //format the value's display according to the attribute
      if (expressed != "Population"){
        value = "$"+roundRight(value);
      } else {
        value = roundRight(value);
      };
      return value;
    };

    function roundRight(number){
      if (number>=100){
        var num = Math.round(number);
        return num.toLocaleString();
      } else if (number<100 && number>=10){
        return number.toPrecision(4);
      } else if (number<10 && number>=1){
        return number.toPrecision(3);
      } else if (number<1){
        return number.toPrecision(2);
      };
    };

    function highlight(data){

      var props = data.properties; //json properties
      // d3.selectAll("#id"+props[key]) //select the current region in the DOM
      // .style("fill", "#000"); //set the enumeration unit fill to black
	  var value = parseFloat(Math.round(props[expressed] * 1000) / 1000).toFixed(3)
      var labelAttribute = "<h1>"+value+
      "</h1><br><b>"+expressed+"</b>"; //label content
      var labelName = props[key] //html string for name to go in child div

      // d3.select("#info-label").selectAll("*").remove();
      //create info label div
	  /*
      var infolabel = d3.select("#info-label")
      .append("div") //create the label div
      .attr("class", "infolabel")
      .attr("id", props[key]+"label") //for styling label
      .html(labelAttribute) //add text
      .append("div") //add child div for feature name
      .attr("class", "labelname") //for styling name
      .html(labelName); //add feature name to label*/
    };

    function dehighlight(data){

      var props = data.properties; //json properties
      //var region = d3.selectAll("#id"+props[key]); //select the current region
      // var fillcolor = region.select("desc").text(); //access original color from desc
      // region.style("fill", fillcolor); //reset enumeration unit to orginal color

      d3.select("#id"+props[key]+"label").remove(); //remove info label
      d3.select("#info-label").selectAll("*").remove();
    };

    function moveLabel() {

      var x = d3.event.clientX+10; //horizontal label coordinate based mouse position stored in d3.event
      var y = d3.event.clientY-75; //vertical label coordinate
      d3.select(".infolabel") //select the label div for moving
      .style("margin-left", x+"px") //reposition label horizontal
      .style("margin-top", y+"px"); //reposition label vertical
    };
		  	  
		  function update(){			
					// zoom: 11,
					var scale = 2*(map.getZoom()/11);
					if(map.getZoom()<=12){
						scale = 1;
					}
					//console.log(1.5*map.getZoom());
				//	console.log(scale);
				if(window.hasOwnProperty('bar')){
					bar.attr("transform", function(d) { 
					   return "translate("+ 
					map.latLngToLayerPoint(d.LatLng).x +","+ 
					(map.latLngToLayerPoint(d.LatLng).y-Number(scale*total_bar_height)) +")";
					   }
				   )			
				
					bar.attr("height",total_bar_height*scale);
					value.attr("height",function(d) {	
						 if(d.properties[value_percentage_name]<1){
								return total_bar_height*d.properties[value_percentage_name]*scale;
							}else{
								return total_bar_height*d.properties[value_percentage_name]*scale/max_y_axis_val;
							}					   
						   })				   
					value.attr("transform", 
					function(d) {    
					   var value_bar_height_offset;					
						// value_percentage_name=precipitation+'_e';					 
						 if(d.properties[value_percentage_name]<1){
								value_bar_height_offset= total_bar_height*d.properties[value_percentage_name]*scale;
							}else{
								value_bar_height_offset= total_bar_height*d.properties[value_percentage_name]*scale/max_y_axis_val;
							}
						 return "translate("+ 
						(map.latLngToLayerPoint(d.LatLng).x+1) +","+ 
						(map.latLngToLayerPoint(d.LatLng).y-Number(value_bar_height_offset)) +")";
					})
				} 
				if(window.hasOwnProperty('d3_circular_culvert')){
					d3_circular_culvert.attr("transform", 
					function(d) {  
						 return "translate("+ 
						(map.latLngToLayerPoint(d.LatLng).x+1) +","+ 
						(map.latLngToLayerPoint(d.LatLng).y) +")";
					})
				}
				  
		   
		  }		//update  
			
		
			//setTimeout(function(){ GEN_change_layer_style_externally(window[dss_app_settings_idot_correlation["app_leaflet_layer"]].usgs_streamflow,{fill:false,stroke:false});}, 100);
					
			
			
		function colorScale(features,expressed){	
		
			//console.log("step1.5");
			//console.log(expressed);
			  var keyArrayToColor={
				"Urban":[
					"#F203FF",
					"#C323FF",
					"#8051FF",
					"#4778FF",
					"#0D9FFF"
			  ],
				"Forest":[
					"#66ff99",
					"#1aff66",
					"#00cc44",
					"#00802b",
					"#003311"
				  ],
			    "Farm":[
					"#fffae6",
					"#fff0b3",
					"#ffe680",
					"#ffdb4d",
					"#ffcc00"
				  ],
				 "Group_A":[
					"#F203FF",
					"#C323FF",
					"#8051FF",
					"#4778FF",
					"#0D9FFF"
				  ],	
				  "Blockage":[
					"#ffe6e6",
					"#ff9999",
					"#ff4d4d",
					"#ff0000",
					"#b30000"
				  ],
				  "rusle_mean":[
					"#ffe6cc",
					"#ffc180",
					"#ff901a",
					"#b35c00",
					"#4d2800"
				  ],
				  "upstream_area":[
					"#ffe6e6",
					"#ff9999",
					"#ff4d4d",
					"#ff0000",
					"#b30000"
				  ],
				   "stc":[
					"#ffe6e6",
					"#ff9999",
					"#ff4d4d",
					"#ff0000",
					"#b30000"
				  ],
				  "sed_area_h":[
					"#0D9FFF",
					"#4778FF",
					"#8051FF",
					 "#C323FF",				  
					"#F203FF"	
				  ],
				 
				  "sed_ratio_n":[
					"#0D9FFF",
					"#4778FF",
					"#8051FF",
					 "#C323FF",				  
					"#F203FF"
				  ],
					"culvert_sed-ratio-n-key":[  //orange to red
					"#fdd0a2",
					"#fdae6b",
					"#FF8E3C", 
					"#e6550d",
					"#a63603"	
				  ],	
						
				   /*
				    "culvert_sed-ratio-n-key":[  //white to purple
					"#dadaeb",
					"#bcbddc",
					"#9e9ac8", 
					"#756bb1",
					"#54278f",	
				  ], 
				   
				  	"culvert_sed-ratio-n-key":[  //green to red
						"#1a9641",
						"#a6d96a",
						"#ffffbf",
						"#fdae61",
						"#d7191c"
				  ], 
				    "culvert_sed-ratio-n-key":[  //pink to red
					"#fcc5c0",
					"#fa9fb5",
					"#f768a1", 
					"#c51b8a",
					"#7a0177"	
				  ],
				 "culvert_sed-ratio-n-key":[  //blue to red
					"#0D9FFF",
					"#4778FF",
					"#8051FF",
					 "#C323FF",				  
					"#F203FF"
				  ], 
				  "culvert_sed-ratio-n-key":[  //yellow to red
					"#fed98e",
					"#fecc5c",
					"#fd8d3c",
					"#f03b20",
					"#bd0026"	//this is yellow to red
				  ],
				   /*
				  "sed_ratio_n":[
					"#ffe6e6",
					"#ff9999",
					"#ff4d4d",
					"#ff0000",
					"#b30000" 
				  ],
				  */
				  "sed_ratio_h":[
					"#0D9FFF",
					"#4778FF",
					"#8051FF",
					 "#C323FF",				  
					"#F203FF"
				  ],
				  "sed_ratio_h_f":[
					"#0D9FFF",
					"#4778FF",
					"#8051FF", 
					 "#C323FF",				  
					"#F203FF"
				  ],
				  "total_blockage":[						  
					"#ffffb2",
					"#fecc5c",
					"#fd8d3c",
					"#f03b20",
					"#bd0026"						  
				  ],
				  
				  
				  
				  
			}
			//console.log("step1.5");
			//console.log(expressed);
			//console.log(keyArrayToColor[expressed]);
			  //create quantile classes with color scale
			  var color = d3.scale.quantile() //designate quantile scale generator
			  .range(keyArrayToColor[expressed]);
			 // console.log(expressed);
			  //build array of all currently expressed values for input domain
			  
			  var domainArray = [];

			  for (var a=0; a<features.length; a++){
				if(features[a].hasOwnProperty("properties")){

					if(typeof(features[a].properties[expressed])!="undefined"){
						domainArray.push(Number(features[a].properties[expressed]));
					}				


				}else{
					
					if(typeof(features[a][expressed])!="undefined"){
						//console.log(Number(features[a][expressed])+"  "+features[a][expressed]);
						domainArray.push(Number(features[a][expressed]));  
					}

					
				}

												
			  }
			  //console.log(domainArray);
			  //pass array of expressed values as domain
			  color.domain(domainArray);
			   var legend_data=[];
			
			   var color_ramp_num=[0];
			   
			   for(var a in color.quantiles()){
				   if(color.quantiles()[a]>1){
					   color_ramp_num.push((color.quantiles()[a]).toFixed(0));
					   
				   }else{
					   color_ramp_num.push((color.quantiles()[a]*100).toFixed(0));					  
				   }
				   
			   }	
			    color_ramp_num.push(100); 
			   //var max = Math.max(...keyArrayToColor[expressed]);
			   //console.log(color_ramp_num);
			   //color_ramp_num.push(max.toFixed(2));	
			   //console.log(max.toFixed(2));
			   //var new_color_array=jQuery.extend(true, {}, keyArrayToColor[expressed]);
			   //new_color_array.unshift("");
			   var new_color_array=[""];
			   for(var i in keyArrayToColor[expressed]){
				   new_color_array.push(keyArrayToColor[expressed][i]);
			   }
			   for(var each_color_index in color_ramp_num){ 
				   legend_data.push([color_ramp_num[each_color_index],new_color_array[each_color_index]]);
			   }
			   //console.log(legend_data);
			   leaflet_legend(legend_data,'<h5>Sedimentation Degree</h5><h6></h6>','',dss_panel_holder_id+' function_panel');
			   $("."+dss_panel_holder_id).css("bottom","26px");
			  
			  return color;	 //return the color scale generator
			};	
		function choropleth(d, recolorMap,expressed){

		  //get data value
		  
		  var value = d.properties[expressed];
		  //if value exists, assign it a color; otherwise assign gray
		  if (value) {
			return recolorMap(value); //recolorMap holds the colorScale generator
		  } else {
			return "#ccc";
		  };
		};			
	}// end of the D3 plotting




/*-----------------------------------------------------------idot_correlation_Functions-------------------------------------------------*/
function idot_culvert_scenario_style_control_by_matching_ppt(event_option_obj,leaflet_layer,style_obj){  // THis function uses parallel structure to visualize usgs_streamflow by the year of built
//API:idot_culvert_scenario_style_control_by_matching_ppt({"class_id":"","matching_value":"","matching_field":""},leaflet_layer,{"pass_filter":""})

		var matching_value=event_option_obj['matching_value'];
		var matching_field=event_option_obj['matching_field'];
		var pass_filter=style_obj['pass_filter'];
		var un_pass_filter=style_obj['un_pass_filter'];
		var filter_value=$("#"+this.id).val();
		var layer=leaflet_layer["_layers"];
		for(var each_element in layer) {
		var feature=layer[each_element]['feature'];

		if(feature.properties[matching_field] == matching_value){
				layer[each_element].setStyle(pass_filter);	
		}else{
			layer[each_element].setStyle( un_pass_filter);
		}
		} // for loop element in in obj
}

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------*/




/*------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
//idot_correlation_scenario_name_control_by_combine_field({'class_name':'','control_field':'','filter':'','input_combination':[]});
function idot_correlation_scenario_name_control_by_combine_field(event_option_obj){  // THis function uses parallel structure to visualize usgs_streamflow by the year of built

var class_name=event_option_obj['class_name'];
var control_field=event_option_obj['control_field'];
var filter=event_option_obj['filter'];
var input_combination=event_option_obj['input_combination'];

var final_combined_scenario_name;


final_combined_scenario_name="";
for(var ic=0;ic<input_combination.length;ic++){
	
	
if(ic==input_combination.length-1){
final_combined_scenario_name+=$("#"+input_combination[ic]).val();
}else{
final_combined_scenario_name+=$("#"+input_combination[ic]).val()+"_";
}//end of if_statment

if($("#"+input_combination[ic]).val()=="null"){
	$("#"+input_combination[ic]).addClass( "invalid_scenario" );	
}else{
	$("#"+input_combination[ic]).removeClass( "invalid_scenario" );
}
}//end of for loop

return final_combined_scenario_name;
}


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

function idot_correlation_decision_tree(data,attNames,expressed){
	//console.log(attNames);
	
	$('#idot_correlation_trees').unbind();
	
	var button_holder=$("#idot_correlation_trees").parent();
	var button='<input class="form-control btn btn-primary dot_panel_txt" id="idot_correlation_trees" value="Analysis Algorithm" style="margin-top: 20px;"  type="button">';
	button_holder.empty();
	button_holder.append(button);
	var data_input=tree_data_parse(jQuery.extend(true, {}, data),attNames,expressed);
		console.log("final_tree_parse_"+data_input.length);
	var config = {
				'trainingSet': data_input, 
				'categoryAttr': 'sedmap_ratio_label', //sex
				'ignoredAttributes': ['sed_area_h','sed_ratio_h','sed_ratio_h_f','sed_ratio_n'],
                'maxTreeDepth': $(".idotculvert_decision_trees_setting_maxtree").val() || 1000,
				'entropyThrehold': $(".idotculvert_decision_trees_setting_entropyThrehold").val() || 0.01,	
		        'num_tree': $(".idotculvert_decision_trees_setting_trees").val() || 500
				
			};
	$('#idot_correlation_trees').click(function() { 
	//$(document).on('click','#idot_correlation_trees',function(){  
						    	
		
		
		if($("#idotculvert_decision_trees").length==0){	
		idot_create_modal_window ("idotculvert_decision_trees",{"title":"J48 Decision Tree","style":"position:absolute; width:80%; height:70%; right:1.5%; top:2%;","no_background":true});
		$("#idotculvert_decision_trees_content").append("<div id='idotculvert_decision_trees_container' class='tree' style='width:9000px; height:"+$( window ).height()*0.5+"; max-height:600px; overflow-x: hidden;direction: rtl; text-align: left;'></div>"); 
		var setting_sets1="<input id='idotculvert_decision_trees_setting_submit' type='button' value='Update' style='width:150px'>  --- "
		+"Max Tree Depth: <input type='text' class='idotculvert_decision_trees_setting_maxtree' name='fname' value='1000'> || "
		+ "Entropy Threhold: <input type='text' class='idotculvert_decision_trees_setting_entropyThrehold' name='fname' value='0.01'> || "
		+"Number of Trees: <input type='text' class='idotculvert_decision_trees_setting_trees' name='fname' value='50' >"
		+"<br><br>";			
		var setting_sets2= " <input id='idotculvert_decision_trees_setting_test' type='button' value='Test' style='width:150px'>  ---  "+
		"Cross-fold:  <input id='idotculvert_decision_trees_setting_crossfold' type='text' value='10' style='width:50px'>  "+
		"|| Testing Results: <input type='text' class='idotculvert_decision_trees_testing_results' name='fname' value='' style='width:400px'><hr>";
		
		$("#idotculvert_decision_trees_content").prepend(setting_sets1+"  "+setting_sets2); 
		 $("#idotculvert_decision_trees_content").height($( window ).height()*0.5);
		
		}else{			
			$("#idotculvert_decision_trees").modal("show");	
	       $("#idotculvert_decision_trees_content").height($( window ).height()*0.5);
		   $( ".modal-backdrop").remove();
		}
		testing_$_updating_events(data_input);
		
		generate_tree(config);
		
		//maxTreeDepth  entropyThrehold
		
		
	});//end of click event
	
	if($("#idotculvert_decision_trees_container").length!=0 && $("#idotculvert_decision_trees").css("display")!="none"){
		testing_$_updating_events(data_input);
		$("#idotculvert_decision_trees_container").empty();
			config['trainingSet']=data_input;	//restore to the pre-modified data (not changed by generating the tree)	
			config['maxTreeDepth']= parseFloat($(".idotculvert_decision_trees_setting_maxtree").val() || 1000) ;
			config['entropyThrehold']=parseFloat($(".idotculvert_decision_trees_setting_entropyThrehold").val() || 0.01);	
			config['num_tree']=parseFloat($(".idotculvert_decision_trees_setting_trees").val() || 500);				
			generate_tree(config);
			
	
	}
	
	function testing_$_updating_events(data_input){
		//var data_input = jQuery.extend(true, {}, input)
		$('#idotculvert_decision_trees_setting_submit').unbind();
		$('#idotculvert_decision_trees_setting_submit').click(function() {
			
			//console.log("final_tree_parse_update"+data_input.length);
			config['maxTreeDepth']= parseFloat($(".idotculvert_decision_trees_setting_maxtree").val() || 1000) ;
			config['entropyThrehold']=parseFloat($(".idotculvert_decision_trees_setting_entropyThrehold").val() || 0.01);	
			config['num_tree']=parseFloat($(".idotculvert_decision_trees_setting_trees").val() || 500);	
			
			config['trainingSet']=data_input;
			$("#idotculvert_decision_trees_container").empty();						
			generate_tree(config);
			//maxTreeDepth  entropyThrehold
			
		});
		$('#idotculvert_decision_trees_setting_test').unbind();
		$('#idotculvert_decision_trees_setting_test').click(function() {				
			config['maxTreeDepth']= parseFloat($(".idotculvert_decision_trees_setting_maxtree").val() || 1000) ;
			config['entropyThrehold']=parseFloat($(".idotculvert_decision_trees_setting_entropyThrehold").val() || 0.01);	
			config['num_tree']=parseFloat($(".idotculvert_decision_trees_setting_trees").val() || 500);			
			//console.log("final_tree_parse_test"+data_input.length); 
			config['trainingSet']=data_input;
			//console.log("final_tree_parse_test"+config1["trainingSet"].length);
			$("#idotculvert_decision_trees_container").empty();	
			training_and_testing(config);
			generate_tree(config);
		});

	}
	
	
	function generate_tree(config){		
		//console.log("final_tree_data");
		//console.log(JSON.stringify(data)); 	
		
		// Building Decision Tree
		var decisionTree = new dt.DecisionTree(config);		
		// Building Random Forest
		var numberOfTrees = 3; 
		var randomForest = new dt.RandomForest(config, numberOfTrees);
       
		// Testing Decision Tree and Random Forest
		//var comic = {person: 'Comic guy', hairLength: 8, weight: 290, age: 38};

		//var decisionTreePrediction = decisionTree.predict(comic);
		//var randomForestPrediction = randomForest.predict(comic);
		// Displaying predictions
		//document.getElementById('testingItem').innerHTML = JSON.stringify(comic, null, 0);
		//document.getElementById('decisionTreePrediction').innerHTML = JSON.stringify(decisionTreePrediction, null, 0);
		//document.getElementById('randomForestPrediction').innerHTML = JSON.stringify(randomForestPrediction, null, 0);		
		// Displaying Decision Tree
		//console.log("treeroot");
		//console.log(decisionTree);  
		//console.log(randomForest); 
		if(!(decisionTree.root).hasOwnProperty('category')){
			document.getElementById('idotculvert_decision_trees_container').innerHTML = treeToHtml(decisionTree.root);
		}else{
			$('#idotculvert_decision_trees_container').append("<h1>Insufficient data for training</h1>")
			console.log("Insufficient data for training");
		}		
		setTimeout(function(){ $('#idotculvert_decision_trees_content').doubleScroll(); }, 1000);
	}
	
	function training_and_testing(config){
		var fulldata = config.trainingSet;
		//console.log("full_length"+fulldata.length);
		//console.log(fulldata);
		var folder_size=$("#idotculvert_decision_trees_setting_crossfold").val() || 10 ;		
		var setting = {
			 "trainning_size":config.trainingSet.length-Math.floor(config.trainingSet.length/folder_size),
			 "testing_size":Math.floor(config.trainingSet.length/folder_size),
			 "corss_folding_dataset":[],
		     "numberOfTrees":$(".idotculvert_decision_trees_setting_trees").val() || 500	,
			 "overall_test":{"correct_predict":0,"wrong_predict":0,"confuse_predict":0, "mis_class":[],"confuse_class":[]},
			
		 };
		//const shuffled = array.sort(() => .5 - Math.random());// shuffle  
        //let selected =shuffled.slice(0,n) ; //get sub-array of first n elements AFTER shuffle
		for(i=0;i<folder_size;i++){
			//console.log(i+" "+folder_size);
			test_data = jQuery.extend(true, {}, fulldata.slice(i*setting['testing_size'],(i+1)*setting['testing_size']));
			train_data = fulldata.slice(0,i*setting['testing_size']).concat(fulldata.slice((i+1)*setting['testing_size'], fulldata.length));
			//console.log(train_data);
			//console.log(test_data);
			var config_each = jQuery.extend(true, {}, config);
			
			var each_prediction_result={"correct_predict":0,"wrong_predict":0};
			config_each['trainingSet']=train_data;
			var randomForest = new dt.RandomForest(config_each, parseFloat($(".idotculvert_decision_trees_setting_trees").val() || 500)	);	
			var prediction_except = ["Low-Clean","Clean-Low","Low-med","Low-med","high & very high-med","med-high & very high"];			
			//setting["corss_folding_dataset"].push({"correct_predict":0,"wrong_predict":0});			
			for(n in test_data){
				var real_result = test_data[n][config_each["categoryAttr"]];
				delete test_data[n][config_each["categoryAttr"]];
				//console.log(test_data[i]);
				var randomForestPrediction = randomForest.predict(test_data[i]);
				var major_prediction=[0];
				for(var each_key in randomForestPrediction){
					if(randomForestPrediction[each_key]>major_prediction[0]){
						major_prediction[0]=randomForestPrediction[each_key];
						major_prediction[1]=each_key;
					}
				}
				//console.log(real_result+"  "+major_prediction[1]);
				if(real_result==major_prediction[1]){
					each_prediction_result["correct_predict"]+=1;
					setting["overall_test"]['correct_predict']+=1;
				}else{
					if(prediction_except.indexOf((real_result+"-"+major_prediction[1]))==-1 ){
						each_prediction_result["wrong_predict"]+=1;
						setting["overall_test"]['wrong_predict']+=1;
						setting["overall_test"]['mis_class'].push(real_result+"-"+major_prediction[1]);
					}else{
						setting["overall_test"]['confuse_predict']+=1;
						setting["overall_test"]['confuse_class'].push(real_result+"-"+major_prediction[1]);
					}
					
				}
				//console.log(major_prediction[1]);
			}		
			    each_prediction_result["accurcy"]=each_prediction_result["correct_predict"]/(each_prediction_result["wrong_predict"]+each_prediction_result["correct_predict"]);
				
				setting["corss_folding_dataset"].push(each_prediction_result);	
								
			//setting["corss_folding_dataset"].push({"test_data":test_data,"training":train_data});
			//var randomForestPrediction = randomForest.predict(comic);
		} 
		    setting["overall_test"]["accurcy_L"]=(setting["overall_test"]["correct_predict"])/(setting["overall_test"]["wrong_predict"]+setting["overall_test"]["correct_predict"]);
			setting["overall_test"]["accurcy_H"]=(setting["overall_test"]["correct_predict"]+setting["overall_test"]["confuse_predict"])/(setting["overall_test"]["wrong_predict"]+setting["overall_test"]["correct_predict"]+setting["overall_test"]["confuse_predict"]);
			//console.log(setting["corss_folding_dataset"]);
			//console.log(setting["overall_test"]);
			var results="Accuracy:"+(setting["overall_test"]["accurcy_L"]*100).toFixed(3)+" - "+(setting["overall_test"]["accurcy_H"]*100).toFixed(3)+"% , Incorrectly predicted:"+setting["overall_test"]['wrong_predict'];
				$(".idotculvert_decision_trees_testing_results").val(results);
	}
	
	
		


		// Recursive (DFS) function for displaying inner structure of decision tree
		function treeToHtml(tree) {
			
			// only leafs containing category
			if (tree.category) {
				return  ['<ul>',
							'<li>',
								'<a href="#">',
									'<b>', tree.category, '</b>',
								'</a>',
							'</li>',
						 '</ul>'].join('');
			}
			
			return  ['<ul>',
						'<li>',
							'<a href="#">',
								'<b>', idot_correlation_parameter_coverter[tree.attribute], ' ', tree.predicateName, ' ', tree.pivot, ' ?</b>',
							'</a>',
							'<ul>',
								'<li>',
									'<a href="#">yes</a>',
									treeToHtml(tree.match),
								'</li>',
								'<li>', 
									'<a href="#">no</a>',
									treeToHtml(tree.notMatch),
								'</li>',
							'</ul>',
						'</li>',
					 '</ul>'].join('');
		}

			function tree_data_parse(data,attNames,expressed){
				    console.log("tree_id "+expressed);
					var pcpdata=[];
					//sed_ratio_h
					//console.log(paracor_data);
					//console.log(attNames);
					//console.log("treedata"); 
					//console.log(data);
					
					var data_input = data.features || data;
					//console.log("before_parse_length "+data_input.length);
					//var data_input_copy=jQuery.extend(true, {}, data_input);
					//console.log(data_input);
					//data_input.forEach(function(d){
						
					for (var i in data_input){
							var d = data_input[i];
					  //attribute names are derived from properties of the first json object
					  // so that the dropdown list could be populated					  
					    var temp={};
						//var temp = jQuery.extend(true, {}, temp_o);
						//var temp1=jQuery.extend(true, {}, temp); 
						for (var i in attNames){ 
							//console.log(d.properties);
							//console.log(attNames[i]);							
							var dp=d.properties || d;
							if(dp.hasOwnProperty(attNames[i])){								
								temp[attNames[i]]=Number(dp[attNames[i]]);								
							}									
						}
						
							var di=d.properties || d;							
						
						
						
						var action_based_on_exp={
							"sed_ratio_h":function(){
								temp["sedmap_ratio_label"]=class_label_generate(di[expressed]);
							},
							"sed_ratio_n":function(){
								temp["sedmap_ratio_label"]=class_label_generate(di[expressed]*100);
							}
						}
						action_based_on_exp[expressed]();


						pcpdata.push(temp);
						//d.properties=temp1=jQuery.extend(true, {}, temp1); 
					  
					  /*
					  for (var k in d.properties){							
						  if(attNames.indexOf(k) == -1){
							 delete d.properties[k] 
						  }
						  k=paracor_title[k];
							}	*/					
						 
						//tempProperties = d.properties;
						//console.log(temp1);
					  
					}//); //end of o each
					
					//console.log('after_parsed__'+pcpdata.length);
					return pcpdata;
					
					function class_label_generate(value){

						class_label = 
							    value > 60  ? 'high & very high' :           
								value > 30  ? 'med' :								
								value > 10   ? 'Low' :
										  "Clean";
						return class_label;
					}
				}//end of data parse	
}




function idot_create_modal_window (modal_id,options){

	
	if($( "body" ).has( "#"+modal_id ).length==0){
		console.log("KH2");
		var modal_title=options['title'];
		var style_window=options['style'];
		var style_window=options['style'];
	var append_model='<div id="'+modal_id+'"  class="modal fade"><div class="modal-dialog"  style="'+style_window+'"><div class="modal-content" ><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h5 class="modal-title">'+modal_title+'</h5></div><div class="modal-body" id="'+modal_id+'_content"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>';
	$("body").append(append_model);
		
		  $("#"+modal_id).draggable({
      handle: ".modal-header"
          });
		   $("#"+modal_id).modal("show");
		  
	}else{
		 $("#"+modal_id).modal("show");
	}
	
}


// JavaScript Document// JavaScript Document