
$(function(){
	$('body').data('id_last',1);
	$('div.estimate thead').find('td:first').html( $('h3').text());
	$('div.estimate tbody').find('tr.input:first td').eq(2).html(f_num(1,1));
	
	$('tbody input[name=add]').live('click',function(){ add_row($(this));});

	$('input[name=delete]').live('click',function(){delete_row($(this));});
	
	
	$('input[name=calc]').live('click',function(){ calc(get_tableid($(this)));});

});
function get_tableid(slct){
		var tid = slct.attr('id').replace(/t([0-9]+)_b([0-9]+)/,'$1');
		return tid;
}
function calc(tid){
		var slct = $('table#t'+tid);
		//var num_pr = $('select#t'+tid + '_pr').val();
		//var per = a_p[num_pr][1];
		var per = $('table td.price_basic').text().replace(/(.)(.*)\/(.*)mm2/,'$2');
		var i = 0;
		var space = 0;
		var text_textarea = '';
		slct.find('tr.input').each(function(i){
			i++;
			var h,w,num;
			$(this).find('input[type=text],select').each(function(){
			var type = $(this).attr('id').replace(/t([0-9]+)_(.*)([0-9]+)/,'$2');
				switch(type){
					case 'h':
						h = $(this).val();
						break;
					case 'w':
						w = $(this).val();
						break;
					case 'num':
						num = $(this).val();
						break;
				}
			});
			space_this = Math.ceil( (h-4) * (w-4) * num / 100000 ) / 10;
			space += space_this;
			
			text_textarea += '縦：' + (h-4) + 'mm' +  ' × 横：' + (w-4) + 'mm（' + space_this  + '平方M）が' + num + '枚\n';
		});
		space = Math.floor(space * 10) / 10 ;
		var text_space = '<span>' + space + '</span>m<sup>2</sup>';
		
		var cost_total;
		cost_total = Math.ceil(space * per * 10);
		text_cost = '<span>' + comma(cost_total) + '</span>円';
		
		$('input').each(function(){
			if($(this).attr('id').match(/quant(.*)/)){
				$(this).val(space);
			}
		});
		$('textarea').val(text_textarea);
		/*
		if(num_pr>0){
				cost_total = Math.ceil(space * per * 10);
			text_cost = '<span>' + comma(cost_total) + '</span>円';
		}else{
			text_cost = '商品を選択下さい';
		}
		*/
		$('#t'+tid+'_space').html(text_space).css(
			{
				opacity:'0',
				backgroundColor:'#ff0000'
			}
		).animate(
			{
				opacity:1,
				backgroundColor:'#ffffff'
			},function(){
		$('#t'+tid+'_price').html(text_cost).css(
			{
				opacity:'0',
				backgroundColor:'#ff0000'
			}
		).animate(
			{
				opacity:1,
				backgroundColor:'#ffffff'
			}
		);
			});
}

function add_table(){
	var num_table;
	if( $('body').data('num_table') > 0){
		num_table = $('body').data('num_table');
	}else{
		num_table = 1;
	}
	
	num_table++;
	var str_html = '<div id="t' + num_table + '" class="input_table"><table><thead><tr><th>商品名</th><td colspan="3">';
	str_html += f_pr(num_table) + '</td></tr></thead><tbody><tr><th>縦</th><th>横</th><th>枚数</th><th>行削除</th></tr>';
	str_html += '<tr class="input" id="t'+num_table+'_row1"><td><input size="5" value="" id="t'+num_table+'_h1" type="text">mm</td>\<td><input size="5" value="" id="t'+num_table+'_w1" type="text">mm</td>\<td>';
	str_html += f_num(num_table,1);
	str_html += '</td><td><input type="button" id="t'+num_table+'_delete1" name="delete" value="削除" /></td></tr>';
	str_html += '<tr><td colspan="3" id="t'+num_table+'_space">-</td><td><input id="t' + num_table + '_add" name="add" value="行追加" type="button"></td></tr>';
	str_html += '<tr><td id="t' + num_table + '_price" colspan="3">-</td><td class="button" colspan="4"><input id="t' + num_table + '_b1" value="計算する" type="button" name="calc" /></td></tr></tbody></table></div>';
	$('body').data('num_table',num_table);
	$(str_html).insertBefore('p#button_addtable').hide().slideDown('slow');
}

function delete_row(slct){
		var tid = slct.attr('id').replace(/t([0-9]+)_delete([0-9]+)/,'$1');
		var id = slct.attr('id').replace(/t([0-9]+)_delete([0-9]+)/,'$2');
		var rest_count_row = $("table#t"+tid+' tr.input').length;
		var rest_count_table = $('div.input_table table').length;
		var slct_target = $('#t'+tid+' tr#t'+tid+'_row'+id);

			if($('body').data('id_last') == id){
				var id_last = slct_target.prev().attr("id").replace(/t([0-9]+)_row([0-9]+)/,'$2');
				$('body').data('id_last',id_last);
			}
		if( rest_count_row > 1){
			slct_target.fadeOut('slow').queue(function(){
				slct_target.remove();
				calc(tid);
			});
			
		}else if(rest_count_row == 1 && rest_count_table > 1 ){
			$('div#t' + tid).animate({opacity:0},'slow').slideUp('fast',function(){$('div#t' + tid).remove();});

		}else{
			alert("削除できません。");
		}
}


function add_row(slct){
	var tid = slct.attr("id").replace(/t([0-9]+)_add/g,'$1');
	var this_div = $('#t'+tid);
	var num_row ;
	if( this_div.data('num_row') > 0){
		num_row = this_div.data('num_row');
	}else{
		num_row = 1;
	}

	var id_last = $('body').data('id_last');

	var id = id_last*1 + 1;
	str_html = '<tr class="input" id="t'+tid+'_row'+id+'"><td><input size="5" value="" id="t'+tid+'_h'+id+'" type="text">mm</td>\<td><input size="5" value="" id="t'+tid+'_w'+id+'" type="text">mm'+id+'</td>\<td>';

	str_html += f_num(tid,id);
	str_html += '</td><td><input type="button" id="t'+tid+'_delete'+id+'" name="delete" value="削除" /></td></tr>';
	num_row++;
	$('body').data('id_last',id);
	this_div.data('num_row',num_row);

	$(str_html).insertAfter('tr#t1_row'+id_last).hide().fadeIn('slow');
}

var a_p = new Array("",
	new Array("強防犯 透明 GS350",560),
	new Array("準防犯 透明 GS200K",400),
	new Array("飛散防止 透明 GS50K-BF",200),
	new Array("飛散防止 透明（外貼り） GS50KExt-BF",240),
	new Array("熱線反射シルバー 60A 50A 35A 20A 15A",320),
	new Array("熱線反射シルバー（外貼り） RS20AE 35AE",320),
	new Array("透明 遮熱・断熱 IRC+SpG SL7480",720),
	new Array("プライバシー ホワイトアウトNF",400),
	new Array("プライバシー ホワイトマットNF",320)
);

function f_pr(tid){
	var output = '<select id="t'+tid+'_pr">\n';
	output += '<option value="0">商品を選択下さい</option>\n';
	for (var i = 1; i < a_p.length; i ++) {
		output += '<option value="' + i + '">' + a_p[i][0] + '</option>\n';
	}
	output += '</select>';
	return output;
}

function f_num(tid,id){
	var output = '<select id="t'+tid+'_num' + id + '">\n';
	output += '<option value="0">枚数を選択</option>\n';
	for (var i = 1; i <= 10; i ++) {
		output += '<option value="' + i + '">' + i + '枚</option>\n';
	}
	output += '</select>';
	return output;
}

function f_sum(id){
	var p = $('#pr_' + id + ' option:selected').val();
	var h = Fulltohalf($('#h_' + id).val());
	var w = Fulltohalf($('#w_' + id).val());
	var num = $('#num_' + id + ' option:selected').val();
	
	var err = new Array();
	if( p < 1){ err.push("商品を選択下さい");}
	if( !w.match(/\d/) || w%1 > 0 ){ err.push("横幅には整数を入力下さい");}
	if( !h.match(/\d/) || h%1 > 0  ){ err.push("縦幅には整数を入力下さい");}
	if( num < 1){ err.push("枚数を選択下さい");}
	
	if( err.length == 0 ){
		var by = h * w;
		var text = by + '<span>mm<sup>2</sup></span>';
		$('#w_'+id).val(w);
		$('#h_'+id).val(h);
		$('#n_'+id).val(num);
		$('#price_'+id).html(text).css(
			{
				opacity:'0',
				backgroundColor:'#ff0000'
			}
		).animate(
			{
				opacity:1,
				backgroundColor:'#ffffff'
			}
		);
	}else{
		var str_err = "";
		for(var n = 0;n< err.length;n++){
			str_err += err[n] + '\n';
		}
			alert (str_err);
	}
}


function Fulltohalf(data){
	//全角数字配列
var char1 = new Array("１","２","３","４","５","６","７","８","９","０");
	//半角数字配列
var char2 = new Array(1,2,3,4,5,6,7,8,9,0);
var count;
	while(data.match(/[０-９]/)){     	//入力データに全角数字がある場合
		for(count = 0; count < char1.length; count++){
				//入力データを全角数字から半角数字に置換する
			data = data.replace(char1[count], char2[count]);
		}
	}
	return(data);
}

function comma(num) {
    return num.toString().replace( /([0-9]+?)(?=(?:[0-9]{3})+$)/g , '$1,' );
} 
