// JavaScript Document


function convert_number(number)
{
	return str.replace(/\d/g, function(str){return String.fromCharCode(str.charCodeAt(0)-65248);});
}
var Cart = Class.create();

Cart.prototype = {
	initialize: function(path,tax)
	{
		this.cart_to_path = path;
		this.pagewidth = document.documentElement.clientWidth || document.body.clientWidth || document.body.scrollWidth;
		this.pageheight = document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight;
		this.scrolltop =  setInterval(this.observe_scrollvalue,5);//document.documentElement.scrollTop || document.body.scrollTop;
		this.newvalue = 0;
		this.timer = '';
		this.cartopenFlag = true;
		this.searchopenFlag = false;
		this.height = document.body.offsetHeight;
		this.tax = tax;
		this.loadimage = this.createloadimage();
		this.layer = this.createlayer('layer');
		this.layer2 = this.createlayer('layer2');
		this.divNode2 = this.createNode('div','modal');
		this.layerheight = (this.height > this.pageheight) ? this.height : this.pageheight;
		this.oldChild_detail = '';
		this.oldchild_layer = '';
		this.oldChild_layer2 = '';
		this.oldChild_dialog = '';
		this.couponFlag = false;


	},
	add : function(element,itemId)
	{
		//在庫チェック
		var color = $('order_color').value;
		var size = $('order_size').value;
		var sku_code = itemId + '-' + color + '-' + size;
		var amount = $('amount').value;
		new Ajax.Request(this.cart_to_path+'cart/checkstock/'+sku_code,
						 {
							 method : 'post',
							 onSuccess : function(httpobj)
							 {
								 if(amount > Number(httpobj.responseText))
								 {
									 alert('在庫数以上のご注文です。');
								 }
								 else
								 {
									element.parentNode.appendChild(Cart.loadimage);
									formName = 'form'+itemId;
									new Ajax.Request(Cart.cart_to_path+'cart/addcart/'+itemId,
													 {
														 method : 'post',
														 parameters :Form.serialize(formName),
														 onSuccess : function(httpobj)
														 {
															element.parentNode.removeChild(Cart.loadimage);
															new Ajax.Updater($('count_value'),Cart.cart_to_path+'cart/updatecart_count');
															new Ajax.Updater($('incart'),Cart.cart_to_path+'cart/updatecart/'+Cart.cartopenFlag);
															Cart.dialogshow(httpobj.responseText);
														 },
														 onFailure : function()
														 {
															 Cart.dialogshow('カートへの追加に失敗しました。お手数ですがもう一度操作をやり直してください。');
														 }
													 });
								 }
							 }
						 });

	},
	changeamount : function(itemId)
	{
		if($('amount'+itemId).value.match("^\-") == '-')
		{
		 	var spanNode = Cart.createNode('span');
		 	spanNode.style.fontSize = '0.8em';
		 	spanNode.style.color = '#c00';
		 	targetNode = document.getElementById('form'+itemId);
		 	spanNode.innerHTML = '<br />個数にマイナス数値は入力できません！';
		 	targetNode.appendChild( spanNode );
		 	this.timer = setTimeout(function(){targetNode.removeChild( spanNode );clearTimeout(this.timer);},2000);
		}
		else if($('amount'+itemId).value == 0)
		{
			text = '<br /><p class="center">数量に0を入力すると削除となります。よろしいですか？</p><br />';
			text += '<input type="button" value="はい" onclick="Cart.deleteitem_confirm_dialog(\''+itemId+'\')" />&nbsp;&nbsp;';
			text += '<input type="button" value="いいえ" onclick="Cart.dialogclose();" />';
			this.dialogshow(text);
		}
 		else
		{
			$('load').appendChild(this.loadimage);
			var coupon = $('coupon_value_hidden').value;
			formName = 'form'+itemId;
			new Ajax.Request(this.cart_to_path+'cart/changeamount/'+itemId,
							 {
								 method : 'post',
								 parameters :Form.serialize(formName),
								 onSuccess : function(httpobj)
								 {
								 	$('load').removeChild(Cart.loadimage);
								 	var spanNode = Cart.createNode('span');
								 	spanNode.style.fontSize = '0.8em';
								 	targetNode = document.getElementById('form'+itemId);
								 	spanNode.innerHTML = '<br />数量を変更しました。';
								 	targetNode.appendChild( spanNode );
								 	Cart.timer = setTimeout(function(){targetNode.removeChild( spanNode );clearTimeout(Cart.timer);},2000);
								 	new Effect.Highlight(document.getElementById('item_line'+itemId));
								 	subTotal_new = $('price'+itemId).value*$('amount'+itemId).value;
								 	$('subtotal_disp'+itemId).innerHTML = String(Cart.number_format(subTotal_new));
								 	$('subtotal'+itemId).value = subTotal_new;
								 	new_total = 0;
								 	$$('.subtotal').each(function(tag){
							 		new_total = new_total+Number($(tag).value);
								 	});
									//new_total = new_total - coupon;

									if(new_total >= $('carriage_free').value)
									{
										$('carriage').innerHTML = '<p>送料は無料となります</p>';
										$('free_msg').innerHTML = '';
									 	$('total').innerHTML = Cart.number_format(new_total - coupon);
									}
									else
									{
										$('carriage').innerHTML = '&yen;'+$('carriage_value').value;
										$('free_msg').innerHTML = '<span class="red">あと'+($('carriage_free').value - new_total)+'円のご購入で送料が無料になります！</span>';
									 	$('total').innerHTML = Cart.number_format(new_total+Number($('carriage_value').value - coupon));
									}
								 },
								 onFailure : function()
								 {
									 Cart.dialogshow('データ通信に失敗しました。お手数ですがもう一度操作をやり直してください。');
								 }
							 });
		}
	},
	deleteitem : function(itemId)
	{
		$('load').appendChild(this.loadimage);
		text = '<p>この商品をカゴから削除してもよろしいですか？<br /><br /><br /><input type="button" value="削除する" onclick="Cart.dialogclose();Cart.deleteitem_confirm(\''+itemId+'\');" />&nbsp;&nbsp;<input type="button" value="中止" onclick="Cart.dialogclose();return false;" /><p>';
		this.dialogshow(text);
		$('load').removeChild(this.loadimage);

	},
	deleteitem_confirm : function(itemId)
	{
		formName = 'delete'+itemId;
		new Ajax.Request(this.cart_to_path+'cart/deletecart',
						{
							method : 'post',
							parameters : Form.serialize(formName),
							onSuccess : function(httpobj)
							{
								location.reload();
							}
						});
	},
	deleteitem_confirm_dialog : function(itemId)
	{
		new Ajax.Request(this.cart_to_path+'cart/deletecart/'+itemId,
						{
							method : 'get',
							onSuccess : function(httpobj)
							{
								location.reload();
							}
						});
	},



	dialogshow : function(text)
	{

		this.layer.style.width = this.pagewidth+'px';
		this.layer.style.height = this.layerheight+'px';

		cartpath = this.cart_to_path+'cart/';
		this.divNode2.innerHTML = text;
		scrolltop =  document.documentElement.scrollTop || document.body.scrollTop;
		new_top = parseInt(this.pageheight)/2+parseInt(scrolltop);

		this.divNode2.style.top = new_top+'px';
		document.body.appendChild(this.layer);
		document.body.appendChild(this.divNode2);
		new Effect.Appear($('layer'),{from:0,to:0.7,duration:0.5});
		new Effect.Appear($('modal'),{from:0,to:0.9,duration:0.5});
		this.timer = setInterval(this.get_scrollvalue,5);
	},
	detailshow : function (itemId)
	{

		divNode3 = this.createNode('div','detailbox');
		cartpath = this.cart_to_path+'shop/';
		new Ajax.Request(cartpath+'detail/'+itemId,
						{
							method :'post',
							onSuccess : function(httpobj)
							{
								json = new Object();
								json = eval("("+httpobj.responseText+")");
								//パース、ページ構成開始
								html = '<div id="detailinfo">';
								html += '<h2>'+json.feature+'</h2>';
								if(json.image != '')
								{
									html += '<img src="'+Cart.cart_to_path+'product_images/'+json.image1+'" /><br />';
								}
								else
								{
									html += '<img src="'+Cart.cart_to_path+'img/product/noimage.jpg" /><br />';
								}
								html += '<table>';
								html += '<tbody>';
								html += '<tr><th colspan="4">サイズ・カラー対応表</th></tr>';
								html += '<tr>';
								html += '<td class="cell1"></td><td class="cell2"></td><td class="cell3"></td><td class="cell4"></td>';
								html += '</tr>';
								html += '<tr>'
								html += '<td class="cell1"></td><td class="cell2"></td><td class="cell3"></td><td class="cell4"></td>';
								html += '</tr>';
								html += '<tr>'
								html += '<td class="cell1"></td><td class="cell2"></td><td class="cell3"></td><td class="cell4"></td>';
								html += '</tr>';
								html += '<tr>'
								html += '<td class="cell1"></td><td class="cell2"></td><td class="cell3"></td><td class="cell4"></td>';
								html += '</tr>';
								html += '</table>';
								html += '<br /><br /><p>';
								html += json.product_name;
								html += '<form name="form'+itemId+'" id="form'+itemId+'">';
								html += '個数：<input type="text" name="amount" value="1" size="2" />';
								html += '</form></p>';
								html += '<p><input type="button" value="カートに追加する" onclick="Cart.add(this,json.p_product_id);" /></p>';
								html += '<br class="clear" />';
								html += '<p style="text-align:center"><input type="button" onclick="Cart.detailclose();" value="閉じる" /></p>';

								html += '</div>';
								html += '<p id="detail_footer"></p>';
								divNode3.innerHTML = html;
								pageheight = document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight;
								scrolltop =  document.documentElement.scrollTop || document.body.scrollTop;
								new_top = parseInt(pageheight)/2+parseInt(scrolltop);

								Cart.layer2.style.height = (Cart.height > pageheight) ? Cart.height+'px' : pageheight+'px';
								divNode3.style.top = new_top+'px';
								document.body.appendChild(Cart.layer2);
								document.body.appendChild(divNode3);
								divNode3.style.height = $('detailinfo').getHeight()+'px';

								divNode3.style.marginTop = -($('detailinfo').getHeight())/2+'px';
								new Effect.Appear($('layer2'),{from:0,to:0.7,duration:0.5});
								$('detailbox').hide().blindDown();
								}
							});
	},
	detailclose : function()
	{
		new Effect.Fade($('layer2'),{duration:0.5,afterFinish : function(effect){
																  	 document.body.removeChild(effect.element);
																  }
});
		new Effect.BlindUp($('detailbox'),{duration:0.5,afterFinish : function(effect){
																  	Cart.oldChild = document.body.removeChild(effect.element);
																  }});
	},
	createlayer : function(idname)
	{
		height = document.body.offsetHeight;
		layerheight = (height > this.pageheight) ? height : this.pageheight;
		layer = this.createNode('div');
		layer.setAttribute('id',idname);
		layer.style.width = this.pagewidth+'px';
		layer.style.height = layerheight+'px';
		return layer;
	},
	createNode : function(nodetag,nodeid)
	{
		var Node = document.createElement(nodetag);
		Node.setAttribute('id',nodeid);

		return Node;
	},
	createloadimage : function()
	{
		var load = document.createElement('img');
		load.setAttribute('src',this.cart_to_path+'img/ajax-loader.gif');
		return load;
	},

	dialogclose : function()
	{
		new Effect.Fade($(this.layer),{duration:0.5,afterFinish : function(effect){
																  	 document.body.removeChild(effect.element);
																  }
});
		new Effect.Fade($(this.divNode2),{duration:0.5,afterFinish : function(effect){
																  	oldChild = document.body.removeChild(effect.element);
																  }});
		clearInterval(this.timer);
		this.newvalue = 0;
	//	divNode2 = '';
	//	layer = '';
	},
	get_scrollvalue : function()
	{
		try{
			scrollvalue = document.documentElement.scrollTop ;
		}
		catch(e)
		{
			scrollvalue = document.body.scrollTop;
		}
		if(this.newvalue != scrollvalue)
		{
			pageheight = document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight;
			scrolltop =  document.documentElement.scrollTop || document.body.scrollTop;
			new_top = parseInt(pageheight)/2+parseInt(scrolltop);
			$('modal').style.top = new_top+'px';
			this.newvalue = scrollvalue;
		}
	},
	get_scrollvalue_detail : function()
	{
		try{
			scrollvalue = document.documentElement.scrollTop ;
		}
		catch(e)
		{
			scrollvalue = document.body.scrollTop;
		}
		if(this.newvalue != scrollvalue)
		{
			pageheight = document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight;
			scrolltop =  document.documentElement.scrollTop || document.body.scrollTop;
			new_top = parseInt(pageheight)/2+parseInt(scrolltop);
			$('layer2').style.top = parseInt(scrolltop)+'px';
		//	$('detailbox').style.top = new_top+'px';
			this.newvalue = scrollvalue;
		}
	},
	observe_scrollvalue : function()
	{
		return document.documentElement.scrollTop || document.body.scrollTop;
	},

	opencart : function(element)
	{
		if(this.cartopenFlag)
		{
			$('cart_list').style.height = 'auto';
			$('cart_list').style.display = 'block';
			$('opensign').innerHTML ='△';
			this.cartopenFlag = false;
		}
		else
		{
			$('cart_list').style.height = '0';
			$('cart_list').style.display = 'none';
			$('opensign').innerHTML ='▽';
			this.cartopenFlag = true;
		}
	},
	opensearch : function()
	{
		if(!this.searchopenFlag)
		{
			$('search_ex').style.display = 'block';
			this.searchopenFlag = true;
		}
		else
		{
			$('search_ex').style.display = 'none';
			this.searchopenFlag = false;
		}
	},

	convert_number : function(id)
	{

	  work='';
	  for (lp=0;lp<id.value.length;lp++) {
	    unicode=id.value.charCodeAt(lp);
	    if ((0xff0f<unicode) && (unicode<0xff1a)) {
	      work+=String.fromCharCode(unicode-0xfee0);
	    } else if ((0xff20<unicode) && (unicode<0xff3b)) {
	      work+=String.fromCharCode(unicode-0xfee0);
	    } else if ((0xff40<unicode) && (unicode<0xff5b)) {
	      work+=String.fromCharCode(unicode-0xfee0);
	    } else {
	      work+=String.fromCharCode(unicode);
	    }
	  }
	  id.value=work;
	},
	//価格数値に変換処理（PHPのnumber_format関数代価）
	number_format : function(number)
	{
		var num = new String(number).replace(/,/g, "");
		while(num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
		return '&yen;'+num;
	},

	//以下、サンプルコード
	//ペーストを禁止するメンバ関数
	pasteCheck : function(event)
	{
		if ((event.keyCode == 86 && event.ctrlKey) || (event.keyCode == 45 && event.shiftKey)) { return false;}
	},

	//上記関数のアラート表示
	alertShow : function(element)
	{
		if($('alert_mail').style.display == 'none')
		{
			$('alert_mail').style.display = 'inline';
		}
		else
		{
			$('alert_mail').style.display = 'none';
		}
	},
	alertShow_pass : function(element)
	{
		if($('alert_pass').style.display == 'none')
		{
			$('alert_pass').style.display = 'inline';
		}
		else
		{
			$('alert_pass').style.display = 'none';
		}
	},
	rollOver : function(element)
	{
		element.src = element.src.gsub('.jpg','_on.jpg');
	},
	rollOut : function(element)
	{
		element.src = element.src.gsub('_on.jpg','.jpg');
	},
	//クーポンシステム
	openCouponForm : function(member_id)
	{
		if(typeof(member_id) == 'undefined')
		{
			 text = '<p class="center">会員クーポンの使用にはログインが必要となっております。<br />'
			 text += 'お手数ですが以下のフォームからログインしてください。';
			 text += '</p><p id="error"></p><br />';
			 text += '<form id="coupon_login" name="coupon_login">';
			 text += '<table><tr>';
			 text += '<td width="120">メールアドレス：</td><td><input type="text" size="40" name="email" /></td>';
			 text += '</tr><tr height="10"><td></td></tr>';
			 text += '<td width="120">パスワード：</td><td><input type="password" name="pass" size="40" /></td>';
			 text += '</tr><tr height="１0"><td></form></td></tr>';
			 text += '<tr><td colspan="2" class="center"><input type="button" value="ログイン" class="long" onclick="Cart.AjaxLogin();" />&nbsp;<input type="button" value="閉じる" onclick="Cart.dialogclose();" class="center long" /></td></tr></table>';
			 text += '<br /><p class="center">新規登録は<a href="'+ this.cart_to_path + 'guide/user_rules">こちら</a></p>';
			 this.dialogshow(text);
			 return;
		}
		else
		{
			if(!this.couponFlag)
			{
				$$('.coupon').each(function(tag)
											{
												$(tag).style.display = '';
											}
											);
				this.couponFlag = true;
				$('coupon_code').focus();
			}
		}
	},
	openCouponFormNotUser : function()
	{
		text = '<p class="center">ご利用になるクーポン番号とお客様のメールアドレスを<br />入力して送信してください。</p>';
		 text += '<p id="error_error" class="red"></p>';
		 text += '<form id="coupon_not_user" name="coupon_not_user">';
		text += '<table><tr>';
		 text += '<td width="120">メールアドレス：</td><td><input type="text" size="40" name="email" /></td>';
		 text += '</tr><tr height="10"><td></td></tr>';
		 text += '<tr><td width="120">クーポン番号</td><td><input type="text" size="40" name="coupon_number" id="coupon_number_not_user" /></td></tr>';
		 text += '<tr height="10"><td></form></td></tr>';
		 text += '<tr><td colspan="2" class="center"><input type="button" value="送信" class="long" onclick="Cart.AjaxCouponCheck();" />&nbsp;<input type="button" value="閉じる" onclick="Cart.dialogclose();" class="center long" /></td></tr></table>';
		 text += '<br /><p class="center red">※会員登録をされている方は上の「会員クーポンを使用」から<br />ご入力ください。</p>';
		this.dialogshow(text);
		return;
	},
	checkcoupon : function(member_id)
	{
		var coupon_code = $('coupon_code').value;
		var menber_id =  member_id;
		new Ajax.Request(this.cart_to_path + 'cart/checkcoupon/' + coupon_code + '/' + member_id,
						 {
							 method : 'post',
						//	 parameters : Form.serialize('coupon'),
							 onSuccess : function(httpobj)
							 {
								try{
									cp = eval('(' +httpobj.responseText+')');
									 $('coupon_category').innerHTML = cp.coupon_name;
									 $('coupon_value').innerHTML = '▲;' + Cart.number_format(cp.charge);
									 $('coupon_value_hidden').value = cp.charge;
									 //クーポン価格を含めて再計算
									var new_total = 0;
									$$('.subtotal').each(function(tag){
									new_total = new_total+Number($(tag).value);
									});
									//new_total = new_total - cp.charge;

									if(new_total >= $('carriage_free').value)
									{
										$('carriage').innerHTML = '<p>送料は無料となります</p>';
										$('free_msg').innerHTML = '';
									 	$('total').innerHTML = Cart.number_format(new_total - cp.charge);
									}
									else
									{
										$('carriage').innerHTML = '&yen;'+$('carriage_value').value;
										$('free_msg').innerHTML = '<span class="red">あと'+($('carriage_free').value - new_total)+'円のご購入で送料が無料になります！</span>';
									 	$('total').innerHTML = Cart.number_format(new_total+Number($('carriage_value').value - cp.charge));
									}
								}
								catch(e)
								{
									$('coupon_category').innerHTML = '<span class="red">'+httpobj.responseText+ '</span>';
									$('coupon_value').innerHTML = '';

								 }
							 }
						 });
	},
	AjaxLogin : function()
	{
		new Ajax.Request(this.cart_to_path + 'cart/ajaxlogin',
						 {
							 method : 'post',
							 parameters : Form.serialize('coupon_login'),
							 onSuccess : function(res)
							 {
								 value = eval('('+res.responseText + ')');
								 if(value == 1)
								 {
									 Cart.dialogclose();
									if(!Cart.couponFlag)
									{
										$$('.coupon').each(function(tag)
																	{
																		$(tag).style.display = '';
																	}
																	);
										Cart.couponFlag = true;

									}
									$('coupon_code').focus();
									$('coupon_button').disabled = false;
								 }
								 else
								 {
									 $('error').innerHTML = '<span class="red">ログインに失敗しました。</span>';
								 }
							 }
						 });
	},
	AjaxCouponCheck : function()
	{
		var coupon_number = $('coupon_number_not_user').value;
		new Ajax.Request(this.cart_to_path + 'cart/ajaxcoupon_notuser/' + coupon_number,
								{
									method : 'post',
									parameters : Form.serialize('coupon_not_user'),
									onSuccess : function(httpobj)
									{
										try{
												value = eval('('+httpobj.responseText + ')');
												Cart.dialogclose();
												if(!Cart.couponFlag)
												{
													$$('.coupon').each(function(tag)
													{
														$(tag).style.display = '';
													});
													Cart.couponFlag = true;
													$('coupon_code').value = value.a_coupon_code;
													$('coupon_button').disabled = true;
													$('coupon_value_hidden').value = value.charge;
													$('coupon_category').innerHTML = value.coupon_name;
													$('coupon_value').innerHTML = '▲&yen;' + value.charge;
													 //クーポン価格を含めて再計算
													var new_total = 0;
													$$('.subtotal').each(function(tag){
													new_total = new_total+Number($(tag).value);
													});
													//new_total = new_total - cp.charge;

													if(new_total >= $('carriage_free').value)
													{
														$('carriage').innerHTML = '<p>送料は無料となります</p>';
														$('free_msg').innerHTML = '';
														$('total').innerHTML = Cart.number_format(new_total - value.charge);
													}
													else
													{
														$('carriage').innerHTML = '&yen;'+$('carriage_value').value;
														$('free_msg').innerHTML = '<span class="red">あと'+($('carriage_free').value - new_total)+'円のご購入で送料が無料になります！</span>';
														$('total').innerHTML = Cart.number_format(new_total+Number($('carriage_value').value - value.charge));
													}
												}
											}
											catch(e)
											{
												$('error_error').innerHTML = httpobj.responseText;
											}
									}
								});





	}





}
