var flowcalc_default_media_id       = 'media_gas';
var flowcalc_default_calc_method_id = 'method_flow';
var flowcalc_default_p_min2         = 0.0;
var flowcalc_default_p_max2         = 10.3;
var flowcalc_default_cv2            = null;

var flowcalc_product_search_url     = '../search/';

var flowcalc_fluid_index_idx   = 0;
var flowcalc_fluid_name_idx    = 1;
var flowcalc_fluid_media_idx   = 2;
var flowcalc_fluid_gravity_idx = 3;
var flowcalc_fluid_data = [
	[ '1001', '空気',               'GAS',    '1.00' ],
	[ '1002', 'アンモニア',         'GAS',    '0.60' ],
	[ '1003', 'アセチレン',         'GAS',    '0.91' ],
	[ '1004', '亜硫酸ガス',         'GAS',    '2.26' ],
	[ '1005', 'アルゴン',           'GAS',    '1.38' ],
	[ '1006', 'イソブタン',         'GAS',    '2.07' ],
	[ '1007', '一酸化炭素',         'GAS',    '0.97' ],
	[ '1008', '塩化水素',           'GAS',    '1.27' ],
	[ '1009', 'エチルエーテル',     'GAS',    '2.55' ],
	[ '1010', '塩素',               'GAS',    '2.49' ],
	[ '1011', 'エタン',             'GAS',    '1.05' ],
	[ '1012', '塩化エチル',         'GAS',    '2.22' ],
	[ '1013', '塩化メチル',         'GAS',    '1.79' ],
	[ '1014', 'エチレン',           'GAS',    '0.97' ],
	[ '1015', '塩化ビニル',         'GAS',    '2.16' ],
	[ '1016', 'オゾン',             'GAS',    '1.66' ],
	[ '1017', 'クロロホルム',       'GAS',    '4.12' ],
	[ '1018', '酸素',               'GAS',    '1.11' ],
	[ '1019', '臭化水素',           'GAS',    '2.82' ],
	[ '1020', '水素',               'GAS',    '0.07' ],
	[ '1021', '窒素',               'GAS',    '0.97' ],
	[ '1022', '二酸化炭素',         'GAS',    '1.53' ],
	[ '1023', '二酸化塩素',         'GAS',    '2.33' ],
	[ '1024', 'ブタン',             'GAS',    '2.08' ],
	[ '1025', 'プロピレン',         'GAS',    '1.48' ],
	[ '1026', 'プロパン',           'GAS',    '1.56' ],
	[ '1027', 'ヘリウム',           'GAS',    '0.14' ],
	[ '1028', 'ベンゼン',           'GAS',    '2.73' ],
	[ '1029', 'メタン',             'GAS',    '0.56' ],
	[ '1030', 'ヨウ化水素',         'GAS',    '4.48' ],
	[ '1031', '硫化水素',           'GAS',    '1.19' ],
	[ '2001', '水',                 'LIQUID', '1.00' ],
	[ '2002', '安息香酸',           'LIQUID', '1.27' ],
	[ '2003', '亜麻仁油',           'LIQUID', '0.93' ],
	[ '2004', 'アセトン',           'LIQUID', '0.79' ],
	[ '2005', 'アンモニア',         'LIQUID', '0.68' ],
	[ '2006', '塩化メチル',         'LIQUID', '0.92' ],
	[ '2007', '塩素',               'LIQUID', '1.57' ],
	[ '2008', '塩酸',               'LIQUID', '1.19' ],
	[ '2009', 'エチルアルコール',   'LIQUID', '0.79' ],
	[ '2010', 'オリーブ油',         'LIQUID', '0.92' ],
	[ '2011', 'ガソリン',           'LIQUID', '0.73' ],
	[ '2012', 'グリセリン',         'LIQUID', '1.27' ],
	[ '2013', '軽油',               'LIQUID', '0.85' ],
	[ '2014', 'コーン油',           'LIQUID', '0.92' ],
	[ '2015', '酢酸',               'LIQUID', '1.07' ],
	[ '2016', '酸化エチレン',       'LIQUID', '0.90' ],
	[ '2017', '臭素',               'LIQUID', '3.14' ],
	[ '2018', '硝酸',               'LIQUID', '1.50' ],
	[ '2020', '潤滑油',             'LIQUID', '0.89' ],
	[ '2021', '水銀',               'LIQUID', '13.52' ],
	[ '2022', '水酸化ナトリウム',   'LIQUID', '2.13' ],
	[ '2023', '石炭酸',             'LIQUID', '1.07' ],
	[ '2024', '灯油',               'LIQUID', '0.81' ],
	[ '2025', 'トルエン',           'LIQUID', '0.88' ],
	[ '2026', 'トリクロロエチレン', 'LIQUID', '1.46' ],
	[ '2027', '二硫化炭素',         'LIQUID', '1.29' ],
	[ '2028', 'ヒマシ油',           'LIQUID', '0.97' ],
	[ '2029', 'ベンゼン',           'LIQUID', '0.88' ],
	[ '2030', 'ミルク',             'LIQUID', '1.04' ],
	[ '2031', '綿実油',             'LIQUID', '0.92' ],
	[ '2032', 'メチルアルコール',   'LIQUID', '0.79' ],
	[ '2033', '落花生油',           'LIQUID', '0.91' ],
	[ '2034', '硫酸',               'LIQUID', '1.84' ],
	[ '2035', '液体窒素',           'LIQUID', '0.81' ],
	[ '2036', '液体酸素',           'LIQUID', '1.14' ],
	[ '3001', '水蒸気',             'STEAM',  '0.46' ]
];

var flowcalc_flow_unit_index_idx = 0;
var flowcalc_flow_unit_name_idx  = 1;
var flowcalc_flow_unit_a1_idx    = 2;
var flowcalc_flow_unit_data = [
	[ '00', 'l/min',   1.00000000E+00 ],
	[ '01', 'dm3/min', 1.00000000E+00 ],
	[ '02', 'cm3/min', 1.00000000E-03 ],
	[ '03', 'm3/h',    1.66666667E+01 ],
	[ '04', 'm3/s',    6.00000000E+04 ],
	[ '05', 'l/h',     1.66666667E-02 ],
	[ '06', 'dm3/h',   1.66666667E-02 ],
	[ '07', 'SCFH',    4.72000000E-01 ]
];
var flowcalc_steam_flow_unit = [
	[ '--', 'kg/h', '0' ]
];

var flowcalc_p_unit_index_idx = 0;
var flowcalc_p_unit_name_idx  = 1;
var flowcalc_p_unit_a2_idx    = 2;
var flowcalc_p_unit_b2_idx    = 3;
var flowcalc_p_unit_data = [
	[ '00', 'MPa',     1.00000000E+00, 0.00000000E+00 ],
	[ '01', 'kgf/cm2', 9.80665000E-02, 0.00000000E+00 ],
	[ '02', 'PSI',     6.89487327E-03, 0.00000000E+00 ],
	[ '03', 'bar',     1.00000000E-01, 0.00000000E+00 ],
	[ '04', 'kPa',     1.00000000E-03, 0.00000000E+00 ],
	[ '05', 'Pa',      1.00000000E-06, 0.00000000E+00 ],
	[ '06', 'mmHg',    1.33322368E-04, 0.00000000E+00 ],
	[ '07', 'mmH2O',   9.80665000E-06, 0.00000000E+00 ],
	[ '08', 'Torr',    1.33322368E-04, 0.00000000E+00 ],
	[ '09', 'atm',     1.01325000E-01, 0.00000000E+00 ]
];

function $( id ) {
	return document.getElementById( id );
}

function FlowCalc() {
	var fc = this;
	
	this.p_min2 = flowcalc_default_p_min2;
	this.p_max2 = flowcalc_default_p_max2;
	this.cv2    = flowcalc_default_cv2;
	
	this.media       = null;
	this.calc_method = null;
	this.fluid       = null;
	this.p_unit      = null;
	this.flow_unit   = null;
	
	this.fluid_list     = flowcalc_fluid_data;
	this.flow_unit_list = flowcalc_flow_unit_data;
	this.p_unit_list    = flowcalc_p_unit_data;
	
	(function () {
		var query_param  = parse_query_string();
		var require_keys = [ 'p_min2', 'p_max2', 'cv2' ];
		
		for( var i = 0; i < require_keys.length; ++i ) {
			var key = require_keys[i];
			if( key in query_param ) {
				fc[key] = query_param[key];
			}
		}
	})();
}

FlowCalc.prototype.round = function( num ) {
	return Math.round( num * 100 ) / 100;
};

FlowCalc.prototype.pressure_round = function( num ) {
	return Math.round( num * 10000 ) / 10000;
};

FlowCalc.prototype.set_select = function( id, list, offset ) {
	var sel = $(id);
	
	sel.length = offset ? offset: 0;
	
	for( var i = 0; i < list.length; ++i ) {
		var obj = list[i];
		var opt = document.createElement( 'option' );
		
		for( var key in obj ) {
			opt[key] = obj[key];
		}
		
		opt.appendChild( document.createTextNode( obj.title ) );
		
		sel.appendChild( opt );
	}
}

FlowCalc.prototype.set_fluid_select = function( media ) {
	var offset = 0;
	var list   = new Array();
	
	if( media != 'STEAM' ) {
		list[ list.length ] = { value: '', title: '' };
	}
	
	for( var i = 0; i < this.fluid_list.length; ++i ) {
		var fluid = this.fluid_list[i];
		
		if( fluid[flowcalc_fluid_media_idx] != media ) continue;
		
		list[ list.length ] = {
			title: fluid[flowcalc_fluid_name_idx],
			value: fluid[flowcalc_fluid_index_idx],
			fc_fluid: fluid
		};
	}
	
	this.set_select( 'fluid', list, offset );
	this.fluid = null;
};

FlowCalc.prototype.set_p_unit_select = function() {
	var offset = 0;
	var list   = new Array();
	
	for( var i = 0; i < this.p_unit_list.length; ++i ) {
		var p_unit = this.p_unit_list[i];
		
		list[ list.length ] = {
			title: p_unit[flowcalc_p_unit_name_idx],
			value: p_unit[flowcalc_p_unit_index_idx],
			fc_p_unit: p_unit
		};
	}
	
	this.set_select( 'p_unit', list, offset );
	this.p_unit = list[0].fc_p_unit;
};

FlowCalc.prototype.set_flow_unit_select = function() {
	var offset = 0;
	var list   = new Array();
	
	for( var i = 0; i < this.flow_unit_list.length; ++i ) {
		var flow_unit = this.flow_unit_list[i];
		
		list[ list.length ] = {
			title: flow_unit[flowcalc_flow_unit_name_idx],
			value: flow_unit[flowcalc_flow_unit_index_idx],
			fc_flow_unit: flow_unit
		};
	}
	
	this.set_select( 'flow_unit', list, offset );
	this.flow_unit = list[0].fc_flow_unit;
};

FlowCalc.prototype.set_flow_unit_select_of_steam = function() {
	var offset = 0;
	var list   = new Array();
	
	for( var i = 0; i < flowcalc_steam_flow_unit.length; ++i ) {
		var flow_unit = flowcalc_steam_flow_unit[i];
		
		list[ list.length ] = {
			title: flow_unit[flowcalc_flow_unit_name_idx],
			value: flow_unit[flowcalc_flow_unit_index_idx],
			fc_flow_unit: flow_unit
		};
	}
	
	this.set_select( 'flow_unit', list, offset );
	this.flow_unit = list[0].fc_flow_unit;
};

FlowCalc.prototype.change_media = function( media ) {
	var temperature = $('temperature');
	var gravity     = $('gravity');
	var flow        = $('flow');
	
	this.media = media;
	
	gravity.value         = '';
	gravity.className     = 'forInput';
	gravity.readOnly      = false;
	flow.value            = '';
	temperature.readOnly  = false;
	temperature.className = 'forInput';
	
	switch( media ) {
	case 'GAS':
		this.set_flow_unit_select();
		break;
	case 'LIQUID':
		temperature.readOnly  = true;
		temperature.className = 'readOnly';
		this.set_flow_unit_select();
		break;
	case 'STEAM':
		temperature.readOnly = true;
		temperature.className = 'readOnly';
		gravity.readOnly     = true;
		gravity.className    = '';
		
		// flow_unitのプルダウンを を kg/h のみに変更
		this.set_flow_unit_select_of_steam();
		
		break;
	}
	
	this.set_fluid_select( media );
	
	if( media == 'STEAM' ) {
		this.change_fluid( $('fluid').options[0] );
	}
	
};

FlowCalc.prototype.init_media = function() {
	var fc        = this;
	var media_ary = document.getElementsByName( 'media' );
	
	for( var i = 0; i < media_ary.length; ++i ) {
		var media = media_ary[i];
		
		media.onclick = function() {
			fc.change_media( this.value );
		};
	}
};

FlowCalc.prototype.change_fluid = function( option ) {
	var gravity = $('gravity');
	
	if( option.value == '' ) {
		gravity.value = '';
		
		this.fluid = null;
	}
	else {
		gravity.value = option.fc_fluid[flowcalc_fluid_gravity_idx];
		
		this.fluid = option.fc_fluid;
	}
};

FlowCalc.prototype.init_fluid = function() {
	var fc    = this;
	var fluid = $('fluid');
	
	fluid.onchange = function() {
		fc.change_fluid( this.options[ this.selectedIndex ] );
	};
};

FlowCalc.prototype.init_cv = function() {
	if( this.cs2 != null ) {
		$('cv').value = this.cv2;
	}
};

FlowCalc.prototype.change_gravity = function( gravity_input ) {
	var fluid = $('fluid');
	
	fluid.value = "";
};


FlowCalc.prototype.init_gravity = function() {
	var fc      = this;
	var gravity = $('gravity');
	
	gravity.onchange = function() {
		fc.change_gravity( this );
	};
};

FlowCalc.prototype.init_pressure = function() {
	var fc = this;
	var p1 = $('p1');
	var p2 = $('p2');
	var dp = $('dp');
	var onchange = function () {
		dp.value = '';
		
		if( isNaN( this.value ) ) {
			alert( '数値を入力してください' );
			this.focus();
			this.select();
			return;
		}
		
		var p1_value = parseFloat( p1.value );
		var p2_value = parseFloat( p2.value );
		
		if( isNaN( p1_value ) || isNaN( p2_value ) ) {
			return;
		}
		
		dp.value = fc.pressure_round( p1_value - p2_value );
	};
	
	p1.onchange = onchange;
	p2.onchange = onchange;
};

FlowCalc.prototype.change_p_unit = function( option ) {
	this.p_unit = option.fc_p_unit;
};

FlowCalc.prototype.init_p_unit = function() {
	var fc = this;
	
	this.set_p_unit_select();
	
	$('p_unit').onchange = function() {
		fc.change_p_unit( this.options[ this.selectedIndex ] );
	};
};

FlowCalc.prototype.change_flow_unit = function( option ) {
	this.flow_unit = option.fc_flow_unit;
};

FlowCalc.prototype.init_flow_unit = function() {
	var fc = this;
	
	this.set_flow_unit_select();
	
	$('flow_unit').onchange = function() {
		fc.change_flow_unit( this.options[ this.selectedIndex ] );
	};
};

FlowCalc.prototype.change_calc_method = function( method ) {
	this.calc_method = method;
	
	if( method == 'flow' ) {
		$('flow').className = '';
		$('cv').className   = 'forInput';
	}else {
		$('flow').className = 'forInput';
		$('cv').className   = '';
	}
};

FlowCalc.prototype.init_calc_method = function() {
	var fc        = this;
	var method_ary = document.getElementsByName( 'method' );
	
	for( var i = 0; i < method_ary.length; ++i ) {
		var method = method_ary[i];
		
		method.onclick = function() {
			fc.change_calc_method( this.value );
		};
	}
};

FlowCalc.prototype.set_p_unit = function( value ) {
	var sel = $('p_unit');
	
	sel.value = value;
	sel.onchange();
};

FlowCalc.prototype.set_flow_unit = function( value ) {
	var sel = $('flow_unit');
	
	sel.value = value;
	sel.onchange();
};

FlowCalc.prototype.get_float_value = function( key ) {
	var obj = $(key);
	var val = obj.value;
	
	if( val == '' ) {
		alert( '入力されていない項目があります' );
		obj.focus();
		return null;
	}
	
	val = parseFloat( val );
	if( isNaN( val ) ) {
		alert( '数値を入力してください' );
		obj.focus();
		obj.select();
		return null;
	}
	
	return val;
};

FlowCalc.prototype.get_pressure = function( key, b_m, c_m ) {
	var p = this.get_float_value( key );
	
	// 圧力単位換算した結果を返す
	return b_m * p + c_m;
};

FlowCalc.prototype.execute = function() {
	var media       = this.media;
	var calc_method = this.calc_method;
	var p_unit      = this.p_unit;
	var flow_unit   = this.flow_unit;
	var a_n         = flow_unit[ flowcalc_flow_unit_a1_idx ];
	var b_m         = p_unit[ flowcalc_p_unit_a2_idx ];
	var c_m         = p_unit[ flowcalc_p_unit_b2_idx ];
	
	// 入力チェック //////////////////////////////////
	
	// 比重
	var gravity = this.get_float_value( 'gravity' );
	if( gravity == null ) {
		return;
	}
	
	// 流体温度
	var temperature = null;
	if( media == 'GAS' ) {
		temperature = this.get_float_value( 'temperature' );
		if( temperature == null ) {
			return;
		}
	}
	
	var p1 = this.get_pressure( 'p1', b_m, c_m );
	if( p1 == null ) {
		return;
	}
	
	var p2 = this.get_pressure( 'p2', b_m, c_m );
	if( p2 == null ) {
		return;
	}
	
	var flow = null;
	var cv   = null;
	if( calc_method == 'flow' ) {
		cv = this.get_float_value( 'cv' );
		if( cv == null ) {
			return;
		}
	}else {
		flow = this.get_float_value( 'flow' );
		if( flow == null ) {
			return;
		}
	}
	
	if( ! ( p1 > p2 ) ) {
		alert( '出口圧力は入口圧力より小さい必要があります。\n圧力値を入力し直してください。' );
		return;
	}
	
	if( ! ( p1 < this.p_max2 * 1.01 )  ) {
		alert( '入口圧力が最大値を超えています。\n圧力値を入力し直してください。' );
//		$('p1').value = this.p_max2;
		$('p1').value = this.pressure_round( ( this.p_max2 - c_m ) / b_m );
		return;
	}
	
	var dp = p1 - p2;
	
	if( dp < this.p_min2 ) {
		alert( '圧力差が最小値より小さくなりました。\n圧力値を入力し直してください。' );
		return;
	}
	
	if( media == 'GAS' || media == 'STEAM' ) {
		dp = Math.min( 0.5 * p1, dp );
	}
	
	// DPフィールドに表示
//	$('dp').value = this.pressure_round( dp );
	$('dp').value = this.pressure_round( ( dp - c_m ) / b_m );
	
	var result;
	if( calc_method == 'flow' ) {
		result = this.calc_flow( media, a_n, cv, temperature, gravity, dp, p1 );
	}else {
		result = this.calc_cv( media, a_n, flow, temperature, gravity, dp, p1 );
	}
	
	$(calc_method).value = this.round( result );
};

FlowCalc.prototype.calc_flow = function( media, unit_rate, cv, t, g, dp, p1 ) {
	var q;
	
	switch( media ) {
	case 'GAS':
		q  = ( 48983 * cv ) / Math.sqrt( ( ( 273 + t ) * g ) / ( dp * ( 2 * p1 + 0.2026 - dp ) ) );
		q /= unit_rate;
		break;
	case 'LIQUID':
		q  = ( 45.58 * cv ) / Math.sqrt( g / dp );
		q /= unit_rate;
		break;
	case 'STEAM':
		q = 138.2 * cv * Math.sqrt( dp * ( 2 * p1 + 0.2026 - dp ) );
		break;
	}
	
	return q;
};

FlowCalc.prototype.calc_cv = function( media, unit_rate, q, t, g, dp, p1 ) {
	var cv;
	
	switch( media ) {
	case 'GAS':
		q *= unit_rate;
		cv = ( q / 48983 ) * Math.sqrt( ( ( 273 + t ) * g ) / ( dp * ( 2 * p1 + 0.2026 - dp ) ) );
		break;
	case 'LIQUID':
		q *= unit_rate;
		cv = ( q / 45.58 ) * Math.sqrt( g / dp );
		break;
	case 'STEAM':
		cv = q / ( 138.2 * Math.sqrt( dp * ( 2 * p1 + 0.2026 - dp ) ) );
		break;
	}
	
	return cv;
};

FlowCalc.prototype.init_execute_button = function() {
	var fc     = this;
	var button = $('execute_calc');
	
	button.onclick = function() {
		fc.execute();
	};
};

FlowCalc.prototype.init = function() {
	var fc = this;
	this.init_media();
	this.init_fluid();
	this.init_gravity();
	this.init_pressure();
	this.init_p_unit();
	this.init_flow_unit();
	this.init_calc_method();
	this.init_execute_button();
	this.init_cv();
	
	var media = $(flowcalc_default_media_id);
	media.checked = true;
	this.change_media( media.value );
	
	var calc_method = $(flowcalc_default_calc_method_id);
	calc_method.checked = true;
	this.change_calc_method( calc_method.value );
	
	$('button_search').onclick = function() {
		var url = flowcalc_product_search_url;
		
		url += '?';
		url += 'cv=' + escape( $('cv').value );
		
		if( ! window.opener || window.opener.closed ) {
			var win = window.open( url );
			win.focus();
		}else {
			window.opener.location.href = url;
		}
		
		window.close();
	};
	
	$('button_close').onclick = function() {
		window.close();
	};
};

function fc_init() {
	var fc = new FlowCalc();
	
	fc.init();
}



