/*@cc_on _d=document;eval('var document=_d')@*/

var widthO = [600,800,1000,1100,1200,1300,1400,1500,1600,1700,1800]; // orgon
var widthS = [800,1000,1200,1400,1600,1800,2000,2200,2400]; // sunstrip
var widthY = [800,1200,1600,2000]; // yokota
var widthT = [600,900,1350,1800,2000]; // tkw
var widthTRMY = [600,900,1350,1800]; // tkw 無地浴室 ウォッシャブル
var widthVariations = {
	'G1':widthO, 'G2':widthO, 'G3':widthO, 'G4':widthO, 'S':widthS, // orgon
	'YP':widthY, 'YS':widthY, // yokota
	'TW':widthT, 'TR':widthT, // tkw
	'TRMB':widthT, 'TRTW':widthT, 'TR3W':widthT, 'TR2':widthT,
	'TR2B':widthT, 'TR1':widthT, 'TRMY':widthTRMY };

var heightO = [1000,2000,2500]; // orgon
var heightS = [800,1000,1200,1400,1600,1800,2000,2200,2400,2600]; // sunstrip
var heightY = [1200,1800,2400,3000]; // yokota
var heightT = [900,1800,2000,2500,3000]; // tkw
var heightTRMY = [900,1800,2000,2500,3000]; // tkw 無地浴室 ウォッシャブル
var heightVariations = {
	'G1':heightO, 'G2':heightO, 'G3':heightO, 'G4':heightO, 'S':heightS, // orgon
	'YP':heightY, 'YS':heightY, // yokota
	'TW':heightT, 'TR':heightT, // tkw
	'TRMB':heightT, 'TRTW':heightT, 'TR3W':heightT, 'TR2':heightT,
	'TR2B':heightT, 'TR1':heightT, 'TRMY':heightTRMY };

var minWidth = {
	'G1':300, 'G2':300, 'G3':300, 'G4':300, 'S':400, // orgon
	'YP':300, 'YS':300, // yokota
	'TW':300, 'TR':300, // tkw
	'TRMB':300, 'TRTW':300, 'TR3W':300, 'TR2':300,
	'TR2B':300, 'TR1':300, 'TRMY':300 };
var maxWidth = {
	'G1':1200, 'G2':1200, 'G3':1200, 'G4':1200, 'S':2400, // orgon
	'YP':2000, 'YS':2000, // yokota
	'TW':2000, 'TR':2000, // tkw
	'TRMB':2000, 'TRTW':2000, 'TR3W':2000, 'TR2':2000,
	'TR2B':2000, 'TR1':2000, 'TRMY':1800 };
	
var minHeight = {
	'G1':500, 'G2':500, 'G3':500, 'G4':500, 'S':400, // orgon
	'YP':500, 'YS':500, // yokota
	'TW':300, 'TR':300, // tkw
	'TRMB':300, 'TRTW':300, 'TR3W':300, 'TR2':300,
	'TR2B':300, 'TR1':300, 'TRMY':300 };
var maxHeight = {
	'G1':2000, 'G2':2000, 'G3':2000, 'G4':1800, 'S':2600, // orgon
	'YP':3000, 'YS':3000, // yokota
	'TW':3000, 'TR':3000, // tkw
	'TRMB':3000, 'TRTW':3000, 'TR3W':3000, 'TR2':3000,
	'TR2B':3000, 'TR1':3000, 'TRMY':1800 };
	
var minFloor = {
	'G1':1000, 'G2':1000, 'G3':1000, 'G4':1000, 'S':1000, // orgon
	'YP':1600, 'YS':1600, // yokota
	'TW':1100, 'TR':1100, // tkw
	'TRMB':1100, 'TRTW':1100, 'TR3W':1100, 'TR2':1100,
	'TR2B':1100, 'TR1':1100, 'TRMY':1100 };
var maxFloor = {
	'G1':3000, 'G2':3000, 'G3':3000, 'G4':3000, 'S':3000, // orgon
	'YP':2900, 'YS':2900, // yokota
	'TW':2900, 'TR':2900, // tkw
	'TRMB':2900, 'TRTW':2900, 'TR3W':2900, 'TR2':2900,
	'TR2B':2900, 'TR1':2900, 'TRMY':2900 };

var priceList = {
	'G1':price1, 'G2':price2, 'G3':price3, 'G4':price4, 'S':priceS,
	'YP':priceYP, 'YS':priceYS,
	'TW':priceTW, 'TR':priceTR,
	'TRMB':priceTRMB, 'TRTW':priceTRTW, 'TR3W':priceTR3W, 'TR2':priceTR2,
	'TR2B':priceTR2B, 'TR1':priceTR1, 'TRMY':priceTRMY };

var groupList = {
	'G1':group1, 'G2':group2, 'G3':group3, 'G4':group4, 'S':groupS,
	'YP':groupYP, 'YS':groupYS,
	'TW':groupTW, 'TR':groupTR,
	'TRMB':groupTRMB, 'TRTW':groupTRTW, 'TR3W':groupTR3W, 'TR2':groupTR2,
	'TR2B':groupTR2B, 'TR1':groupTR1, 'TRMY':groupTRMY };

var labels = {
	'group':['ロールスクリーンタイプ', {
		'G1':'オルゴン スタンダード',
		'G2':'GROUP-2',
		'G3':'オルゴン プレミアム',
		'G4':'GROUP-4',
		'S':'オルゴン サンストリップ',
		'YP':'SUNNY プレーン',
		'YS':'SUNNY 遮光',
		'TW':'TKW ウォッシャブル',
		'TR':'TKW リーズナブル',
		'TRMB':'TKW 無地防炎',
		'TRTW':'TKW シースルー ウォッシャブル',
		'TR3W':'TKW 遮光3級 ウォッシャブル',
		'TR2':'TKW 遮光2級',
		'TR2B':'TKW 遮光2級 防炎',
		'TR1':'TKW 遮光1級',
		'TRMY':'TKW 無地浴室 ウォッシャブル'
	}],
	'screenType':['生地の種類', {}],
	'handleType':['操作タイプ', {
		'-':'標準仕様',
		'S':'スプリング式',
		'C':'チェーン式',
		'P':'プルコード式'
	}],
	'partsColor':['部品カラー', {
		'-':'標準仕様',
		'white':'オフホワイト',
		'brown':'ダークブラウン'
	}],
	'chainPosition':['チェーンの位置', {
		'-':'標準仕様',
		'right':'右',
		'left':'左'
	}],
	'attachStyle':['窓枠への取付', {
		'ceiling':'天井',
		'wall':'正面'
	}],
	'orderWidth':['製品サイズ幅(ミリ)', {}],
	'orderHeight':['製品サイズ丈(ミリ)', {}],
	'floorHeight':['床より本体上部高(ミリ)', {
		'u1000':'1000mm以下',
		'u1500':'1500mm以下',
		'o3000':'3000mm以上'
	}]
};

var pids = {
	'G1':'ROS901', 'G2':'ROS901', 'G3':'ROP901', 'G4':'ROP901', 'S':'ROU901', // orgon
	'YP':'RYSP01', 'YS':'RYSS01', // yokota
	'TW':'RT9901', 'TR':'RT9901', // tkw
	'TRMB':'RT9901', 'TRTW':'RT9901', 'TR3W':'RT9901', 'TR2':'RT9901',
	'TR2B':'RT9901', 'TR1':'RT9901', 'TRMY':'RT9901' };
	
function getGroup() { return $('#group').val(); }
function getHandleType() { return $('#handleType').val(); }
function getScreenType() { return $('#screenType').val(); }
function getPartsColor() { return $('#partsColor').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', '#screenType', '生地の種類を選択してください。'],
	['required', '#partsColor', '部品カラーを選択してください。'],
	['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;
	
	if (getGroup().charAt(0) == 'T' && getHandleType() == 'P') { // tkw && プルコード
		if (getOrderWidth() <= 600) {
			if (getOrderHeight() > 1800) return NG;
		}
		else {
			if (getOrderHeight() > 2500) return NG;
		}
	}
	
	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() != ''
		&& 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 changeScreenType(v) {
	var o = $('#screenType');
	hideSample(o);
	o.empty();
	
	if (getGroup() == '') {
		o.append(newOption('', '↑ 先にスクリーンタイプをお選びください'));
		return;
	}
	
	o.append(newOption('', '▽ ここをクリックしてお選びください'));
	var screens = groupList[getGroup()];
	for (var i = 0; i < screens.length; i++) {
		if (!screens[i]) break;
		o.append(newOption(screens[i][0], screens[i][1], v));
	}
}

function getPriceList() {
	if (!isReadyToCalculatePrice()) return false;
	return priceList[getGroup()];
}

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 == 'screenType') {
			var text = $(o).find('option:selected').text(); 
			value = (value == text) ? value : (value +' '+ text);
		}
		
		if (o.name == 'orderWidth') {
			key = labels['orderWidth'][0] +'×'+ labels['orderHeight'][0];
			value = getOrderWidth() +'×'+ getOrderHeight();
		}
		if (o.name == 'orderHeight') continue;
		
		if (isYokota() || isTkw()) {
			if (o.name == 'chainPosition'
				&& (getHandleType() == 'S'
					|| getHandleType() == 'P')) continue;
		}
		else {
			if (o.name == 'handleType') continue;
		}
		
		if (!isTkw() && o.name == 'partsColor') 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());
	changeOrderHeight();
	changeChainPosition();
	doUpdatePrice();
}

function onChangeChainPosition() {
	$.cookie('chainPosition', getChainPosition());
}

function onChangeScreenType() {
	$.cookie('screenType', getScreenType());

	var t = this;
	var d = $(t).parent().find('.sample');
	
	var showIt = function () {
		if (!t.value) return;
		var g0 = getGroup().charAt(0); 
		if (g0 == 'T' || g0 == 'Y' || g0 == 'S') return; // sunstrip, yokota, tkw なし
		
		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);
	}
}

function onChangePartsColor() {
	$.cookie('partsColor', getPartsColor());
}

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();
	changeScreenType();
	changePartsColor();
	changeChainPosition();
	changeOrderWidth();
	changeOrderHeight();
	changeFloorHeight();
	doUpdatePrice();
}

function isYokota() {
	return getGroup().charAt(0) == 'Y';
}

function isTkw() {
	return getGroup().charAt(0) == 'T';
}

function changeHandleType(v) {
	var o = $('#handleType');
	showChoice(o, true);
	o.empty();
	
	if (getGroup() == '') {
		o.append(newOption('', '↑ 先にスクリーンタイプをお選びください'));
		return;
	}
	
	if (isYokota()) {
		o.append(newOption('', '▽ ここをクリックしてお選びください'));
		o.append(newOption('S', 'スプリング式', v));
		o.append(newOption('C', 'チェーン式', v));
	}
	else if (getGroup() == 'TRMY') {
		o.append(newOption('P', 'プルコード式', v));
	}
	else if (isTkw() && getGroup() != 'TRMY') {
		o.append(newOption('', '▽ ここをクリックしてお選びください'));
		o.append(newOption('P', 'プルコード式', v));
		o.append(newOption('C', 'チェーン式', v));
	}
	else {
		o.append(newOption('-', '標準仕様'));
	}
	
	showChoice(o, isYokota() || isTkw());
}

function changeChainPosition(v) {
	var o = $('#chainPosition');
	showChoice(o, true);
	o.empty();
	
	if (!getGroup()) {
		o.append(newOption('', '↑ 先にスクリーンタイプをお選びください'));
		return;
	}
	
	if (isYokota() || isTkw()) {
		if (!getHandleType()) {
			o.append(newOption('', '↑ 先に操作タイプをお選びください'));
			return;
		}
	}
	
	var h = getHandleType();
	if (h == 'S' || h == 'P') {
		o.append(newOption('-', '標準仕様'));
	}
	else {
		o.append(newOption('', '▽ ここをクリックしてお選びください'));
		o.append(newOption('right', '右', v));
		o.append(newOption('left', '左', v));
	}
	
	showChoice(o, h != 'S' && h != 'P');
}

function changePartsColor(v) {
	var o = $('#partsColor');
	showChoice(o, true);
	o.empty();

	if (isTkw()) {
		o.append(newOption('', '▽ ここをクリックしてお選びください'));
		o.append(newOption('white', 'オフホワイト', v));
		o.append(newOption('brown', 'ダークブラウン', v));
	}
	else {
		o.append(newOption('-', '標準仕様'));
	}
	
	showChoice(o, isTkw());
}

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 (!getHandleType()) {
		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('', '▽'));
	
	var t = getGroup().charAt(0);
	if (t == 'Y') {
		o.append(newOption('u1500', '1500mm 以下', v));
	}
	else if (t == 'T') {
		o.append(newOption('u1000', '1000mm 以下', v));
	}
		
	var min = minFloor[getGroup()];
	var max = maxFloor[getGroup()];
	for (var i = min; i <= max; i+=100) {
		o.append(newOption(i, i, v));
	}

	if (t == 'Y' || t == 'T') {
		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'));
	changeScreenType($.cookie('screenType'));
	changePartsColor($.cookie('partsColor'));
	changeChainPosition($.cookie('chainPosition'));
	changeAttachStyle($.cookie('attachStyle'));
	changeOrderWidth($.cookie('orderWidth'));
	changeOrderHeight($.cookie('orderHeight'));
	changeFloorHeight($.cookie('floorHeight'));
	changeNumItems($.cookie('numItems'));
}

function run(f) {
	setTimeout(f, 10);
}

$(function () {
	console.log('document.ready');
	
	initbox(); // dropdown box
	
	$('.guideButton').click(function () { showDetail(this); });
	
	$('#group').change(onChangeGroup);
	$('#handleType').change(onChangeHandleType);
	$('#screenType').change(onChangeScreenType);
	$('#partsColor').change(onChangePartsColor);
	$('#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);
});
