//The color of each hexagon

$('head').append([		
			'<script src="js/pcp_label_conversion.js"></script>',
			'<script src="assets-examples/js/som_package/som.js"></script>',					
	].join('\n'));



    
var feature_oprtions={
	//"sed_features":["rusle_mean","stc","culvert_width","rusle_sum","year_built","tree_cd","tall_tree_cd","grass_cd","agc_cd","catareasqkm","wsareasqkm","pctag2006slp10cat","pctag2006slp10ws","pctag2006slp20cat","bfiws","elevws","kffactcat","kffactws","pctcolluvsedcat"],
	//"visual_ana_feature":["stc","culvert_to_stream","nhdslope","q100","claycat","rusle_mean","agc_cd","grass_cd","tall_tree_cd"],
	"full_ana_feature":{"key":"site_id","data_url":'data/culvert_sedmap_liz.json',"features":["stc","culvert_to_stream","culvert_width","nhdslope","year_built","q100","claycat","rusle_mean","agc_cd","grass_cd","tree_cd","tall_tree_cd","catareasqkm","wsareasqkm","pctag2006slp10cat","pctag2006slp10ws","pctag2006slp20cat","bfiws","elevws","kffactcat","kffactws"]}, 
	"sed_feature":{"key":"site_id","data_url":'data/culvert_sedmap_liz.json',"features":["nhdslope","q100","claycat","rusle_mean","rusle_sum","agc_cd","grass_cd","tree_cd","tall_tree_cd","catareasqkm","wsareasqkm"]}, 
	"test":{"key":"site_id","data_url":'data/culvert_sedmap_liz.json',"features":["wsareasqkm","culvert_width"]}, 
	"tutorial":{"key":"site_id","data_url":'data/tutorial.json',"features":["hello","hola","ciao"]},	
	"ws_testing":{"key":"site_id","data_url":'data/testing_data_ws.json',"features":["ag","size","nature","urban"]},	
	"culvert_serious":{
		"key":"sed_ratio_n","data_url":'data/culvert_new_data_320.json',
		"features":['area_km','agc_cd_n','rusle_mean_n','tree_cd','tall_tree_cd','grass_cd','agc_cd','rusle_mean'],
		"log_ln_field":["area-km",'up2500_100mb_channel-density','fl_100mb_urban']
		},
	
	"iris":{"key":"class","data_url":'data/iris.json',"features":['sepal_length','sepal_width','petal_length','petal_width'],"optimal_neuron":[3,3]},
	"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'],  
		"log_ln_field":["fl_ws_area-km",'up2500_100mb_channel-density','fl_100mb_urban','up2500_100mb_coniferous',],  //'culvert_stc-n'
		"optimal_neuron":[8,8]
		},	
	
		
	};  
	

var color = ["#E9FF63", "#7DFF63", "#63F8FF", "#99FF63", "#CFFE63", "#FFC263", "#FFC763", "#FF8E63", "#FF6464", "#FF7563", "#FF6364", "#FF7F63", "#FFE963", "#E3FF63", "#FFD963", "#FFE263", "#BAFF63", "#6BFF63", "#64FF69", "#71FF63", "#63FF6C", "#63FFD8", "#64FF69", "#63FF9A", "#FDFC63", "#88FF63", "#66FF64", "#A6FF63", "#63FFDB", "#63D9FE", "#90FF63", "#FF9B63", "#FF7263", "#9DFF63", "#E5FF63", "#FF7F63", "#FF7463", "#FFAE63", "#F4FF63", "#FFEC63", "#FBFF63", "#FFE663", "#FFC263", "#9DFF63", "#AEFF63", "#6AFF63", "#65FF65", "#63FFC7", "#C5FF63", "#63FFBE", "#63FF93", "#63FFAC", "#62FF79", "#90FF63", "#6AFF63", "#63FFEF", "#63F7FF", "#63FFD1", "#6370FF", "#638DFF", "#63FFDF", "#C5FF63", "#63FF6A", "#64FF69", "#C7FE63", "#FDFC63", "#D0FE63", "#FFDC63", "#E3FF63", "#DCFF63", "#C9FE63", "#FBFF63", "#FFB663", "#D9FF63", "#9DFF63", "#69FF63", "#DCFF63", "#63FFD4", "#63FFB8", "#64FF67", "#74FF63", "#63FCFF", "#63FFF9", "#63FFE9", "#A6FF63", "#63FFCD", "#63CEFE", "#63FBFF", "#63FFFB", "#637CFF", "#6379FF", "#D2FE63", "#CFFE63", "#63FF6E", "#65FF65", "#EEFF63", "#DCFF63", "#9DFF63", "#AAFF63", "#B6FF63", "#D0FE63", "#AEFF63", "#CDFE63", "#64FF67", "#99FF63", "#66FF64", "#63FFC1", "#63FFD4", "#63FF90", "#63FFD1", "#63FFF4", "#63FFEC", "#63FFF9", "#71FF63", "#63FF93", "#63FFC4", "#63F7FF", "#638DFF", "#63E9FF", "#6375FF", "#88FF63", "#95FF63", "#63FFAF", "#63FF93", "#63FF9A", "#9DFF63", "#88FF63", "#EEFF63", "#BDFF63", "#71FF63", "#B6FF63", "#80FF63", "#62FF82", "#63FF6C", "#62FF76", "#63FF6E", "#63FFCD", "#63EFFF", "#63FFF6", "#63FFB5", "#63FFFC", "#63B4FF", "#63FFC1", "#63F5FF", "#63FFB5", "#63FFBB", "#63FFFC", "#6379FF", "#63B0FF", "#63FFBB", "#D5FE63", "#63FFB8", "#63FF6C", "#62FF7C", "#63FFBE", "#FFDF63", "#FFE263", "#FFE963", "#76FF63", "#67FF64", "#63FF90", "#65FF65", "#63FFA0", "#63FFA6", "#62FF73", "#63FFC1", "#63FFC4", "#63FFF9", "#63CEFE", "#63A4FF", "#6373FF", "#63C5FE", "#638DFF", "#63FF9D", "#6387FF", "#63FFBE", "#63FEFE", "#63FFEC", "#63FFF1", "#638DFF", "#FF6A64", "#FBFF63", "#FFEF63", "#63FFE9", "#62FF8C", "#BAFF63", "#FFAB63", "#FFCB63", "#62FF82", "#88FF63", "#63FFB2", "#63FFC1", "#63FFDF", "#63FFB5", "#63FFB5", "#62FF7F", "#63FFC4", "#63ECFF", "#63FFFC", "#63F3FF", "#63FFE5", "#63D2FE", "#63FFF6", "#63A8FF", "#63F8FF", "#63FFFB", "#63E4FF", "#636DFF", "#63FFC4", "#6387FF", "#FF8B63", "#EBFF63", "#C5FF63", "#BDFF63", "#62FF76", "#DCFF63", "#BDFF63", "#99FF63", "#62FF82", "#63FFA6", "#63C9FE", "#63FEFE", "#62FF89", "#63FFD8", "#63FFB8", "#63FFF1", "#63C1FE", "#63FCFF", "#63FFCA", "#63C9FE", "#63FFFC", "#6FFF63", "#63FFE5", "#63E9FF", "#63F7FF", "#63B0FF", "#636CFF", "#636CFF", "#63ACFF", "#63F1FF", "#FF8863", "#FF6864", "#FFB363", "#A2FF63", "#63FFD8", "#63FF96", "#99FF63", "#AEFF63", "#C7FE63", "#63FF93", "#63FFC1", "#63FFF9", "#63FFFB", "#67FF64", "#B2FF63", "#62FF76", "#62FF73", "#639CFF", "#63FFC1", "#63FFEF", "#66FF64", "#62FF76", "#63FFC4", "#63FFCA", "#63FFBE", "#63FFFC", "#6363FF", "#63ACFF", "#6375FF", "#63CEFE", "#FFB663", "#79FF63", "#BDFF63", "#63FF6C", "#66FF64", "#76FF63", "#FEF763", "#D7FE63", "#7DFF63", "#63FFB8", "#63F5FF", "#63F7FF", "#62FF7F", "#63FFA6", "#62FF76", "#63FFA6", "#63FFD1", "#63FEFE", "#63FFDF", "#63F8FF", "#63FF96", "#63FFA9", "#63FFA9", "#63C1FE", "#63FFC1", "#63D6FE", "#636EFF", "#6364FF", "#6370FF", "#6398FF", "#FFE663", "#C0FF63", "#EBFF63", "#C5FF63", "#D2FE63", "#69FF63", "#6FFF63", "#D4FE63", "#F4FF63", "#63FFC4", "#62FF89", "#63FFF4", "#63FFB8", "#63FFF4", "#63F8FF", "#62FF71", "#63FFBB", "#63FFEF", "#63FFF1", "#63FBFF", "#63C1FE", "#63FFDF", "#63FFD1", "#63FFE2", "#63ACFF", "#63F3FF", "#63DDFF", "#63FFF6", "#63D6FE", "#63CEFE", "#D4FE63", "#80FF63", "#FF8B63", "#D5FE63", "#63FFCA", "#90FF63", "#D7FE63", "#FBFF63", "#62FF7C", "#C9FE63", "#76FF63", "#69FF63", "#62FF7C", "#63FFD4", "#63FFA6", "#6BFF63", "#63FFC7", "#63E4FF", "#62FF7C", "#63FFF6", "#6379FF", "#63FFCD", "#63FFCA", "#63FFEF", "#63FFBE", "#63E9FF", "#63ECFF", "#63FFF9", "#63E0FF", "#63C5FE", "#FF6B63", "#FFD663", "#63FF6E", "#63FFB2", "#FFD663", "#62FF7F", "#63FFA6", "#9DFF63", "#F6FF63", "#95FF63", "#95FF63", "#FFD963", "#DCFF63", "#63FF90", "#63FFD1", "#63FFFC", "#63FFA3", "#63FFAF", "#63ECFF", "#63FFEF", "#63C5FE", "#63FDFF", "#63FF93", "#62FF76", "#69FF63", "#63EFFF", "#636DFF", "#6379FF", "#63E7FF", "#63E7FF", "#FF8E63", "#CDFE63", "#BDFF63", "#F9FF63", "#62FF7F", "#63FFE2", "#62FF86", "#67FF64", "#63FFA3", "#6DFF63", "#9DFF63", "#FFE963", "#FFBE63", "#6AFF63", "#62FF7F", "#63FFD4", "#79FF63", "#63D2FE", "#63DDFF", "#63FEFE", "#63BDFE", "#63FFDB", "#64FF69", "#62FF8C", "#63FFD8", "#63BDFE", "#63B8FF", "#6391FF", "#63FFDB", "#63FEFE", "#F8FF63", "#FFF263", "#C2FF63", "#FFDF63", "#D2FE63", "#64FF69", "#63FFE2", "#7DFF63", "#FDFC63", "#FF9763", "#6BFF63", "#F2FF63", "#FBFF63", "#AEFF63", "#80FF63", "#63D9FE", "#63FFBB", "#63FFD8", "#63FFEF", "#63C5FE", "#63FF90", "#62FF89", "#63D2FE", "#63FFC4", "#63FF93", "#63D2FE", "#63DDFF", "#63FDFF", "#6DFF63", "#62FF82", "#FF8363", "#DAFF63", "#74FF63", 
             "#63FF6A", "#63FF6A", "#64FF69", "#FFDF63", "#FF7F63", "#FFEF63", "#EEFF63", "#CFFE63", "#6AFF63", "#95FF63", "#63FF6C", "#63FF90", "#6BFF63", "#63FF90", "#63FFCA", "#63E9FF", "#63FFEC", "#63FFAC", "#63FFD4", "#63FAFF", "#63FFCA", "#63ECFF", "#62FF8C", "#63FFE5", "#69FF63", "#FF7463", "#FF9463", "#E0FF63", "#FFCB63", "#A6FF63", "#63FF93", "#E0FF63", "#FEFA63", "#EBFF63", "#AAFF63", "#C2FF63", "#D4FE63", "#63FFAC", "#65FF65", "#62FF73", "#63FFE9", "#65FF66", "#95FF63", "#62FF7F", "#63FFB5", "#63D2FE", "#63FFAC", "#63FFFB", "#62FF8C", "#64FF69", "#99FF63", "#63FFB2", "#63FFDF", "#63FFB8", "#BAFF63", "#FFDC63", "#62FF76", "#BDFF63", "#C2FF63", "#95FF63", "#F6FF63", "#FFA163", "#CFFE63", "#63FFE9", "#84FF63", "#6BFF63", "#6DFF63", "#63FFC1", "#D0FE63", "#69FF63", "#63FFC1", "#62FF8C", "#63FFBB", "#63FF96", "#63FAFF", "#63FFEC", "#63FEFE", "#62FF76", "#63FF9A", "#FFC563", "#6FFF63", "#63FFAF", "#63F5FF", "#63F1FF", "#63FF6A", "#62FF7C", "#63F8FF", "#9DFF63", "#99FF63", "#AEFF63", "#FF8363", "#FFC963", "#62FF79", "#63FF90", "#63FF6A", "#63FCFF", "#63E9FF", "#63FFA0", "#64FF67", "#FFD463", "#A6FF63", "#CBFE63", "#63FF90", "#63FFC4", "#63C9FE", "#63FFE5", "#63FFDB", "#62FF89", "#63FFD8", "#79FF63", "#63FF9A", "#63FAFF", "#63E9FF", "#63FF6E", "#63F7FF", "#63E4FF", "#63F5FF", "#64FF67", "#C9FE63", "#FFBA63", "#D9FF63", "#63FFD1", "#63FFF6", "#63FF93", "#C0FF63", "#F6FF63", "#62FF82", "#AEFF63", "#CBFE63", "#FF8363", "#63FF6A", "#63FFCD", "#63F7FF", "#63FFF9", "#63FFC4", "#63FFC4", "#95FF63", "#63FFCD", "#A2FF63", "#EBFF63", "#63FFC1", "#63FFA0", "#63E4FF", "#63FFFB", "#63F3FF", "#63CEFE", "#63FBFF"]


	 
	
				 
	///////////////////////////////////////////////////////////////////////////
	////////////// Initiate SVG and create hexagon centers ////////////////////
	///////////////////////////////////////////////////////////////////////////






	//svg sizes and margins
	var margin = {
		top: 50,
		right: 50,
		bottom: 50,
		left: 50
	};
	//console.log("height");
	//console.log(Number($("#chart").height())*0.5);
	init_settings={
		"width":$("#chart").width(),  // 850
		"height": $("#chart").height(),  // 350
		"MapColumns":5, //30
		"MapRows":5,  //20
		"data":{}, 
		"neighbour":{}
	};
	
	if(!window.hasOwnProperty("idot_correlation_data")){
		
	}else{
		window["idot_correlation_data"]["init_settings"]={
								"width":$("#chart").width(),  // 850
								"height": $("#chart").height(),  // 350
								"MapColumns":5, //30
								"MapRows":5,  //20
								"data":{}, 
								"neighbour":{}
								};
								
	};

	$(".pcp_unhighlight").click(function(){
		window['som_pcp'].unhighlight();
	});
	//feature_oprtions[$("#data_set_select").val()][features].length
	$(".rolcol").click(function(){
		//alert("The text has been changed.");			
		 var y=$("#mapcolumns").val(),x=$("#maprows").val();		 
		 var initialrate2=$("#initialrate").val();
		 var iteration_rate2=$("#iteration_rate").val();
		 init_settings["MapColumns"]= parseInt(x) ;
		 init_settings["MapRows"]= parseInt(y); 
		 $("#chart").empty();
		 //console.log(initialrate2+"  cgc "+iteration_rate2);
		 var neighbour_distance=$("#neighbour_distance").val(),
		 initial_radius=$("#initial_radius").val();	
		 
		trigger_som(x,y,initialrate2,iteration_rate2,neighbour_distance,Number(initial_radius),feature_oprtions[$("#data_set_select").val()]);
	}); 
	$(".som_setting").change(function(){
		var optimal_neuron = feature_oprtions[$("#data_set_select").val()]["optimal_neuron"] || [4,4];
		console.log(feature_oprtions[$("#data_set_select").val()]);
		$("#mapcolumns").val(optimal_neuron[0]); $("#maprows").val(optimal_neuron[1]); 
		//alert("The text has been changed.");		 
		 var y=$("#mapcolumns").val(),x=$("#maprows").val();
		 var initialrate2=$("#initialrate").val();
		 var iteration_rate2=$("#iteration_rate").val();
		 init_settings["MapColumns"]= parseInt(x) ;
		 init_settings["MapRows"]= parseInt(y); 
		 $("#chart").empty();
		// console.log(initialrate2+"  cgc "+iteration_rate2);
		 var neighbour_distance=$("#neighbour_distance").val(),
		 initial_radius=$("#initial_radius").val();		 
		 trigger_som(x,y,initialrate2,iteration_rate2,neighbour_distance,Number(initial_radius),feature_oprtions[$("#data_set_select").val()]);
	});  

	$( document ).ready(function() {	
		render_som(feature_oprtions);
	});
	
	function render_som(feature_oprtions){
		var x=$("#maprows").val(),
				 y=$("#mapcolumns").val(),
				initialrate1=$("#initialrate").val(),
				iteration1=$("#iteration_rate").val(),
				neighbour_distance=$("#neighbour_distance").val(),
				initial_radius=$("#initial_radius").val();
				//console.log("get_data2");
				 //max(this.width, this.height)/2;
				 if($("#chart").find("svg").length==0){
					 console.log($("#chart").find("svg").length);
						trigger_som(x,y,initialrate1,iteration1,neighbour_distance,initial_radius,feature_oprtions[$("#data_set_select").val()]); 
				 }
	}
	//render_som(feature_oprtions)
	/*
	$( window ).resize(function() {
		
		setTimeout(function(){ 
			console.log('aaaaa'); 
			  $("#chart").empty();			  
			  $("#paracoord").empty();
			  render_som(feature_oprtions); 

				}, 500);
				 
		  });*/
 
 
 
			//$.getJSON( "http://s-iihr32.iihr.uiowa.edu:8081/som/som.sev?x="+x+"&y="+y, function(data) {  
	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={},data = survey_run_som (parseInt(x),parseInt(y),Number(initialrate),parseInt(iteration),Number(neighbour_distance),Number(initial_radius),input_data_setting);
				//console.log("input data reuslt - clustered");
				//console.log(data);					
				
				init_settings["data"]=data["index_list"];  //index_list neighbour
				init_settings["neighbour"]=data["neighbour_group"]; 
				init_settings["variables"]=data["features"];
				init_settings["neighbors_best"]=data["neighbors_best"];
				init_settings["raw_data"]=data["raw_data"];
				init_settings["join_key"]=data["join_key"];
				 
				$(".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();	
					});
				
				//console.log(data_color);
				survey_color_ramp(init_settings,init_settings["MapColumns"],init_settings["MapRows"]);
		}			
			//}); 
	

function survey_color_ramp(input_setting_data,MapColumns,MapRows){	
   //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();
		}
		$('#color_ramp_contain').append('<canvas id="color_ramp_display" width="'+width+'" height="'+height+'" style="position:absolute; border: red;border-style: dotted">')
		
		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["data"],MapColumns,MapRows);
		    create_plot(init_settings,color_matrix);
			prepare_cluster_data_for_pcp(input_setting_data,color_matrix);
		};
		imageObj.src = $("#color_ramp_select").val();
		//console.log($("#color_ramp_select").val());
		//"data/color_ramp/color_ramp1.png";
		//console.log(imageObj.length); 		
		
		 /*setTimeout(function(){ 
				console.log("color_data");
				var canvasColor=context.getImageData(1, 1, 1, 1).data
			    console.log(canvasColor[0]+","+canvasColor[1]+","+canvasColor[2])
				
		}, 500);*/	
	
	function prepare_cluster_data_for_pcp(init_settings_input,color_matrix){
		var id_to_cluster={},cluster_coord_to_color={},row_data_with_cluster=[],data_collection_array,join_key=init_settings_input['join_key'];		
		color_matrix.forEach((color_for_node) => {			
			cluster_coord_to_color[color_for_node[1]]=color_for_node[0];
		});		
		for(var each_coord in init_settings_input['data']){ 
			var cluster_color = cluster_coord_to_color[each_coord] || '#45484c';
			for(var each_data in init_settings_input['data'][each_coord]){
				var each_data_id = init_settings_input['data'][each_coord][each_data]['id'];
				id_to_cluster[each_data_id]={"cluster_id":each_coord, "cluster_color":cluster_color};				
			}
		}		
		data_collection_array = init_settings_input["raw_data"]["features"] || init_settings_input["raw_data"];		
		data_collection_array.forEach((each_array) => {
			var each_data_entry= each_array["properties"] || each_array;
			//each_data_entry['cluster_color']= id_to_cluster[each_data_entry[join_key]]['cluster_color'];
			each_data_entry['cluster_id']= id_to_cluster[each_data_entry[join_key]]['cluster_id'];
			row_data_with_cluster.push(each_data_entry);			
			
		});	
		//console.log("PCP result");
		//console.log(row_data_with_cluster);
		//var pcp_data=[{"sed_ratio_n":"0.400102","stc_n":"0.3","area_km":"18.8698","nhdslope":"0.00405351","q100":"4467.96","claycat":"24.8207","rusle_mean":"81","agc_cd":"37.3626381158829","grass_cd":"40.2930408716202","tall_tree_cd":"14.1941398382187"},{"sed_ratio_n":"0.620248","stc_n":"0.168","area_km":"4.63944","nhdslope":"0.00802913","q100":"2465.74","claycat":"24.0217","rusle_mean":"70","agc_cd":"54.9076795578003","grass_cd":"33.5276961326599","tall_tree_cd":"1.84645280241966"},{"sed_ratio_n":"0.250171","stc_n":"0.47","area_km":"49.2923","nhdslope":"0.00103995","q100":"6338.58","claycat":"18.9204","rusle_mean":"39","agc_cd":"46.405228972435","grass_cd":"26.4705896377563","tall_tree_cd":"3.26797403395176"},{"sed_ratio_n":"0.330173","stc_n":"0.262","area_km":"46.9011","nhdslope":"0.00103995","q100":"6338.58","claycat":"18.9204","rusle_mean":"39","agc_cd":"46.405228972435","grass_cd":"26.4705896377563","tall_tree_cd":"3.26797403395176"}];
		
			//$.getScript( "js/d3.parcoords.js", function( data, textStatus, jqxhr ){
				console.log("implement");
				//console.log(row_data_with_cluster);
				init_settings['pcp_data']=row_data_with_cluster;
		
		//console.log(init_settings_input);
		
		
		function order_and_select_field_for_pcp(row_data_with_cluster){
			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['cluster_id']=each_item['cluster_id'];
				
				
				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];
					}			
				}
				 if(each_item.hasOwnProperty('landform_region')){
					temp_row['landform_region']=each_item['landform_region'];
				}
				final_result.push(temp_row);
			}
			return final_result;
		}
		
		function row_data_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":{}}
				}
				
				
				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*/
						}	
						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];
				
				for(var each_field_name in each_class_data['data']){
					let each_data_array = each_class_data['data'][each_field_name];	
						//console.log(each_class_data);
					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)); 
					
					
					/*iterate each field of valuse (array) to calculate mean value for cluster (used for edge bundling)*/
				}
			};		
			console.log(collecting_data_for_each_class);
			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			
		}
		
			var cluster_mean_info=row_data_cluster_calculate_mean_by_class({'target_class_name':"cluster_id",'skip_field':["class"],'data_input':row_data_with_cluster});
		
		//console.log(color);	
			$("#paracoord").empty();
		    window['som_pcp'] = d3.parcoords()("#paracoord").data(order_and_select_field_for_pcp(row_data_with_cluster)).clusterdata(cluster_mean_info).color(function(d) {								  //if value exists, assign it a color; otherwise assign gray
								if (id_to_cluster[d[join_key]]) {	 
									var rgb_color =(id_to_cluster[d[join_key]]["cluster_color"].replace("rgb(", "").replace(")", "")).split(",");									
									var hex_color = rgbToHex(Number(rgb_color[0]), Number(rgb_color[1]), Number(rgb_color[2]));
									return hex_color; //recolorMap holds the colorScale generator
								  } else {
									return "#ccc";
								  };
								}).render().brushable().on("brush", function(items) {
								
								
								//console.log(items);
								var items_id_list = (items.map((val, i, arr) => {
									  
									 // return id_to_cluster[val[join_key]]["cluster_id"];
									 return val["cluster_id"];
									}));
									window['som_pcp'].unhighlight(); 
								//console.log(items_id_list);
								//items.length!=0 ? console.log(id_to_cluster[items[join_key]]["cluster_id"]) : console.log("empty");
								//console.log(id_to_cluster[items[join_key]]["cluster_id"] );
								
								hex_som.style("opacity", 0.11).filter(function(d) {	
										    //console.log("S:"+selected_cluster_to_individual+"  dkey:"+d.properties[key]);
										    //console.log("i"+d.i+"-"+d.j);																						
											return items_id_list.indexOf("i"+(d.j)+"-"+(d.i)) > -1 ;
											  //if there it is in the slected  value
										  }).style("opacity", 1);
								
								}); 
								window['som_pcp'].clusterdata(cluster_mean_info);								
								
								pcp_label_conversion();
							   
								
								
								
			//});
	}
	
	function color_to_cell_mapping(context,input_data,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;
	}	
} //end of whole_color map
	
function mapping_u_matrix(neighbour){	
	for(var i in neighbour){
		
	}
}
			
function create_plot(options,data_color){
		var width=options["width"],
		    height=options["height"],
			MapColumns=options["MapColumns"],
			MapRows=options["MapRows"];
		//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
		var svg = d3.select("#chart").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()
			
			window['hex_som']=svg_draw.append("path")
			.attr("class", function (d,i) {						
				var class_as_id_array=[];		
				if(options['data'].hasOwnProperty(data_color[i][1])){
					class_as_id_array = options['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) { 
				var opc;			  
					data_color[i][2]!='empty' ? opc=1 : opc=0.11;
				return opc; 
			})			
			.on("mouseover", mover)
			.on("mouseout", mout)
			.on("click", clicker);
			
			svg_draw.append("text")
			.attr("x", function(d) { return d.x; })
			.attr("y", function(d) { return d.y; })
			.attr("dy", ".35em")
			.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) {
				
			}

		//Mouseout function
			function mout(d) { 
				var el = d3.select(this)
				   .transition()
				   .duration(100)
				   .style("stroke", "white")
				   .style("stroke-width", 1)
				   ;
				  
				  //$("#chart_info").html(""); 
			};

		//Click function
		function clicker(d) { 
			   var el = d3.select(this)
				.transition()
				.duration(10)		  
				.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];	     
			   //neighbors_best  neighbour
			   //console.log(group_neighbour); 
			   var res_text=" ";
				var neigh_text=" ";
			   if(typeof(group)!="undefined"){		   	  
				   
				   for(var each in group){
				   res_text+=group[each]["id"]+" , ";		  
					}
					/*basic information*/
					var res_sample_size="<b>Coordinate: </b>"+cluster_name+" ,<b>Cluster Size: </b>"+group.length+" ,<b>Label: </b>"+group[0]["i"]+"<br><br><b>Children:</b>"+res_text+" <hr>"
				   //console.log(res_sample_size);
				   for (var each_nei in group_neighbour){ 
					   var each_record=group_neighbour[each_nei];   
						//console.log("negroup");
						//console.log(each_record);
					   neigh_text+="<b>Coordinates: i</b>"+each_record["x"]+"-"+each_record["y"]+"<br> Distance:"+each_record["distance"].toExponential()+",<br> Vec:"+JSON.stringify(each_record["vector"])+ "<br><br>"; 
				   }
				 //console.log(res_sample_size+"\n"+neigh_text+"\n"+res_text);
			   $("#chart_info").html("Variables: "+init_settings["variables"].join()+"<br><br>"+res_sample_size+"<br>"+neigh_text+"<br>");
			   }
				//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 componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
