/*$('head').append([		
		'<script src="assets-examples/js/som_package/som_backage/som.js"></script>',	
	].join('\n'));*/
  
	/*
var feature_oprtions={
	"culvert_serious2":{
		"key":"culvert_sed-ratio-n-key",
		"data_url":'data/new_culvert_analysis_sentivity_done.json',
		"features":	['culvert_sed-ratio-n-key','culvert_stc-n','up2500_100mb_ag-m','up2500_100mb_grass','up2500_100mb_forest','fl_ws_area-km','q100'],  
		// original "features":	['culvert_sed-ratio-n-key','culvert_stc-n','up2500_100mb_ag-m','up2500_100mb_grass','up2500_100mb_forest','up2500_100mb_area_km'], 
		//,"features":	['culvert_stc-n','fl_ws_area-km','up2500_100mb_ag','up2500_100mb_grass','up2500_100mb_forest','fl_100mb_urban','up2500_100mb_coniferous','up2500_100mb_channel-density'], 
		"log_ln_field":["fl_ws_area-km",'up2500_100mb_channel-density','fl_100mb_urban','up2500_100mb_coniferous',],  //'culvert_stc-n'
		"optimal_neuron":[8,8]
		},				
	};  
	console.log('aaa');*/
	
	
function culvert_vis_analysis_som(feature_oprtions_input){	
	
	var margin = { 
		top: 50,
		right: 50,
		bottom: 50, 
		left: 50
	};		
	
	var x=$("#maprows").val() || Number($(".maprows_columns").val()),
		y=$("#mapcolumns").val() || Number($(".maprows_columns").val()),
		initialrate1=$("#initialrate").val() || 0.001,
		iteration1=$("#iteration_rate").val()|| 10000 ,
		neighbour_distance=$("#neighbour_distance").val() || 1,
		initial_distance=$("#initial_radius").val() || 1,
		initial_radius=$("#initial_radius").val() || 100;		
		
		
		var som_results = trigger_som(x,y,initialrate1,10000,10,initial_distance,feature_oprtions_input); 
		return som_results;
		/*console.log(som_results);
		$.getJSON( "assets-examples/js/som_package/som_good_cluster/cluster4_10x10.json", function(data) { 
			console.log(data);
			return data;
		});*/
		
		
		
		/*if($("#chart").find("svg").length==0){
			 console.log($("#chart").find("svg").length);
			 trigger_som(x,y,initialrate1,iteration1,neighbour_distance,initial_radius,feature_oprtions_input); 
		 }*/
}	
	
	function trigger_som(x,y,initialrate,iteration,neighbour_distance,initial_radius,input_data_setting){
		//$.getJSON( "http://s-iihr32.iihr.uiowa.edu:8081/som/som.sev?x="+parseInt(x)+"&y="+parseInt(y)+"&initialrate="+Number(initialrate)+"&iteration="+parseInt(iteration), function(data) {  
				
				var clustered_data={}, result = train_som (parseInt(x),parseInt(y),Number(initialrate),parseInt(iteration),Number(neighbour_distance),Number(initial_radius),input_data_setting);
				var clustered_data_init_settings =	{
						"width":$("#chart").width(),  // 850
						"height": $("#chart").height(),  // 350
						"MapColumns":x, //30
						"MapRows":y,  //20
						"data":result["index_list"], 					
						"neighbour":result["neighbour_group"],
						"variables":result["features"],
						"raw_data":result["raw_data"],
						"join_key":result["join_key"],
						"sample_to_cluster": result["sample_to_cluster"] 
					};
					
				
				var som_pcp_data = prepare_som_pcp_data({
					"data_input":clustered_data_init_settings["raw_data"],
					"sample_to_cluster":clustered_data_init_settings["sample_to_cluster"],
					"join_key":clustered_data_init_settings["join_key"],
				});
					
				var som_pcp_data_mean_for_edge_bundle=prepare_edge_bundle_cluster_calculate_mean_by_class({
					'target_class_name':"cluster_id",'skip_field':["class"],'data_input':som_pcp_data});
					//console.log(som_pcp_data_mean_for_edge_bundle); 	
				
				$(".export_som_class").unbind(); 
				$(".export_som_class").click(function(){
					var url = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(init_settings));   
								window.open(url, '_blank');
								window.focus();	
					});
				
				return {"edge_bundle_data":som_pcp_data_mean_for_edge_bundle, "som_pcp_data":som_pcp_data, "som_main_setting":clustered_data_init_settings  }
				//console.log(data_color);
				//survey_color_ramp(init_settings,init_settings["MapColumns"],init_settings["MapRows"]);
		}
		
	function train_som(x,y,initialrate,iteration,distance,initialradius,input_data_setting){  			
			var jsondata_url=input_data_setting['data_url'];	
			var json_properties=input_data_setting["features"];	
			var key=input_data_setting["key"]; 	
			var final_result;
			var log_ln_field=input_data_setting['log_ln_field'] || [];
			// log_ln_field:["fl_ws_area-km",'culvert_stc-n','up2500_100mb_channel-density',fl_100mb_urban]
			//var jsondata = require('data/culvert_sedmap_liz.json'); 
			if(typeof(jsondata_url)=="object"){
				//console.log('object call');
				
				let nor_data=data_normalization(jsondata_url,json_properties,log_ln_field);						
				final_result=handle_data_som_training(nor_data,json_properties,key);
				//console.log(final_result);
				return final_result;
			}
			if(typeof(jsondata_url)=="string" && jsondata_url.includes("json")){
				//console.log('ajax call'); 
				$.ajax({
					  url: jsondata_url,
					  dataType: 'json',
					  async: false,
					  //data: myData,
					  success: function(data) {
							//console.log(data);
							let nor_data=data_normalization(data,json_properties,log_ln_field);
							final_result=handle_data_som_training(data,json_properties,key);
							//console.log(final_result);
							
					  }//success
					});
				return final_result; 
			}
			//setInterval(function(){ console.log(sed_degree); }, 3000);		
			//console.log('start', +new Date());
			//console.log('end', +new Date());
			//Look at the internal structure of the SOM
			//console.log('SOM', util.inspect(som.traineeIndex, false, 4)); 
			//console.log(som.traineeIndex); 
			//util.inspect(som.traineeIndex, false, 8)			
			function handle_data_som_training(data,json_properties,key){
				//console.log({ 'iterationCount': iteration, 'width': x, 'height': y, 'initialLearningRate':initialrate, 'initialRadius':initialradius})
				var som = new Som({features: input_data_setting['features'], iterationCount: iteration, width: x, height: y, initialLearningRate :initialrate, initialRadius:initialradius});
				var final_result;
				som.init({});
				var jsondata = data;
						var json_outputs={};
						var data_feature=data["features"] || data;
						for(var i in data_feature){						
							var each_item=data_feature[i]["properties"] || data_feature[i];
							var text_features_training="";
							//console.log(each_item["site_id"]);
							var each_site_id = each_item[key];
							
							for(var eachfeature in json_properties){
								text_features_training+="'"+json_properties[eachfeature]+"':Number("+(each_item[json_properties[eachfeature]])+"),"								
							} 		
							text_features_training="som.train('"+each_site_id+"',{"+text_features_training+"})";
							
							//console.log(text_features_training);
							eval(text_features_training);
							json_outputs[each_site_id]=each_item["sed_ratio_h"];
												
						} //end of for loop
						
					return result_logging(som,json_outputs,distance,data,key)			
			}
			
			function data_normalization(data,json_properties,log_ln_field){ 	
			
				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 json_properties){
									
									each_item[json_properties[eachfeature]]
									
									if( log_ln_field.indexOf(json_properties[eachfeature])!=-1){
												//let value = 
												//-Infinity
											if(Math.log10(Number(each_item[json_properties[eachfeature]]))==-Infinity){
												each_item[json_properties[eachfeature]]=0; 
											}else{
												each_item[json_properties[eachfeature]]=Math.log10(Number(each_item[json_properties[eachfeature]])); 									
											}																	
									}								
									if(!max_value_set.hasOwnProperty(json_properties[eachfeature])){
										max_value_set[json_properties[eachfeature]]=-99999;
										min_value_set[json_properties[eachfeature]]=99999;
										dataset_for_stats[json_properties[eachfeature]]=[];
									}
									dataset_for_stats[json_properties[eachfeature]].push(Number(each_item[json_properties[eachfeature]]))
									if(Number(each_item[json_properties[eachfeature]])>=max_value_set[json_properties[eachfeature]]){
										max_value_set[json_properties[eachfeature]]=Number(each_item[json_properties[eachfeature]]);									
									}
									if(Number(each_item[json_properties[eachfeature]])<=min_value_set[json_properties[eachfeature]]){
										min_value_set[json_properties[eachfeature]]=Number(each_item[json_properties[eachfeature]]);									
									}								
									//text_features_training+="'"+json_properties[eachfeature]+"':Number("+(each_item[json_properties[eachfeature]])+"),"								
								}
						} //end of for loop
						for(var eachfeature in json_properties){
							let eachfield = json_properties[eachfeature];
							stats_set[eachfield]={  
								"mean": getMean(dataset_for_stats[eachfield]),
								"std": getSD(dataset_for_stats[eachfield]) };
						}				
				//console.log("get_max_value");
								
				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 json_properties){							
									
										//each_item[json_properties[eachfeature]]=(each_item[json_properties[eachfeature]]-stats_set[json_properties[eachfeature]]["mean"])/stats_set[json_properties[eachfeature]]["std"];
										if(json_properties[eachfeature]=="up2500_100mb_coniferous"){ 
											//console.log('('+Number(each_item[json_properties[eachfeature]])+'-'+min_value_set[json_properties[eachfeature]]+')/('+max_value_set[json_properties[eachfeature]]+'-'+min_value_set[json_properties[eachfeature]]+')');
										}
										if(json_properties[eachfeature]=="culvert_sed-ratio-n-key"){ 
											//stay unchanged
											temp_for_each[json_properties[eachfeature]]=each_item[json_properties[eachfeature]];
										}else{
											temp_for_each[json_properties[eachfeature]]=(Number(each_item[json_properties[eachfeature]])-min_value_set[json_properties[eachfeature]])/(max_value_set[json_properties[eachfeature]]-min_value_set[json_properties[eachfeature]]);
											//each_item[json_properties[eachfeature]]=temp_for_each[json_properties[eachfeature]];
										}
										//console.log(each_item);										  									
																			
										/*}else{
											console.log("let");
										}*/									
									//text_features_training+="'"+json_properties[eachfeature]+"':Number("+(each_item[json_properties[eachfeature]])+"),"								
								}
							normalized_results.push(temp_for_each);
						} //end of for loop				
				return normalized_results;				
			}			
			
			function result_logging(som,sed_degree,distance,data,key){
				//console.log('sed_degree');
				//console.log(distance); 			
				var res=som.traineeIndex;
				var cout=0
				var indexing_result={},
				  neighbors_result={},
				  neighbors_best={},
				  sample_to_cluster={};
				  
				
				for (var each in res){
					//console.log(res[each]);
					var index="i"+res[each].x+"-"+res[each].y; 
					if(!indexing_result.hasOwnProperty(index)){
									indexing_result[index]=[];
						};
					indexing_result[index].push( {"id":each,"x":res[each].x,"i":res[each].i,"y":res[each].y,"sed":sed_degree[each],"weight":res[each]["weights"]});				
					
					//let temp_neighbors=som.neighbors(each,distance),temp_neighbors_res={};
					//for(each_neighbor in temp_neighbors){
						//let tem_index="i"+temp_neighbors[each_neighbor]["x"]+"-""
						//distance: 1.4642293904129806, x: 0, y: 1
					//}
					
					neighbors_result[index]=som.neighbors(each,distance);
					sample_to_cluster[ each.toString()]	= index;	 		
					}					 
					cout++;					
					//console.log(indexing_result["neighbors_result"])
					return indexing_result={"index_list":indexing_result,"neighbour_group":neighbors_result,"features":input_data_setting['features'],"raw_data":data,"join_key":key,"sample_to_cluster":sample_to_cluster}; 
					//return {"index_list":indexing_result,"neighbour_group":neighbors_result};  				
				}		 
	};  //end of train_som function
	
	
	
	
	function prepare_som_pcp_data(options){	
				
		var data_input=options['data_input'], data_input_cluster=options['sample_to_cluster'], join_key=options['join_key'];
		for(var each in data_input){
			data_input[each]["cluster_id"]=   data_input_cluster[data_input[each][join_key]] //get cluster id of each sample
		}
		return  data_input;
	}
	
	function prepare_edge_bundle_cluster_calculate_mean_by_class(options){		
		
			var target_class_name=options['target_class_name'], skip_field =options['skip_field'], data_input=options['data_input'];
			var collecting_data_for_each_class={};
			data_input.map(function(x,i){
				if(!collecting_data_for_each_class.hasOwnProperty(x["cluster_id"])){
					collecting_data_for_each_class[x["cluster_id"]]={ "data":{},"mean":{},"std":{},"range":{},"cluster_to_full_data":[]}
				}
				collecting_data_for_each_class[x["cluster_id"]]["cluster_to_full_data"].push(x);
				for(var field_name in x){
					let field_value=x[field_name];					
					if(field_name!=target_class_name && skip_field.indexOf(field_name)==-1){  /*exclude cluster name and other unwanted field*/
						if(!collecting_data_for_each_class[x["cluster_id"]]["data"].hasOwnProperty(field_name)){
						collecting_data_for_each_class[x["cluster_id"]]["data"][field_name]=[];		/*defining the array for storing each field further statistical analysis*/
						}	
						if(!isNaN(field_value)){
							collecting_data_for_each_class[x["cluster_id"]]["data"][field_name].push(field_value);	/*collecting field value in an array for further statistical analysis*/
						} }
				}
			});			
			
			
				for(var class_name in collecting_data_for_each_class){				
								let each_class_data = collecting_data_for_each_class[class_name];
								//console.log(each_class_data);	
								for(var each_field_name in each_class_data['data']){
									let each_data_array = each_class_data['data'][each_field_name];
									//console.log(each_data_array);
									//console.log(each_field_name);
									if(typeof(each_data_array)!='undefined'){
										each_class_data["mean"][each_field_name]=each_data_array.map(function(x,i,arr){return x/arr.length}).reduce(function(a,b){return a + b}); 
										each_class_data["std"][each_field_name]=Math.sqrt(each_data_array.reduce(function (sq, n) {
																						return sq + Math.pow(n - each_class_data["mean"][each_field_name], 2);
																					}, 0) / (each_data_array.length - 1)); 
										each_class_data["range"][each_field_name]=each_data_array.reduce(function(a, b) {return Math.max(a, b);}) - each_data_array.reduce(function(a, b) {return Math.min(a, b);});	
										each_class_data["sample_size"]=each_data_array.length;  
									}														
									/*iterate each field of valuse (array) to calculate mean value for cluster (used for edge bundling)*/
								}
								
							};	 		
							
					return { "class":target_class_name,"cluster_info":collecting_data_for_each_class};
			
			
			
			//var mean = [7,14,21].map(function(x,i,arr){return x/arr.length}).reduce(function(a,b){return a + b});			
			//javascript get mean			
		}
	
	
	
	
	function culvert_vis_analysis_som__draw_edgebundle_pcp(options){
		window['pcp_plot_option']=options;
		var edge_bundle_data = options['edge_bundle_data'],		
		pcp_container_id = options['pcp_container_id'];
		
		var pcp_input_data=order_and_select_field_for_pcp(options['som_pcp_data'],options['som_main_setting']),
		recolorMap=options['recolorMap'],		
		sample_to_cluster=options['som_main_setting']['sample_to_cluster'];
		
		$(pcp_container_id).empty(); 
		var pcp_id=pcp_container_id+"_plot";		
		$(pcp_container_id).append("<div id='"+pcp_id.replace("#","")+"'  class='parcoords' style='height:"+$(pcp_container_id).parent().height()+"px;width:"+($(pcp_container_id).width()+40)+"px'></div>");
				
		//d3.parcoords()(pcp_container_id).data(pcp_input_data).clusterdata(edge_bundle_data).color(function(d) {								  //if value exists, assign it a color; otherwise assign gray
		$(".legend_container").empty();
		
		let highlight_mode=$("#pcp_forms").val() || "edge-bundling";
		
		if(highlight_mode=="edge-bundling"){
		
			var type_of_pcp="assets-examples/js/som_package/d3.parcoords_edgebundling.js"; 
			$.getScript( type_of_pcp, function( data, textStatus, jqxhr ){				
					setTimeout(function(){ 							
					var join_key = options['som_main_setting']['join_key'],								
					culvert_key_to_color=options["culvert_id_to_cluster_color"];								
			
					window["idot_correlation_data"]["pcp"][pcp_id] = d3.parcoords()(pcp_id).data(pcp_input_data).clusterdata(edge_bundle_data).color(function(d) {								  //if value exists, assign it a color; otherwise assign gray
												//return recolorMap( edge_bundle_data['cluster_info'][d['cluster_id']]['mean']['culvert_sed-ratio-n-key'])												
													
													if(typeof (culvert_key_to_color)!='undefined'){	
														return culvert_key_to_color[d[join_key]] || "#d3d3d3";
													}			
													
												
												
												//return recolorMap( d['culvert_sed-ratio-n-key'])									
											}).render().brushable().on("brush", function(items) {
											
															var key = 'culvert_sed-ratio-n-key';
															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]))){
															 try {
															  selected_cluster_to_individual+= ","+window["idot_correlation_data"]['parced_data_averging_id_cluster'][String(d[key])].join(",");													 
																}
																catch(error) {
																  console.log(error);
																}
															 
															 }//accumlting clustering id	
															return d[key]; //selected value from brushing (non-cluster case)											
														  });  																			  
														
														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.01).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.idot_correlation_data.hasOwnProperty('som')){
															window.idot_correlation_data.som["#pie_contain5"].style("opacity", 0.11).filter(function(d){
																//console.log(d['som_coordinate']);
																let selected_cluster=selected.map(function(d) {
																	return sample_to_cluster[d];
																	 }); 
																return selected_cluster.indexOf(d['som_coordinate'])>-1 ||  selected_cluster.indexOf(("i"+d['j']+"-"+d['i']))>-1;																 
																	  }).style("opacity", 1);	
														}
														
													
											
											}); //end of brush
											//window['som_pcp'].clusterdata(cluster_mean_info);								
										
										options['som_main_setting']['pcp_som_dom']=window["idot_correlation_data"]["pcp"][pcp_id];
										pcp_label_conversion_som($("#pcp_real_data_vs_normal").val());
										
										//$(".shadows").css("background-color", "#B2B2B2");
										$("#pcp_plot_contain5_plot").css("background-color", "#B2B2B2"); //more area gery than the previous line
										 
										
										$(".shadows").height(Number($(".shadows").css("margin-top").replace("px",""))+$(".shadows").height()+10);
										$(".shadows").css("margin-top",0);
										//#C6C6C6
				}, 1000);//end of set time out
				});
		}
		if(highlight_mode=="normal"){
			console.log("normal");
			var type_of_pcp="assets/js/leaflet_extension/d3.parcoords.js";
			
			$.getScript( type_of_pcp, function( data, textStatus, jqxhr ){				
					setTimeout(function(){ 							
					var join_key = options['som_main_setting']['join_key'],								
					culvert_key_to_color=options["culvert_id_to_cluster_color"];								
			
					window["idot_correlation_data"]["pcp"][pcp_id] = d3.parcoords()(pcp_id).data(pcp_input_data).color(function(d) {								  //if value exists, assign it a color; otherwise assign gray
												//return recolorMap( edge_bundle_data['cluster_info'][d['cluster_id']]['mean']['culvert_sed-ratio-n-key'])												
													
													if(typeof (culvert_key_to_color)!='undefined'){	
														return culvert_key_to_color[d[join_key]] || "#d3d3d3";
													}		
												
												//return recolorMap( d['culvert_sed-ratio-n-key'])									
											}).render().brushable().on("brush", function(items) {
											
															var key = 'culvert_sed-ratio-n-key';
															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]))){
															 try {
															  selected_cluster_to_individual+= ","+window["idot_correlation_data"]['parced_data_averging_id_cluster'][String(d[key])].join(",");													 
																}
																catch(error) {
																  console.log(error);
																}
															 
															 }//accumlting clustering id	
															return d[key]; //selected value from brushing (non-cluster case)											
														  });  																			  
														
														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.01).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.idot_correlation_data.hasOwnProperty('som')){
															window.idot_correlation_data.som["#pie_contain5"].style("opacity", 0.11).filter(function(d){
																//console.log(d['som_coordinate']);
																let selected_cluster=selected.map(function(d) {
																	return sample_to_cluster[d];
																	 }); 
																return selected_cluster.indexOf(d['som_coordinate'])>-1 ||  selected_cluster.indexOf(("i"+d['j']+"-"+d['i']))>-1;																 
																	  }).style("opacity", 1);	
														}
														
													
											
											}); //end of brush
											//window['som_pcp'].clusterdata(cluster_mean_info);								
										
										options['som_main_setting']['pcp_som_dom']=window["idot_correlation_data"]["pcp"][pcp_id];
										pcp_label_conversion_som($("#pcp_real_data_vs_normal").val());
										
										//$(".shadows").css("background-color", "#B2B2B2");
										$("#pcp_plot_contain5_plot").css("background-color", "#B2B2B2"); //more area gery than the previous line
										 
										
										$(".shadows").height(Number($(".shadows").css("margin-top").replace("px",""))+$(".shadows").height()+10);
										$(".shadows").css("margin-top",0);
										//#C6C6C6
				}, 1000);//end of set time out
				});
		}
		console.log(type_of_pcp);
		
		
		
	
		function order_and_select_field_for_pcp(row_data_with_cluster,init_settings_input){
			
			//return {"edge_bundle_data":som_pcp_data_mean_for_edge_bundle, "som_pcp_data":som_pcp_data, "som_main_setting":clustered_data_init_settings  }
		
			if(!window["idot_correlation_data"].hasOwnProperty("som")){
				window["idot_correlation_data"]["som"]={};
			}
			
			var final_result=[];
			for(var each_item_index in row_data_with_cluster){
					let each_item=row_data_with_cluster[each_item_index];
					let temp_row={};
				
				
				
				temp_row[init_settings_input["join_key"]]=each_item[init_settings_input["join_key"]];
				//console.log(init_settings_input["variables"]);
				for (var each_field_index in init_settings_input["variables"]){
					let each_field = init_settings_input["variables"][each_field_index];					
					//console.log(init_settings_input["variables"]);
					//console.log(each_field+"   "+init_settings_input["variables"].indexOf(each_field));
					if(init_settings_input["variables"].indexOf(each_field)!=-1 && each_field!=init_settings_input["join_key"] && each_field!="cluster_id"){
						//delete each_item[each_field];
						temp_row[each_field]=each_item[each_field];
					}			
				}
				temp_row['cluster_id']=each_item['cluster_id'];
				 if(each_item.hasOwnProperty('landform_region')){
					temp_row['landform_region']=each_item['landform_region'];
				}
				final_result.push(temp_row);
			}
			return final_result;
			}			
	}

	function culvert_vis_analysis_som__draw_som_grids(options){			
			var gridData = prapare_som_grid_data(options);  
			draw_d3_map(gridData,options);	
			
			function prapare_som_grid_data(options){
				let som_container_id = options['som_container_id'],
				MapColumns=options['som_main_setting']["MapColumns"],
				MapRows=options['som_main_setting']["MapRows"];				
				
				//https://bl.ocks.org/cagrimmett/07f8c8daea00946b9e704e3efcbd5739
				let grid_data = new Array();
				var xpos = 1, ypos=1, width =($(som_container_id).width()-20)/MapColumns, height=($(som_container_id).height()-20)/MapRows;
				for (var column  = 0; column < MapColumns; column++) {
					grid_data.push( new Array() );
					
					// iterate for cells/columns inside rows
					for (var row = 0; row < MapRows ; row++) {
						grid_data[column].push({
							x: xpos,y: ypos,width: width,height: height, som_coordinate:"i"+column+"-"+row 
						})
						// increment the x position. I.e. move it over by 50 (width variable)
						xpos += width;
						}
						// reset the x position after a row is complete
						xpos = 1;
						// increment the y position for the next row. Move it down 50 (height variable)
						ypos += height; 
				}
				return grid_data;
			}
			
			function draw_d3_map(gridData,options){			
				var som_container_id = options['som_container_id'],	
				som_main_setting = options['som_main_setting'],
				edge_bundle_data=options['edge_bundle_data'],
				recolorMap=options['recolorMap'],		
				sample_to_cluster=options['som_main_setting']['sample_to_cluster'];
			
						
				$(som_container_id).empty(); 
				// I like to log the data to the console for quick debugging
				//console.log(gridData);
				var grid = d3.select(som_container_id)
					.append("svg")
					.attr("width",$(som_container_id).width()-0) 
					.attr("height",$(som_container_id).height()-0);
				var row = grid.selectAll(".row")
					.data(gridData)
					.enter().append("g")
					.attr("class", "row");
				var column = row.selectAll(".square")
					.data(function(d) { return d; })
					.enter().append("rect")
					.attr("class","square")
					.attr("x", function(d) { return d.x; })
					.attr("y", function(d) { return d.y; })
					.attr("width", function(d) { return d.width; })
					.attr("height", function(d) { return d.height; })
					.style("fill", function(d) { 
							//console.log(d.som_coordinate);
							if(edge_bundle_data["cluster_info"].hasOwnProperty(d.som_coordinate)){								
								let color = recolorMap(edge_bundle_data["cluster_info"][d.som_coordinate]['mean']['culvert_sed-ratio-n-key']);
								
								return color;
							}else{
								return "#FFF";
							}
							 })
					.style("stroke", "#222")
					//.on("mouseover", mover)
			.on("mouseout", som_mout)
			.on("click", som_clicker);
													
				window["idot_correlation_data"]['som'][som_container_id]=column;
				
				row.selectAll("text")
					.data(function(d) { return d; })
					.enter()
					.append("text")					
					.attr("x", function(d) { return d.x+(d.width)/4; })
					.attr("y", function(d) { return d.y+(d.height)/2; })
					.attr("dy", ".35em")
					.attr("pointer-events", "none")
					.text(function(d) {
						
						if(edge_bundle_data["cluster_info"].hasOwnProperty(d.som_coordinate)){
							return edge_bundle_data["cluster_info"][d.som_coordinate]['data']['culvert_sed-ratio-n-key'].length; 
						}
					});	
				
				
				function som_mout(d) { 
					var el = d3.select(this)
					   .transition()
					   .duration(100)
					   .style("stroke", "black")
					   .style("stroke-width", 1);				  
				  //$("#chart_info").html(""); 
				};
				function som_clicker(d) {
					var el = d3.select(this)
					.transition()
					.duration(10)		  
					.style("stroke", "red")
					.style("stroke-width", 5);	
					//console.log(d);					
					
					if(options['som_main_setting'].hasOwnProperty('pcp_som_dom') ){
						//console.log(d['som_coordinate']);
						let highlight_list = edge_bundle_data["cluster_info"][d['som_coordinate']]['cluster_to_full_data'];					
						//console.log(highlight_list); 
						options['som_main_setting']['pcp_som_dom'].highlight(highlight_list);
					}
					
					if(window.hasOwnProperty('d3_circular_culvert')){	
								let selected=[];
								for(var each_key in sample_to_cluster){
									if(sample_to_cluster[each_key]==d['som_coordinate']){
										selected.push(each_key);
									}
								}
								window['d3_circular_culvert'].style("opacity", 0.01).filter(function(d) {
									//console.log(selected);
									//console.log(d.properties['culvert_sed-ratio-n-key']);
									return selected.indexOf(d.properties['culvert_sed-ratio-n-key']) > -1;  //if there it is in the slected  value
											}).style("opacity", 1);
								}					
				}				
				$(som_container_id).append('<button type="button" id="som_dehighlight_all" class="btn btn-primary">Default View</button>');
				$("#som_dehighlight_all").click(function() {
					if(options['som_main_setting'].hasOwnProperty('pcp_som_dom') ){
						options['som_main_setting']['pcp_som_dom'].unhighlight();
					}
				});
				
			}//end of draw_d3-map_grid
		}//end of draw som grid
		
		
		function culvert_vis_analysis_som__draw_som_hex(options){
			
			//input_setting_data,MapColumns,MapRows
			let som_container_id = options['som_container_id'],
			input_setting_data = options['som_main_setting'],
			MapColumns=options['som_main_setting']["MapColumns"],
			MapRows=options['som_main_setting']["MapRows"];	
			//console.log(som_container_id);
			
			//var c = e.getContext('2d');
					var color_matrix=[];
					var width=50;
					var height=50;
				//var color = document.getElementById("color");
					if($("#color_ramp_display").length==0){
					$('#color_ramp_display').remove();
					}
					//$('body').append('')
					 
					var canvas = document.getElementById('color_ramp_display');
							canvas.crossOrigin="anonymous";
					var context = canvas.getContext("2d");
					 
					var imageObj = new Image();
					//console.log(imageObj.length);
					imageObj.onload = function(){
						context.drawImage(imageObj, 0, 0);	
						//console.log("color_data");
						var color_matrix=color_to_cell_mapping(context,input_setting_data,MapColumns,MapRows);
						create_hex_plot(options,color_matrix,som_container_id);
						prepare_som_pcp_data_add_color(options,color_matrix,som_container_id);
						dot_representation_som_special(options,color_matrix,som_container_id);
						export_cluster (options); 
					};
					imageObj.src = $("#color_ramp_select").val();
			
					function color_to_cell_mapping(context,init_settings,MapColumns,MapRows){
						var data_color=[];
						var counter=0
						//console.log(MapColumns+"--"+MapRows);
						//console.log(input_data);
								//console.log(init_settings["data"]);				
							for (i = 0; i < MapColumns; i++) {
								 //for (j = MapRows; j >=0 ; j--) {
								for (j = 0; j < MapRows; j++) {						
										var index="i"+i+"-"+j;
										//console.log("rgb("+canvasColor[0]+","+canvasColor[1]+","+canvasColor[2]+")")
										  //console.log(index);
										var canvasColor=context.getImageData(parseInt(j/MapRows*height),parseInt(i/MapColumns*width), 1, 1).data;
										var color_result="rgb("+canvasColor[0]+","+canvasColor[1]+","+canvasColor[2]+")"						  
										 if(init_settings["data"].hasOwnProperty(index)){ 						 
											 data_color.push([color_result,index,"node"]);							 
										 }else{
											 data_color.push([color_result,index,"empty"]);   //no data 
										 }
									counter++;
								}
							}//end of for loop
							//console.log(data_color);
							return data_color;
					}	
						
				function create_hex_plot(options,data_color,som_container_id){
					
						window["idot_correlation_data"]["som_selected"]=[]; 	
						let init_settings = options ['som_main_setting'],
						edge_bundle_data = options ['edge_bundle_data'];
						
						
						var margin = {
							top: init_settings['MapColumns']>10? 20: 60,
							right: 30,
							bottom: 30,
							left: init_settings['MapColumns']>10? 20: 50
						};
						
						$(som_container_id).empty();
						
						var width=$(som_container_id).width(),
							height=$(som_container_id).height(),
							MapColumns=init_settings["MapColumns"],
							MapRows=init_settings["MapRows"],
							sample_to_cluster=options['som_main_setting']['sample_to_cluster'],
							som_container_id=som_container_id || "#chart";
						//console.log(data_color);
						
						//The maximum radius the hexagons can have to still fit the screen
						//console.log("width: "+width);
						var hexRadius = d3.min([width/((MapColumns + 0.5) * Math.sqrt(3)),
									height/((MapRows + 1/3) * 1.5)]);

						//Set the new height and width of the SVG based on the max possible
						width = MapColumns*hexRadius*Math.sqrt(3);
						heigth = MapRows*1.5*hexRadius+0.5*hexRadius;
						//console.log("width: "+width+",height:"+heigth+",radius:"+hexRadius);
						//Set the hexagon radius
						var hexbin = d3.hexbin()
									   .radius(hexRadius);

						//Calculate the center positions of each hexagon	
						var points = [];
						for (var i = 0; i < MapRows; i++) {
							for (var j = 0; j < MapColumns; j++) {
								points.push([hexRadius * j * 1.75, hexRadius * i * 1.5]);
							}//for j
						}//for i

						//Create SVG element
						//console.log(width+" "+height);
						var svg = d3.select(som_container_id).append("svg")
							.attr("width", width + margin.left + margin.right) 
							.attr("height", height + margin.top + margin.bottom)
							.append("g")
							.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

						///////////////////////////////////////////////////////////////////////////
						////////////////////// Draw hexagons and color them ///////////////////////
						///////////////////////////////////////////////////////////////////////////

						//Start drawing the hexagons
						var svg_draw=svg.append("g")
							.selectAll(".hexagon")
							.data(hexbin(points))
							.enter();							
							
							
							var hex_plot=svg_draw.append("path")
							.attr("class", function (d,i) {						
								var class_as_id_array=[];		
								if(init_settings['data'].hasOwnProperty(data_color[i][1])){
									class_as_id_array = init_settings['data'][data_color[i][1]].map((val, index, arr) => {
										newval=val["id"].replace(/ /g, '-');
										return newval;	  
									})				
								}				
								return "hexagon "+class_as_id_array.join(' ');
								
							})
							.attr("d", function (d) {
								return "M" + d.x + "," + d.y + hexbin.hexagon();
							})
							.attr("stroke", function (d,i) {
								return "#fff";
							})
							.attr("stroke-width", "1px")
							.style("fill", function (d,i) {
								//return color[i];
								return data_color[i][0];				
							})
							.attr("id",function (d,i) {
								//return color[i];
								//console.log(data_color[i])
								return "hid"+data_color[i][1];				
							})
							.style("opacity", function(d,i) { 									
									
									if(data_color[i][2]!='empty'){
										let length=init_settings['data'][data_color[i][1]].length;  
										//data_color[i][2]!='empty' ? opc=1 : opc=0.3;  //old good
										let highlight_mode=$("#pcp_major_vs_minor").val() || "major_clusters";
										if(highlight_mode=="major_clusters"){
											let opc =										        
											length >= 10  ? 1 :
											length >= 5  ? 0.5 :								
											length > 1   ? 0.3 :
													  0.2;
											return opc; 
										}
										if(highlight_mode=="minor_clusters"){
											let opc =										        
											length >= 10  ? 0.2 :
											length >= 5  ? 0.3 :								
											length > 1   ? 0.5 :
													  1;
											return opc; 
										}
										
											
									}else{
										return 0.2; 
									}
								
							})			
							.on("mouseover", mover)
							//.on("mouseout", som_mout)
							.on("click", multi_som_selection);	
							
							window["idot_correlation_data"]['som'][som_container_id]=hex_plot;						
							
							svg_draw.append("text")
							.attr("x", function(d) { return d.x; }) 
							.attr("y", function(d) { return d.y; })
							.attr("dy", ".35em")
							.attr("dx", function(d,i) {  //hex text displacement
								if(data_color[i][2]!='empty'){
									var length = init_settings['data'][data_color[i][1]].length;
									
								}else{
									var length = 0;
								}								
								
								if(length>=10){
									return "-.35em"; 
								}
								if(length<10){
									return "0em"; 
								}
								})
							.attr("pointer-events", "none")
							.text(function(d,i) { 
								var result;	
										//console.log(i);
										//console.log(init_settings);
										//console.log(data_color);
									data_color[i][2]!='empty' ? result=init_settings['data'][data_color[i][1]].length : result='';
								
								return result; 
							});
							
							
								//Function to call when you mouseover a node
							function mover(d) {
								
							}

						function multi_som_selection (d) {
							
							if(!window["idot_correlation_data"].hasOwnProperty("som_selected")){								
								window["idot_correlation_data"]["som_selected"]=[];	
							}
								if(window["idot_correlation_data"]["som_selected"].indexOf(d)==-1){
										window["idot_correlation_data"]["som_selected"].push(d);
										var el = d3.select(this)
										.transition()
										.duration(10)		  
										.style("stroke", "red")
										.style("stroke-width", 5);	
										
									}else{
										 window["idot_correlation_data"]["som_selected"].splice(window["idot_correlation_data"]["som_selected"].indexOf(d), 1);
											var el = d3.select(this)
											   .transition()
											   .duration(100)
											   .style("stroke", "white")
											   .style("stroke-width", 1)
											   ;
										
										if(options['som_main_setting'].hasOwnProperty('pcp_som_dom') && window["idot_correlation_data"]["som_selected"].length==0){
											options['som_main_setting']['pcp_som_dom'].unhighlight(); 
										}  
									}
									
										
										if(window.hasOwnProperty('d3_circular_culvert')){  //for highlighting map	
													let selected=[];
													let highlight_list=[];
													let highlight_list_item=[];
													
													console.log(edge_bundle_data["cluster_info"]);
													
													for(each in window["idot_correlation_data"]["som_selected"]){
														let d_each = window["idot_correlation_data"]["som_selected"][each];
														for(var each_key in sample_to_cluster){
															if(sample_to_cluster[each_key]==("i"+d_each['j']+"-"+d_each['i'])){
																selected.push(each_key);
																if(options['som_main_setting'].hasOwnProperty('pcp_som_dom')){																	
																	highlight_list.push(edge_bundle_data["cluster_info"]["i"+d_each['j']+"-"+d_each['i']]['cluster_to_full_data']);	
																
																}//end of if statement
															}
														}// end of for loop													
													}
													for(each in highlight_list){
														for(each_a in highlight_list[each]){
															highlight_list_item.push(highlight_list[each][each_a]);
														}
													}															
													
													options['som_main_setting']['pcp_som_dom'].highlight(highlight_list_item);
													window['d3_circular_culvert'].style("opacity", 0.01).filter(function(d) {
														//console.log(selected);
														//console.log(d.properties['culvert_sed-ratio-n-key']);
														return selected.indexOf(d.properties['culvert_sed-ratio-n-key']) > -1;  //if there it is in the slected  value
																}).style("opacity", 1);													
													
													if(window["idot_correlation_data"]["som_selected"].length==0){		//if no claster is selected									
														window['d3_circular_culvert'].style("opacity", 1);
														options['som_main_setting']['pcp_som_dom'].unhighlight();
													}
													}
									
						} //end of multi selection
						
						
						
						//Mouseout function
					    function som_mout(d) {
						
							var el = d3.select(this)
								   .transition()
								   .duration(100)
								   .style("stroke", "white")
								   .style("stroke-width", 1)
								   ;
						};						
						
						function som_clicker(d) {							
					
							var el = d3.select(this)
							.transition()
							.duration(10)		  
							.style("stroke", "red")
							.style("stroke-width", 5);	
							//console.log(d);					
							 
							if(options['som_main_setting'].hasOwnProperty('pcp_som_dom') ){
								//console.log(d);
								//console.log("i"+d['j']+"-"+d['i']);
								let highlight_list = edge_bundle_data["cluster_info"]["i"+d['j']+"-"+d['i']]['cluster_to_full_data'];					
								//console.log(highlight_list); 
								options['som_main_setting']['pcp_som_dom'].highlight(highlight_list);
							}
							
							if(window.hasOwnProperty('d3_circular_culvert')){	
										let selected=[];
										for(var each_key in sample_to_cluster){
											if(sample_to_cluster[each_key]==("i"+d['j']+"-"+d['i'])){
												selected.push(each_key);
											}
										}
										window['d3_circular_culvert'].style("opacity", 0.01).filter(function(d) {
											//console.log(selected);
											//console.log(d.properties['culvert_sed-ratio-n-key']);
											return selected.indexOf(d.properties['culvert_sed-ratio-n-key']) > -1;  //if there it is in the slected  value
													}).style("opacity", 1);
										}					
						}						
				}
				
				function export_cluster (options) {
					
					
					let som_container_id = options['som_container_id'];					
					$("#som_dehighlight_all").remove();
					$(som_container_id).prepend(
						'<button type="button" id="som_dehighlight_all" class="btn btn-primary" style="font-size: 12px;">Default View</button>'
					);
				$("#som_dehighlight_all").click(function() {
						if(options['som_main_setting'].hasOwnProperty('pcp_som_dom') ){
							options['som_main_setting']['pcp_som_dom'].unhighlight();
						}
						if(window.hasOwnProperty('d3_circular_culvert')){											
													window['d3_circular_culvert'].style("opacity", 1);
										}
					});
					$(".export_som_class").remove();
					
					
					
					console.log(options); 
					$(som_container_id).prepend(
						'<button type="button" class="export_som_guidance btn btn-primary" style="font-size: 12px;">Export Guidance</button>'					
					);
					$(som_container_id).prepend(
						'<button type="button" class="export_som_class btn btn-primary" style="font-size: 12px;">Export Result</button>'
										
					);
					 
					
					
					$(".export_som_class").unbind();
					$(".export_som_class").click(function(){
					var url = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(options));   
								window.open(url, '_blank');
								window.focus();	
					});
					
					$(".export_som_guidance").click(function(){ //export guide
						
						let title_export='',main_content='';						
						let cluster_list={};						
						for(var each_item in options['som_pcp_data']){
							if(!cluster_list.hasOwnProperty(options['som_pcp_data'][each_item]["cluster_id"])){
								cluster_list[options['som_pcp_data'][each_item]["cluster_id"]]={
									"data":{},
									'sample_size':0,
								};
							}
							
						for(var each_var in options['som_pcp_data'][each_item]){
							if(!cluster_list[options['som_pcp_data'][each_item]["cluster_id"]]["data"].hasOwnProperty(each_var)){
								cluster_list[options['som_pcp_data'][each_item]["cluster_id"]]["data"][each_var]=[];
							}
							cluster_list[options['som_pcp_data'][each_item]["cluster_id"]]["data"][each_var].push(options['som_pcp_data'][each_item][each_var]);
							
						}
							cluster_list[options['som_pcp_data'][each_item]["cluster_id"]]["sample_size"]++; 
							}
						console.log(cluster_list);					
						//let cluster_list=window['pcp_plot_option']['edge_bundle_data']['cluster_info'];  
												
						//setTimeout(function(){ 
							for(var cluster_name in cluster_list){
								cluster_list[cluster_name]['min_max']={}
								let variable_list=cluster_list[cluster_name]['data'];
								if(cluster_list[cluster_name]['sample_size']>=4){
									title_export="cluster_name,";
									main_content+=cluster_name+',';
									for(var each_variable in variable_list){									
										title_export+=each_variable+",";
										
										let array = variable_list[each_variable].map(x => Number(x));									
										
										let max = array.reduce(function(a, b) {
											return Math.max(a, b);
										});
										let min = array.reduce(function(a, b) {
											return Math.min(a, b);
										});	
										cluster_list[cluster_name]['min_max'][each_variable]=[min,max];
										main_content+=min.toFixed(2)+'-'+max.toFixed(2)+',';
									}
									main_content+= cluster_list[cluster_name]['sample_size']+',<br>';
								}
								
							}
							console.log('try to export');
							title_export+="sample,";
							console.log(title_export+"<br>"+main_content);
							var url = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(title_export+"<br>"+main_content));   
									window.open(url, '_blank');
									window.focus();	

						//}, 2000);
						
					
					
					});
					
					let var_each = [],cluster_total=0;
					let clus = {"0":0,"5":0,"10":0,"20":0,"50":0,"100":0};
					for(var each_cluster in options['edge_bundle_data']['cluster_info']){
							
						var_each.push(options['edge_bundle_data']['cluster_info'][each_cluster]['range']["culvert_sed-ratio-n-key"]);
						cluster_total++;
						let sample_size=options['edge_bundle_data']['cluster_info'][each_cluster]['sample_size']
						
							    sample_size >= 100  ? clus["100"]++ :
								sample_size >= 20  ? clus["20"]++ :
								sample_size >= 10  ? clus["10"]++ :									
								sample_size >= 5   ? clus["5"]++ :
										  clus["0"]++;
					}
					
					var max_range = var_each.reduce(function(a, b) {
						return Math.max(a, b);
					});
					
					let table_style='width:100%;border: 1px solid black;border-collapse: collapse;';
					 let table_html='<table class="som_stats" style="'+table_style+'">'+
						'<tr><th style="width:100px">Cluster Size</th><th>1-4</th><th>5-9</th><th>10-19</th><th>20-99</th><th>>100</th></tr>'+
						'<tr><th>Counts</th><th>'+clus["0"]+'</th><th>'+clus["5"]+'</th><th>'+
						clus["10"]+'<th>'+clus["20"]+'</th><th>'+clus["100"]+'</th><tr>'+
						'</table><table class="som_stats" style="'+table_style+'">'+
						'<tr><th>Max Cluster Range: '+max_range.toFixed(2)+'</th>'+
						'<th>Number of Cluster: '+cluster_total+'</th></tr>'
						'</table><br><br>'; 
						;
								
					$(".som_stats").remove();
					$("#pie_contain5").prepend(table_html);
					//$("#max_key_range").html(max_range);
					//console.log(max_range);  range very important koala
					
				}
				
				function prepare_som_pcp_data_add_color(options,data_color,som_container_id){ 
							var init_settings = options['som_main_setting'];
							var join_key = init_settings['join_key'],
								cluster_to_color={},
								culvert_key_to_color={};
							
							for(var each in data_color){
								cluster_to_color[data_color[each][1]] = data_color[each][0];
							}
							for(var each in init_settings["sample_to_cluster"]){
								culvert_key_to_color[each]=cluster_to_color[init_settings["sample_to_cluster"][each]]								
							}	
								options["culvert_id_to_cluster_color"]=culvert_key_to_color;
								//console.log("color code");
								//console.log(options["culvert_id_to_cluster_color"]);				
						}
				
				function dot_representation_som_special(options ,data_color,som_container_id){
							
							//console.log(options); 
							
							var init_settings = options['som_main_setting'];							
							var join_key = init_settings['join_key'];						
							var culvert_key_to_color=options["culvert_id_to_cluster_color"];
							
														
							if(window.hasOwnProperty("d3_circular_culvert") ){
								window.d3_circular_culvert.style("fill", function(d){ 								
									return culvert_key_to_color[d.properties[join_key]] || "#d3d3d3" })
								.attr("r", function(d) {
									return d.properties[join_key]/1*5+5;
									})
							.on("mouseout", function(d){
								window["ifis_search_result"].clearLayers();
							})
							.on("click", function(d){														
								
								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");
							});
									
							}
							 /*
							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"]);
								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");
							});*/
							
							
						}
		}