/*
 * Shopping Cart
 * 関東図書株式会社 / nunokawa@kanto-t.jp
 *
 * Encoding  : UTF-8, LF
 * Date      : 2010-06-14
 */

jQuery.cart={
	// 各種設定
	COOKIE_NAME:'kt_cart',					// クッキーの名称
	COOKIE_OPTION:{ path:'/' },				// クッキーが有効なディレクトリの範囲
	ORDER_PAGE:'https://kanto-t.jp/order/',					// 注文ページ
	CART_PARENT_ID:'#cartarea',				// カートを追加するHTMLのID
	ORDER_PARENT_ID:'#orderarea',			// 注文フォームを追加するHTMLのID
	SUBMIT_URL: '/common/cart/submit.php',	//注文情報を処理するPHPファイル		

	// 初期化
	items: {},			// カートの内容
	customer: {			// 発注者情報
		name: '',
		address: '',
		phone: '',
		fax: '',
		email: '',
		note: '',

		opt1_name: '',
		opt1_company: '',
		opt1_position: '',
		opt1_joint1: '',
		opt1_jointnote1: '',
		opt1_joint2: '',
		opt1_jointnote2: '',
		opt1_joint3: '',
		opt1_jointnote3: '',
		opt1_address: '',
		opt1_phone: '',
		opt1_fax: '',
		opt1_email: '',
		opt1_note: ''
	},
	option:0,			// オプション入力事項があるかどうか

	// メソッド
	decodeObj: function () {
		if ($.cookie(this.COOKIE_NAME)) {
			this.items=$.json.decode($.cookie(this.COOKIE_NAME));
		}

		if ($.cookie(this.COOKIE_NAME+'_customer')) {
			this.customer=$.json.decode($.cookie(this.COOKIE_NAME+'_customer'));
		}

		if ($.cookie(this.COOKIE_NAME+'_option')) {
			this.option=$.json.decode($.cookie(this.COOKIE_NAME+'_option'));
		}
	},

	items_size: function () {
		var size=0;

		for (_item in this.items) {
			size++;
		}

		return size;
	},

	dispose: function () {
		this.items={};
		this.customer={
			name: '',
			address: '',
			phone: '',
			fax: '',
			email: '',
			note: '',

			opt1_name: '',
			opt1_company: '',
			opt1_position: '',
			opt1_joint1: '',
			opt1_jointnote1: '',
			opt1_joint2: '',
			opt1_jointnote2: '',
			opt1_joint3: '',
			opt1_jointnote3: '',
			opt1_address: '',
			opt1_phone: '',
			opt1_fax: '',
			opt1_email: '',
			opt1_note: ''
		};
		this.save();
		this.redraw();
		alert('ショッピングカートが空になりました');
	},

	take: function (_id, _description, _price) {
		//alert('take '+_description);
		this.decodeObj();

		if (this.items.hasOwnProperty(_id)) {
			this.items[_id].amount+=1;
		} else {
			this.items[_id]={
				description: _description,
				amount: 1,
				price: _price
			};
		}

		this.save();
		this.redraw();
		if (confirm("商品がショッピングカートに入りました。\nご注文手続きへ進みますか?")) {
			location.href=this.ORDER_PAGE;
			window.event.returnValue=false;
		}
	},

	plus: function (_id) {
		this.decodeObj();

		if (this.items.hasOwnProperty(_id)) {
			this.items[_id].amount+=1;
		}

		this.save();
		this.redraw();
	},

	minus: function (_id) {
		this.decodeObj();

		if (this.items.hasOwnProperty(_id)) {
			if (this.items[_id].amount == 1) {
				delete this.items[_id];
			} else {
				this.items[_id].amount-=1;
			}
		}

		this.save();
		this.redraw();

		if (this.items_size() == 0) {
			alert('ショッピングカートが空になりました');
		}
	},

	remove: function (_id) {
		this.decodeObj();

		if (this.items.hasOwnProperty(_id)) {
			delete this.items[_id];
		}

		this.save();
		this.redraw();

		if (this.items_size() == 0) {
			alert('ショッピングカートが空になりました');
		}
	},

	save: function () {
		// オプション入力があるかどうかを判定
		this.option=0;
		for (_item in this.items) {
			// 年賀状が入っているかどうか
			if (_item.indexOf('K-') > -1) {
				this.option++;
				break;
			}
		}

		$.cookie(this.COOKIE_NAME, $.json.encode(this.items), this.COOKIE_OPTION);
		$.cookie(this.COOKIE_NAME+'_customer', $.json.encode(this.customer), this.COOKIE_OPTION);
		$.cookie(this.COOKIE_NAME+'_option', $.json.encode(this.option), this.COOKIE_OPTION);
	},

	show: function () {
		var html='';
		var size=0;
		var total_price=0;
		var total_amount=0;

		this.decodeObj();

		html+='<h3><a href="/order/"><img src="/common/cart/h3.gif" width="220" height="38" alt="現在のショッピングカート"></a></h3>'
			+'<div id="cart">'
			+'<ul class="item">';

		for (_item in this.items) {
			var item=this.items[_item];

			html+='<li>'
				+item.description+'（×'+item.amount+'）'+(item.amount*item.price)+'円 '
				+'<span class="plus_minus">'
				+'[ <a href="javascript:void(0);" onclick="$.cart.plus(\''+_item+'\')">＋</a> | '
				+'<a href="javascript:void(0);" onclick="$.cart.minus(\''+_item+'\')">−</a>'
				+' ]</span>';

			size++;
			total_price+=item.amount*item.price;
			total_amount+=item.amount;
		}

		html+='</ul>';

		if (size > 0) {
			html+='<div id="total">'
				+'合計：<span style="color:#903;font-weight:bold;">'+total_amount+'点</span>　<span style="color:#903;font-weight:bold;">'+total_price+'円</span>'
				+'</div>'
				+'<div id="command">'
				+'<a href="'+this.ORDER_PAGE+'">注文手続きへ</a> | '
				+'<a href="http://kanto-t.jp/order/shipping/">送料</a> | '
				+'<a href="http://kanto-t.jp/order/payment/">お支払方法</a>'
				+'</div>'
				+'<div style="clear:both;"></div>'
				+'</div>';

			$(this.CART_PARENT_ID).fadeIn('slow');
			$(this.CART_PARENT_ID).html(html);
		} else {
			$(this.CART_PARENT_ID).html('');
		}
	},

	showItemList: function () {
		//alert('itemList');
		var html='';
		var total_price=0;
		var total_amount=0;

		this.decodeObj();

		html+='<h2>現在のショッピングカート</h2>'
		if (this.items_size() > 0) {
			html+='<table id="cart_list">'
				+'<tr>'
				+'<th>商品名</th>'
				+'<th>数量</th>'
				+'<th>単価</th>'
				+'<th>小計</th>'
				+'</tr>';

			for (_item in this.items) {
				var item=this.items[_item];

				html+='<tr>'
					+'<td>'+item.description+'</td>'
					+'<td>'
					+item.amount+'冊'
					+'<span class="plus_minus">'
					+'[ <a href="javascript:void(0);" onclick="$.cart.plus(\''+_item+'\')">＋</a> | '
					+'<a href="javascript:void(0);" onclick="$.cart.minus(\''+_item+'\')">−</a> | '
					+'<a href="javascript:void(0);" onclick="$.cart.remove(\''+_item+'\')">削除</a>'
					+' ]</span>'
					+'</td>'
					+'<td>'+item.price+'円</td>'
					+'<td>'+(item.amount*item.price)+'円</td>';

				total_price+=item.amount*item.price;
				total_amount+=item.amount;
			}

			html+='<tr>'
				+'<td colspan="3">合計</td>'
				+'<td>'+total_price+'円</td>'
				+'</tr>'
				+'</table>'
				+'<div id="checkout">'
				+'<a class="next" href="javascript:void(0);" onclick="$.cart.checkout();">注文手続きへ進む</a>'
				+'<a class="next" href="javascript:void(0);" onclick="javascript:history.back();return false;">戻る</a>'
				+'<a class="next" href="javascript:void(0);" onclick="$.cart.dispose();">ショッピングカートを空にする</a>'
				+'</div>'
				+'<div id="step"></div>'
				+'<div id="procedure"></div>';
		} else {
			html+='お客様のショッピングカートには何も入っていません';
		}

		$(this.ORDER_PARENT_ID).html(html);
	},

	redraw: function () {
		if ($(this.ORDER_PARENT_ID).length) {
			this.showItemList();
		} else {
			this.show();
		}
	},

	checkout: function () {
		var html;

		$('#checkout').remove();

		html='<ul>'
			+'<li id="step1" class="now">納品先の入力</li>';

		if (this.option > 0) {
			html+='<li id="stepoption1">&raquo; 印刷内容の入力</li>';
		}

		html+='<li id="step2">&raquo; 内容確認</li>'
			+'<li id="step3">&raquo; 注文完了</li>'
			+'</ul>';

		$('#step').html(html).fadeIn();
		this.step1();
	},

	step1: function () {
		var html;

		this.decodeObj();
		$('.plus_minus').hide();

		html='<div id="order_info">'
			+'<dl>'
			+'<dt>お名前（例：関東太郎）</dt>'
			+'<dd><input id="name" value="'+this.customer.name+'"></dd>'
			+'<dt>納品先（郵便番号からご記入ください　例：〒336-0021 さいたま市南区別所3-1-10）</dt>'
			+'<dd><input id="address" value="'+this.customer.address+'"></dd>'
			+'<dt>電話番号（半角数字とハイフン　例：048-862-2901）</dt>'
			+'<dd><input id="phone" value="'+this.customer.phone+'"></dd>'
			+'<dt>FAX番号（半角数字とハイフン　例：048-862-2908）</dt>'
			+'<dd><input id="fax" value="'+this.customer.fax+'"></dd>'
			+'<dt>メールアドレス（半角英数字　例：taro@kanto-t.jp）</dt>'
			+'<dd><input id="email" value="'+this.customer.email+'"></dd>'
			+'<dt>ご要望など</dt>'
			+'<dd><textarea id="note">'+this.customer.note+'</textarea></dd>'
			+'</dl>'
			+'<a class="next" href="javascript:void(0);" onclick="$.cart.verify();">次へ進む</a>'
			+'<a class="next" href="javascript:void(0);" onclick="$.cart.redraw();">一つ戻る</a>　'
			+'</div>';

		$('#procedure').html(html).fadeIn();
	},

	verify: function () {
		 if (!$('#name').val().valueCheck('kanji')) {
			alert('お名前を確認してください');
		} else if (!$('#address').val().valueCheck('kanji')) {
			alert('送り先を確認してください');
		} else if (!$('#phone').val().valueCheck('phone')) {
			alert('電話番号を確認してください');
		} else if (($('#fax').val() != '') && (!$('#fax').val().valueCheck('phone'))) {
			alert('FAX番号を確認してください');
		} else if (!$('#email').val().valueCheck('email')) {
			alert('メールアドレスを確認してください');
		} else {
			this.decodeObj();
			this.customer.name=$('#name').val(),
			this.customer.address=$('#address').val(),
			this.customer.phone=$('#phone').val(),
			this.customer.fax=$('#fax').val(),
			this.customer.email=$('#email').val(),
			this.customer.note=$('#note').val()

			this.save();

			if (this.option > 0) {
				this.stepOption1();
			} else {
				this.step2();
			}
		}
	},

	stepOption1: function () {
		var html;

		$('.now').removeClass('now');
		$('#stepoption1').addClass('now');

		this.decodeObj();

		html='<div id="order_info">'
			+'<p>※納品先の入力内容を <a class="next" href="javascript:void(0);" onclick="$.cart.copy();">コピー</a>する</p>'
			+'<dl>'
			+'<dt>お名前（例：関東太郎）</dt>'
			+'<dd><input id="opt1_name" value="'+this.customer.opt1_name+'"></dd>'
			+'<dt>法人名（例：関東図書株式会社）</dt>'
			+'<dd><input id="opt1_company" value="'+this.customer.opt1_company+'"></dd>'
			+'<dt>肩書（例：代表取締役社長）</dt>'
			+'<dd><input id="opt1_position" value="'+this.customer.opt1_position+'"></dd>'
			+'<dt>連名1、旧姓・学年・年齢等（例：花子、旧姓：山田）</dt>'
			+'<dd><input id="opt1_joint1" class="joint" value="'+this.customer.opt1_joint1+'"><input id="opt1_jointnote1" class="joint" value="'+this.customer.opt1_jointnote1+'"></dd>'
			+'<dt>連名2、旧姓・学年・年齢等（例：一郎、小1）</dt>'
			+'<dd><input id="opt1_joint2" class="joint" value="'+this.customer.opt1_joint2+'"><input id="opt1_jointnote2" class="joint" value="'+this.customer.opt1_jointnote2+'"></dd>'
			+'<dt>連名3、旧姓・学年・年齢等（例：二郎、3歳）</dt>'
			+'<dd><input id="opt1_joint3" class="joint" value="'+this.customer.opt1_joint3+'"><input id="opt1_jointnote3" class="joint" value="'+this.customer.opt1_jointnote3+'"></dd>'
			+'<dt>ご住所（郵便番号からご記入ください　例：〒336-0021 さいたま市南区別所3-1-10）</dt>'
			+'<dd><input id="opt1_address" value="'+this.customer.opt1_address+'"></dd>'
			+'<dt>電話番号（半角数字とハイフン　例：048-862-2901）</dt>'
			+'<dd><input id="opt1_phone" value="'+this.customer.opt1_phone+'"></dd>'
			+'<dt>FAX番号（半角数字とハイフン　例：048-862-2901）</dt>'
			+'<dd><input id="opt1_fax" value="'+this.customer.opt1_fax+'"></dd>'
			+'<dt>メールアドレス（半角英数字　例：taro@kanto-t.jp）</dt>'
			+'<dd><input id="opt1_email" value="'+this.customer.opt1_email+'"></dd>'
			+'<dt>ご要望、その他の追加印刷事項など</dt>'
			+'<dd><textarea id="opt1_note">'+this.customer.opt1_note+'</textarea></dd>'
			+'</dl>'
			+'<a class="next" href="javascript:void(0);" onclick="$.cart.verifyOption1();">次へ進む</a>'
			+'<a class="next" href="javascript:void(0);" onclick="$.cart.step1();">一つ戻る</a>　'
			+'</div>';

		$('#procedure').html(html).fadeIn();
	},

	copy: function () {
		this.decodeObj();

		$('#opt1_name').val(this.customer.name);
		$('#opt1_address').val(this.customer.address);
		$('#opt1_phone').val(this.customer.phone);
		$('#opt1_fax').val(this.customer.fax);
		$('#opt1_email').val(this.customer.email);
	},

	verifyOption1: function () {
		if (($('#opt1_name').val() != '') && !$('#opt1_name').val().valueCheck('kanji')) {
			alert('お名前を確認してください');
		} else if (($('#opt1_company').val() != '') && !$('#opt1_company').val().valueCheck('kanji')) {
			alert('法人名を確認してください');
		} else if (($('#opt1_position').val() != '') && !$('#opt1_position').val().valueCheck('kanji')) {
			alert('肩書を確認してください');
		} else if (!$('#opt1_address').val().valueCheck('kanji')) {
			alert('ご住所を確認してください');
		} else if (($('#opt1_phone').val() != '') && !$('#opt1_phone').val().valueCheck('phone')) {
			alert('電話番号を確認してください');
		} else if (($('#opt1_fax').val() != '') && !$('#opt1_fax').val().valueCheck('phone')) {
			alert('FAX番号を確認してください');
		} else if (($('#opt1_email').val() != '') && !$('#opt1_email').val().valueCheck('email')) {
			alert('電話番号を確認してください');
		} else {
			this.decodeObj();

			this.customer.opt1_name=$('#opt1_name').val(),
			this.customer.opt1_company=$('#opt1_company').val(),
			this.customer.opt1_position=$('#opt1_position').val(),
			this.customer.opt1_joint1=$('#opt1_joint1').val(),
			this.customer.opt1_jointnote1=$('#opt1_jointnote1').val(),
			this.customer.opt1_joint2=$('#opt1_joint2').val(),
			this.customer.opt1_jointnote2=$('#opt1_jointnote2').val(),
			this.customer.opt1_joint3=$('#opt1_joint3').val(),
			this.customer.opt1_jointnote3=$('#opt1_jointnote3').val(),
			this.customer.opt1_address=$('#opt1_address').val(),
			this.customer.opt1_phone=$('#opt1_phone').val(),
			this.customer.opt1_fax=$('#opt1_fax').val(),
			this.customer.opt1_email=$('#opt1_email').val(),
			this.customer.opt1_note=$('#opt1_note').val()

			this.save();

			this.step2();
		}
	},

	step2: function () {
		var html;

		$('.now').removeClass('now');
		$('#step2').addClass('now');

		this.decodeObj();

		html='<p style="margin:0;">入力内容をご確認ください。よろしければ「注文する」ボタンを押してください</p>'
			+'<p style="margin:0;font-weight:bold;">納品先</p>'
			+'<table>'
			+'<tr>'
			+'<td>お名前</td>'
			+'<td>'+this.customer.name.xhe()+'</td>'
			+'</tr>'
			+'<tr>'
			+'<td>送り先</td>'
			+'<td>'+this.customer.address.xhe()+'</td>'
			+'</tr>'
			+'<tr>'
			+'<td>電話番号</td>'
			+'<td>'+this.customer.phone.xhe()+'</td>'
			+'</tr>'
			+'<tr>'
			+'<td>FAX番号</td>'
			+'<td>'+this.customer.fax.xhe()+'</td>'
			+'</tr>'
			+'<tr>'
			+'<td>メールアドレス</td>'
			+'<td>'+this.customer.email.xhe()+'</td>'
			+'</tr>'
			+'<tr>'
			+'<td>ご要望など</td>'
			+'<td>'+this.customer.note.xhe()+'</td>'
			+'</tr>'
			+'</table>';

		if (this.option > 0) {
			html+='<p style="margin:0;font-weight:bold;">印刷内容</p>'
				+'<table>'
				+'<tr>'
				+'<td>お名前</td>'
				+'<td>'+this.customer.opt1_name.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>法人名</td>'
				+'<td>'+this.customer.opt1_company.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>肩書</td>'
				+'<td>'+this.customer.opt1_position.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>連名1</td>'
				+'<td>'+this.customer.opt1_joint1.xhe()+'　'+this.customer.opt1_jointnote1.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>連名2</td>'
				+'<td>'+this.customer.opt1_joint2.xhe()+'　'+this.customer.opt1_jointnote2.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>連名3</td>'
				+'<td>'+this.customer.opt1_joint3.xhe()+'　'+this.customer.opt1_jointnote3.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>ご住所</td>'
				+'<td>'+this.customer.opt1_address.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>電話番号</td>'
				+'<td>'+this.customer.opt1_phone.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>FAX番号</td>'
				+'<td>'+this.customer.opt1_fax.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>メールアドレス</td>'
				+'<td>'+this.customer.opt1_email.xhe()+'</td>'
				+'</tr>'
				+'<tr>'
				+'<td>ご要望など</td>'
				+'<td>'+this.customer.opt1_note.xhe()+'</td>'
				+'</tr>'
				+'</table>';
		}

		html+='<a class="next" href="javascript:void(0);" onclick="$.cart.step3();">注文する</a>';

		if (this.option > 0) {
			html+='<a class="next" href="javascript:void(0);" onclick="$.cart.stepOption1();">一つ戻る</a>　';
		} else {
			html+='<a class="next" href="javascript:void(0);" onclick="$.cart.step1();">一つ戻る</a>　';
		}

		$('#order_info').html(html);
	},

	step3: function () {
		var that=this;

		$.ajax({
			async: true,
			cache: false,
			type: 'POST',
			url: this.SUBMIT_URL,
			data: '',
			success: function () {
				$('.now').removeClass('now');
				$('#step3').addClass('now');
		
				var html='<p>ご注文ありがとうございます。お客様に注文内容を記したメールをお送りしました。'
						+'24時間以内にメールが届かない場合はお手数でもご連絡くださいますようお願い申し上げます。</p>';

				$('#order_info').fadeIn().html(html);

				// 注文内容を破棄
				that.items={};
				for (_v in that.customer) {
					that.customer[_v]='';
				}
				that.save();
				window.scrollTo(0,0);
			},
			error: function () {
				var html='<p>発注処理が正しく終了しませんでした。'
						+'もう一度「注文する」ボタンを押してください。</p>';

				$('#order_info').fadeIn().html(html);
			}
		});

	}
};



$(function () {
	$.cart.redraw();
});
