var widthSD = [600,900,1400,1900,2400];
var widthRM = [450,900,1400,1900,2400];
var widthVariations = { 'SD':widthSD, 'RM':widthRM };

var heightSD = [1000,1200,1400,1600,1800,2000,2200];
var heightRM = [1000,1400,1800,2200,2600,3000];
var heightVariations = { 'SD':heightSD, 'RM':heightRM };

var minWidth = { 'SD':250, 'RM':300 };
var maxWidth = { 'SD':2400, 'RM':2400 };
var minHeight = { 'SD':810, 'RM':400 };
var maxHeight = { 'SD':2200, 'RM':3000 };
var minFloor = { 'SD':1600, 'RM':1600 };
var maxFloor = { 'SD':2900, 'RM':2900 };

var CALL = -1;
var NG = -2;

var priceSD1 =  [
	[9200,10000,14200,15300,19600], // -1000
	[9700,10500,15500,16600,21500], // -1200
	[10500,11200,16700,17800,23200], // -1400
	[10700,11500,17500,18500,24200], // -1600
	[11500,12300,18800,19800,26100], // -1800
	[12000,12900,19900,21000,28100], // -2000
	[12400,13400,20700,21700,29200]]; // -2200

var priceSD2 = [
	[9900,10700,16100,17100,22200], // -1000
	[10600,11300,17300,18300,24300], // -1200
	[11500,12300,18800,19800,26300], // -1400
	[12200,12900,20000,21000,28200], // -1600
	[12700,13500,21500,22600,30200], // -1800
	[13300,14200,22700,23800,32300], // -2000
	[14200,15200,24200,25300,34300]]; // -2200

var priceSD3 = [
	[9100,9900,14400,15500,19900], // -1000
	[9300,10000,14600,15600,20000], // -1200
	[10000,10600,15900,16900,22100], // -1400
	[10800,11600,17300,18400,24200], // -1600
	[10800,11700,17500,18500,24300], // -1800
	[11400,12300,19000,20000,26500], // -2000
	[12000,13000,20300,21400,28600]]; // -2200

var priceSD4 = [
	[7800,8600,11900,13000,16300], // -1000
	[8300,9000,12600,13700,17300], // -1200
	[8800,9600,13500,14600,18500], // -1400
	[9200,10000,14200,15300,19700], // -1600
	[9500,10300,15100,16100,20700], // -1800
	[9800,10800,15800,16900,21900], // -2000
	[10200,11200,16500,17600,22900]]; // -2200
	
var priceRM1 = [
	[10800,13200,15000,20600,23200], // -1000
	[12200,14500,16600,23100,25900], // -1400
	[13500,15900,18100,25600,28500], // -1800
	[14900,17300,19500,28100,31200], // -2200
	[16300,18800,21000,30700,33800], // -2600
	[17600,20100,22500,33300,36500]]; // -3000
	
var priceList = {
	'SD1':priceSD1, 'SD2':priceSD2, 'SD3':priceSD3, 'SD4':priceSD4,
	'RM1':priceRM1 };
	
var colorSD = [
	['CK225_SD1','CK225'],
	['CK226_SD1','CK226'],
	['CK227_SD1','CK227'],
	['CK228_SD1','CK228'],
	['CK340_SD2','CK340'],
	['CK341_SD2','CK341'],
	['CK342_SD2','CK342'],
	['CK343_SD2','CK343'],
	['CK625_SD3','CK625'],
	['CK1015_SD4','CK1015'],
	['CK1016_SD4','CK1016'],
	['CK1017_SD4','CK1017'],
	['CK1018_SD4','CK1018']];
	
var colorRM = [
	['58591_RM1','58591'],
	['58592_RM1','58592'],
	['58593_RM1','58593'],
	['58594_RM1','58594'],
	['58595_RM1','58595']];

var groupList = { 'SD':colorSD, 'RM':colorRM };

var labels = {
	'group':['ローマンシェード タイプ', {
		'RM':'リリカラ・エムフロント',
		'SD':'サンゲツ・デザイン'
	}],
	'colorType':['カラー', {
		'CK225_SD1':'CK225',
		'CK226_SD1':'CK226',
		'CK227_SD1':'CK227',
		'CK228_SD1':'CK228',
		'CK340_SD2':'CK340',
		'CK341_SD2':'CK341',
		'CK342_SD2':'CK342',
		'CK343_SD2':'CK343',
		'CK625_SD3':'CK625',
		'CK1015_SD4':'CK1015',
		'CK1016_SD4':'CK1016',
		'CK1017_SD4':'CK1017',
		'CK1018_SD4':'CK1018',
		'58591_RM1':'58591',
		'58592_RM1':'58592',
		'58593_RM1':'58593',
		'58594_RM1':'58594',
		'58595_RM1':'58595'
	}],
	'handleType':['操作タイプ', {
		'-':'標準仕様',
		'C':'コード式'
	}],
	'chainPosition':['チェーンの位置', {
		'-':'標準仕様',
		'right':'右',
		'left':'左'
	}],
	'attachStyle':['窓枠への取付', {
		'ceiling':'天井',
		'wall':'正面'
	}],
	'orderWidth':['製品サイズ幅(ミリ)', {}],
	'orderHeight':['製品サイズ丈(ミリ)', {}],
	'floorHeight':['床より本体上部高(ミリ)', {
		'u1500':'1500mm以下',
		'o3000':'3000mm以上'
	}]
};

var pids = { 'SD':'SSD901', 'RM':'SRM901' };

function getGroup() { return $('#group').val(); }
function getHandleType() { return $('#handleType').val(); }
function getColorType() { return $('#colorType').val(); }
function getBalanceType() { return $('#balanceType').val(); }
function getChainPosition() { return $('#chainPosition').val(); }
function getAttachStyle() { return $('#attachStyle').val(); }
function getOrderWidth() { return $('#orderWidth').val(); }
function getOrderHeight() { return $('#orderHeight').val(); }
function getFloorHeight() { return $('#floorHeight').val(); }
function getNumItems() { return $('#numItems').val(); }

var validations = [
	['required', '#group', 'ローマンシェードの種類を選択してください。'],
	['required', '#handleType', '操作タイプを指定してください。'],
	['required', '#colorType', '生地の種類を選択してください。'],
	['required', '#chainPosition', 'チェーンの位置を選択してください。'],
	['required', '#attachStyle', '窓枠への取付方法を選択してください。'],
	['required', '#orderWidth', '製品サイズ・幅を指定してください。'],
	['required', '#orderHeight', '製品サイズ・丈を指定してください。'],
	['required', '#floorHeight', '床上高を指定してください。'],
	['f', validateFloorHeight]];

function getMtxPos(w, h) {
	var t = getGroup();
	if (!t || !w || !h) return false;
	
	var hv = heightVariations[t];
	var wv = widthVariations[t];
	for (var i = 0; i < hv.length; i++) {
		if (h <= hv[i]) {
			for (var j = 0; j < wv.length; j++) {
				if (w <= wv[j]) return [i, j];
			}
			return false;
		}
	}
	return false;
}

function getUnitPrice() {
	if (!isReadyToCalculatePrice()) return false;

	var pos = getMtxPos(getOrderWidth(), getOrderHeight());
	if (!pos) return false;
	var priceList = getPriceList();
	return priceList[pos[0]][pos[1]];
}

function getPrice() {
	var unitPrice = getUnitPrice();
	if (!unitPrice) return false;
	
	var price = unitPrice * (
		$('#numItems').size() > 0 ? Number($('#numItems').val()) : 1);
	
	return price;
}

function isReadyToCalculatePrice() {
	return (
		getGroup() != ''
		&& getColorType() != ''
		&& getOrderWidth() != ''
		&& getOrderHeight() != '');
}

function doUpdatePrice() {
	console.log('doUpdatePrice()');
	
	var changeIt = function (s) {
		$('#estimatePrice').text(s);
		$('#estimateTotalPrice').text(s);
		$('#estimateShipping').text(s == '―' ? '―' : '0');
	};
	
	if (!isReadyToCalculatePrice()) {
		changeIt('―');
		showCallme(false);
		return;
	}

	var priceLabel = getPrice() < 0 ? "―" : addComma(getPrice());
	console.log('priceLabel='+ priceLabel);
	changeIt(priceLabel);
	
	if (getPrice() < 0) {
		$('#callme').text('この寸法での価格については、お問い合わせください。');
		$('#intoCart').attr('disabled', 'disabled');
		showCallme(true);
	}
	else {
		$('#intoCart').removeAttr('disabled');
		showCallme(false);
	}
}

function showCallme(b) {
	var o = $('#callme');
	if (o.css('display') == 'none') {
		if (b) o.show('normal');
	}
	else {
		if (!b) o.hide('normal');
	}
}

function changeColorType(v) {
	var o = $('#colorType');
	hideSample(o);
	o.empty();
	
	if (getGroup() == '') {
		o.append(newOption('', '↑ 先にローマンシェードタイプをお選びください'));
		return;
	}
	
	o.append(newOption('', '▽ ここをクリックしてお選びください'));
	var colors = groupList[getGroup()];
	for (var i = 0; i < colors.length; i++) {
		if (!colors[i]) break;
		o.append(newOption(colors[i][0], colors[i][1], v));
	}
}

function getPriceList() {
	if (!isReadyToCalculatePrice()) return false;
	
	var colorGroup = getColorType().split('_')[1];
	console.log('colorGroup ='+colorGroup );
	return priceList[colorGroup];
}

function hideSample(o) {
	var d = $(o).parent().find('.sample');
	if (d.css('display') != 'none') {
		d.hide('normal');
	}
}

function newOption(v, t, d) {
	var o = document.createElement('option');
	if (v == d) o.setAttribute('selected', 'selected');
	return $(o).val(v).text(t);
}

function addComma(value) {
	var s = String(value);
	for (var i = 0; i < s.length / 3; i++) {
		s = s.replace(/^([+-]?\d+)(\d\d\d)/, "$1,$2");
	}
	return s;
}

function validateFloorHeight() {
	if (getFloorHeight() == 'o3000') return true;
	
	var floor = getFloorHeight() == 'u1500' ? 1500 : Number(getFloorHeight());
	var order = Number(getOrderHeight());
	if (floor < order) {
		alert('床上高は製品サイズ・丈よりも大きい値を指定してください。');
		$('#floorHeight').get(0).focus();
		return false;
	}
	return true;
}

function validateChooser() {
	for (var i = 0; i < validations.length; i++) {
		var entry = validations[i];
		
		if (entry[0] == 'required') {
			if (!required(entry[1], entry[2])) return false;
		}
		else if (entry[0] == 'f') {
			if (!entry[1]()) return false;
		}
	}
	return true;
}

function required(id, msg) {
	var v = $(id).val();
	if (!v || v == '') {
		alert(msg);
		$(id).parent().ScrollTo(800, 'easeout');
		setTimeout(function () { $(id).get(0).focus(); }, 1000);
		return false;
	}
	return true;
}

function showDetail(o) {
	var d = $(o).parent().parent().find('.detail');
	if (!d) return;
	
	if (d.css('display') == 'none') {
		d.show('normal');
	}
	else {
		d.hide('normal');
	}
}

function onClickIntoCart() {
	doUpdatePrice();
	if (!validateChooser()) return false;
	
	document.cartForm.PID.value = pids[getGroup()];
	document.cartForm.TANKA.value = getUnitPrice();
	document.cartForm.QTY.value = document.chooserForm.numItems.value;
	
	removeOrderOptions();
	
	var cf = $('#cartForm');
	var options = []
	for (var i = 0; i < document.chooserForm.length; i++) {
		var o = document.chooserForm[i];
		if (o.type == 'button') continue;
		if (!labels[o.name]) continue;
		
		var key = labels[o.name][0];
		var value = labels[o.name][1][o.value];
		if (!value) value = o.value;
		
		if (o.name == 'orderWidth') {
			key = labels['orderWidth'][0] +'×'+ labels['orderHeight'][0];
			value = getOrderWidth() +'×'+ getOrderHeight();
		}
		if (o.name == 'orderHeight') continue;

		options.push(key +': '+ value);
	}
	
	document.cartForm.MEMO.value = options.join('\n');
	
	for (var i = 0; i < document.cartForm.length; i++) {
		var o = document.cartForm[i];
		console.log(o.name +':'+ o.value);
	}
	
	document.cartForm.submit();
}

function hiddenNameValue(cf, name, value) {
	cf.append('<input type="hidden" name="'+ name +'" />');
	$('input[name='+ name +']', cf).val(value);
}

function removeOrderOptions() {
	$('#cartForm input').each(function () {
		var o = $(this);
		if (o.attr('name').indexOf('option') === 0) o.remove(); 
	});
}

function showChoice(o, sw) {
	var div = o.parent();
	if (sw) {
		div.show().next().show();
	}
	else {
		div.hide().next().hide();
	}
}

function onChangeHandleType() {
	$.cookie('handleType', getHandleType());
}

function onChangeChainPosition() {
	$.cookie('chainPosition', getChainPosition());
}

function onChangeColorType() {
	$.cookie('colorType', getColorType());
	
	var t = this;
	var d = $(t).parent().find('.sample');
	
	var showIt = function () {
		if (!t.value) return;
		
		return; // none of sample
		
		d.find('img').attr('src', 'screen_img/'+ t.value +'s.jpg');
		d.show('normal');
	}
	
	if (d.css('display') != 'none') {
		d.hide('normal', showIt);
	}
	else {
		showIt(t);
	}
	
	doUpdatePrice();
}

function onChangeOrderWidth() {
	$.cookie('orderWidth', getOrderWidth());
	doUpdatePrice();
}

function onChangeOrderHeight() {
	$.cookie('orderHeight', getOrderHeight());
	doUpdatePrice();
}

function onChangeAttachStyle() {
	$.cookie('attachStyle', getAttachStyle());
}

function onChangeFloorHeight() {
	$.cookie('floorHeight', getFloorHeight());
}

var preloadedImages = new Array();
function preload() {
	console.log('preloading...');
	
	for (var i in groupList) {
		for (var j = 0; j < groupList[i].length; j++) {
			var img = new Image();
			img.src = 'screen_img/'+ groupList[i][j][0] +'.jpg';
			//console.log('loading:'+ img.src);
			preloadedImages.push(img);
		}
	}
}

function onChangeNumItems() {
	$.cookie('numItems', getNumItems());
	doUpdatePrice();
}

function onChangeGroup() {
	$.cookie('group', getGroup());
	changeHandleType();
	changeColorType();
	changeChainPosition();
	changeOrderWidth();
	changeOrderHeight();
	changeFloorHeight();
	doUpdatePrice();
}

function changeHandleType(v) {
	var o = $('#handleType');
	o.empty();
	
	if (getGroup() == '') {
		o.append(newOption('', '↑ 先にローマンシェードタイプをお選びください'));
		return;
	}
	
	o.append(newOption('C', 'コード式'));
}

function changeChainPosition(v) {
	var o = $('#chainPosition');
	o.empty();
	
	o.append(newOption('', '▽ ここをクリックしてお選びください'));
	o.append(newOption('right', '右', v));
	o.append(newOption('left', '左', v));
}

function changeOrderWidth(v) {
	var o = $('#orderWidth');
	o.empty();
	
	if (getGroup() == '') {
		o.append(newOption('', '↑ 先にローマンシェードタイプをお選びください'));
		return;
	}
	
	o.append(newOption('', '▽'));
	
	var min = minWidth[getGroup()];
	var max = maxWidth[getGroup()];
	for (var i = min; i <= max; i += 10) {
		o.append(newOption(i, i, v));
	}
}

function changeOrderHeight(v) {
	var o = $('#orderHeight');
	o.empty();
	
	if (!getGroup()) {
		o.append(newOption('', '↑ 先にローマンシェードタイプをお選びください'));
		return;
	}
	
	o.append(newOption('', '▽'));
	
	var min = minHeight[getGroup()];
	var max = maxHeight[getGroup()];
	for (var i = min; i <= max; i += 10) {
		o.append(newOption(i, i, v));
	}
}

function changeFloorHeight(v) {
	var o = $('#floorHeight');
	o.empty();
	
	if (!getGroup()) {
		o.append(newOption('', '↑ 先にローマンシェードタイプをお選びください'));
		return;
	}
	
	o.append(newOption('', '▽'));
	o.append(newOption('u1500', '1500mm 以下', v));
		
	var min = minFloor[getGroup()];
	var max = maxFloor[getGroup()];
	for (var i = min; i <= max; i+=100) {
		o.append(newOption(i, i, v));
	}

	o.append(newOption('o3000', '3000mm 以上', v));
}

function changeAttachStyle(v) {
	$('#attachStyle').val(v ? v : '');
}

function changeNumItems(v) {
	$('#numItems').val(v ? v : '1');
}

function initSelectors() {
	$('#group').val($.cookie('group'));

	changeHandleType($.cookie('handleType'));
	changeColorType($.cookie('colorType'));
	changeChainPosition($.cookie('chainPosition'));
	changeAttachStyle($.cookie('attachStyle'));
	changeOrderWidth($.cookie('orderWidth'));
	changeOrderHeight($.cookie('orderHeight'));
	changeFloorHeight($.cookie('floorHeight'));
	changeNumItems($.cookie('numItems'));
}

function run(f) {
	setTimeout(f, 10);
}

$(document).ready(function() {
	console.log('document.ready');
	
	initbox(); // dropdown box
	
	$('.guideButton').click(function () { showDetail(this); });
	
	$('#group').change(onChangeGroup);
	$('#handleType').change(onChangeHandleType);
	$('#colorType').change(onChangeColorType);
	$('#chainPosition').change(onChangeChainPosition);
	$('#attachStyle').change(onChangeAttachStyle);
	$('#orderWidth').change(onChangeOrderWidth);
	$('#orderHeight').change(onChangeOrderHeight);
	$('#floorHeight').change(onChangeFloorHeight);
	$('#numItems').change(onChangeNumItems);
	$('#intoCart').click(onClickIntoCart);
	
	initSelectors();
	doUpdatePrice();
	run(preload);
});
