/**
 * /js/cart/cart.common.js
 * カート共通js
 *
 * @auther  izutani 2011/04/12
 */
var cart = {
	'version' : 1.00,
	'removeProducts' : {}
}

cart.params = {
	
}

cart.common = {

	/**
	 * resetParams
	 * パラメータを初期値に戻す
	 * 
	 */
	resetParams : function() {
		debug(new Date() + ' ** [start] cart.common.resetParams');

		cart.params.is_campaign = false;
		cart.params.edit_delivery_to = null;

		cart.total_amt = {
			'value'   : 0,
			'price_t' : 0,
			'price_m' : 0,
			'price_b' : 0
		}

		cart.postage.free_product = false;
		cart.postage.free_campaign = false;
		cart.postage.teiki_include = false;
		cart.postage.value = cart.postage.base; // TODO: 沖縄対応

		cart.delivery_types = {
			0 : 'standard',
			1 : 'periodical'
		}
	},

	/**
	 * bindViewEvent
	 * お買い物かごイベントの有効化
	 * 商品削除・削除商品の戻し・定期商品への変更 ボタン
	 *
	 */
	bindViewEvent : function() {
		debug(new Date() + ' ** [start] cart.common.bindViewEvent');

		// 商品削除
		$('.cart_item_delete a').bind('click', cart.common.clickDeleteProduct);
		// 削除商品の戻し
		$('.undo-cart-button').bind('click', cart.common.clickUndoProduct);
		// 定期商品への変更
		$('.cart_item_change').bind('click', cart.common.clickChgTeikiProduct);
		// 次の画面へ進むボタン
		$('.view_submit').unbind('click');
	},

	/**
	 * unbindViewEvent
	 * お買い物かごイベントの無効化
	 * 商品削除・削除商品の戻し・定期商品への変更 ボタン
	 *
	 */
	unbindViewEvent : function() {
		debug(new Date() + ' ** [start] cart.common.unbindViewEvent');

		// 商品削除
		$('.cart_item_delete a').unbind('click', cart.common.clickDeleteProduct);
		$('.cart_item_delete a').bind('click', function(){return false;});
		// 削除商品の戻し
		$('.undo-cart-button').unbind('click', cart.common.clickUndoProduct);
		$('.undo-cart-button').bind('click', function(){return false;});
		// 定期商品への変更
		$('.cart_item_change').unbind('click', cart.common.clickChgTeikiProduct);
		$('.cart_item_change').bind('click', function(){return false;});
		// 次の画面へ進むボタン
		$('.view_submit').bind('click', function(){return false;});
	},

	/**
	 * renderCart()
	 * カートのレンダリング（金額・メッセージ）
	 *
	 * [沖縄送料]（送付先住所が沖縄の場合）
	 * cart.postage.okinawa
	 *
	 * [送料無料の条件]
	 * ・合計金額が「cart.postage.free_border」以上
	 * ・送料無料商品カートイン時（cart.postage.free_product == true）
	 * ・定期同梱時（cart.postage.teiki_include == true）
	 * ・送料無料キャンペーン定期用時（cart.postage.free_campaign == true）
	 *
	 * @param
	 * @return
	 */
	renderCart : function() {
		debug(new Date() + ' ** [start] cart.common.renderCart');

		/****************************************************
		 * パラメータを初期値に戻す
		 ****************************************************/
		cart.common.resetParams();

		/****************************************************
		 * 商品情報から各種値の生成
		 ****************************************************/
		var product_count = 0;
		var total_qty = 0;
		var cookie_products = {};
		$.each(cart.products, function(i, product) {
			if (product.qty > 0) {
				product_count++;
				total_qty += eval(product.qty);
				cookie_products[product.id] = {
					'q' : product.qty,
					'g' : product.is_gift
				}
			} else {
				delete cart.products[i];
			}
		});
		// 商品情報をクッキーに保存
		cookie_products = $.toJSON(cookie_products);
		$.cookie(cart.shopInfo.name + '_products', cookie_products, {expires:30, path:'/'});
		// ショップヘッダー合計点数
		$('span#header_products_count').text(total_qty);

		/****************************************************
		 * 送料・合計金額の算出
		 ****************************************************/
		if (cart.action == undefined || cart.action === 'view') {
			cart.common.renderTotalPriceCart();
		} else {
			cart.common.createDeliveryToProducts();
			cart.common.renderTotalPriceDeliveryTo();
		}

		/****************************************************
		 * 適用する合計金額 と キャンペーン値引き額をセット
		 * ログイン時 or 新規会員登録希望時 は 会員価格を適用
		 ****************************************************/
		var campaign_discount_total = 0;
		var member_discount_total = 0;
		if (cart.params.is_member) {
			campaign_discount_total = cart.total_amt.price_b - cart.total_amt.price_m
		} else {
			campaign_discount_total = cart.total_amt.price_b - cart.total_amt.price_t
		}
		member_discount_total = cart.total_amt.price_t - cart.total_amt.price_m;
		$('span.member_discount').text(commaNumber(member_discount_total));

		/****************************************************
		 * キャンペーン
		 ****************************************************/
		// キャンペーン値引き額合計
		if (cart.params.is_discount) {
			$('.nebikigaku').show();
			$('span.campaign_discount').text(commaNumber(campaign_discount_total));
		} else {
			$('.nebikigaku').hide();
		}

		/****************************************************
		 * ビューへセット
		 ****************************************************/
		// ショップヘッダー合計金額（送料含まない）
		$('span#header_total_price').text(commaNumber(cart.total_amt.value));

		/**
		 * 送料無料誘導メッセージ
		 */
		if (cart.postage.value > 0 && product_count > 0) {
			var free_countdown = cart.postage.free_border - cart.total_amt.price_t;
			$('span.free_countdown').text(commaNumber(free_countdown));
			$('#free_countdown').text(commaNumber(free_countdown)); // ヘッダー用
			$('#postageFree').fadeIn();
			if (cart.shopInfo.name != 'gm' && $('a#free_search_url').size() > 0) {
				var href = $('a#free_search_url').attr('href').replace(/min_price:[\d]+/,'min_price:' + free_countdown);
				$('a#free_search_url').attr('href',href);
			}
		} else {
			$('#postageFree').fadeOut();
		}

		// ショップヘッダーの送料無料表示
		if (cart.postage.value > 0) {
			$('#header_free').hide();
			$('#header_free_countdown').show();
		} else {
			$('#header_free').show();
			$('#header_free_countdown').hide();
		}

		/**
		 * 商品表示
		 */
		if (product_count > 0) {
			$('#empty-cart').hide();
			$('#cartInfoTable').show();
			if (cart.postage.value > 0) {
				$('.cartInfoSectionSP,.cartInfoLinkSP').show();
			}
			// ショップヘッダー吹き出し
			$('#orderDetails-fukidashi').show();
		} else {
			$('#empty-cart').show();
			$('#cartInfoTable').hide();
			$('.cartInfoSectionSP,.cartInfoLinkSP').hide();
			// ショップヘッダー吹き出し
			$('#orderDetails-fukidashi').hide();
		}

		/**
		 * 削除商品表示
		 */
		var remove_product_count = 0;
		$.each(cart.removeProducts, function() {
			remove_product_count++;
		});
		if (remove_product_count > 0) {
			$('#cart-back').show();
			$('.cart-back-item').hide();
			var show_remove_count = 0;
			$('.cart-back-item').each(function(){
				var remove_id = $(this).attr('id').replace('remove_item_', '');
				if (cart.removeProducts[remove_id] != undefined) {
					$('#remove_item_' + remove_id).show();
					show_remove_count++;
				}
			});
		} else {
			$('#cart-back').hide();
		}

		// 割引額メッセージの表示切り替え
        if (member_discount_total == 0) {
            $('#web_member_notice').show();
            $('#mem_discount_notice').hide();
			$('#payShip-memberPrice').hide();
        } else {
            $('#web_member_notice').hide();
            $('#mem_discount_notice').show();
        }

		// お支払い・お届け先情報のレンダリング
		if (cart.action == 'address_and_payment') {
			/***************************************************
			 * お支払い方法のラジオボタン制御
			 ***************************************************/
			cart.aap.renderPayment();
		}
	},

	/**
	 * renderTotalPriceCart
	 * お買い物かごの送料・合計金額レンダリング
	 *
	 * [沖縄送料]（送付先住所が沖縄の場合）
	 * cart.postage.okinawa
	 *
	 * [送料無料の条件]
	 * ・合計金額が「cart.postage.free_border」以上
	 * ・送料無料商品カートイン時（cart.postage.free_product == true）
	 * ・定期同梱時（cart.postage.teiki_include == true）
	 * ・送料無料キャンペーン定期用時（cart.postage.free_campaign == true）
	 */
	renderTotalPriceCart : function() {
		debug(new Date() + ' ** [start] cart.common.renderTotalPriceCart');

		$.each(cart.products, function(i, product) {
			/**
			 * 送料無料商品が含まれる場合は送料無料
			 */
			if (cart.postage.value > 0 && product.free_product) {
				cart.postage.value = 0;
			}
			/**
			 * キャンペーン適用
			 */
			if (product.c_type != undefined && product.c_type > 0) {
				cart.params.is_campaign = true;
				cart.params.is_discount = product.is_discount;
			}
			/**
			 * 合計金額
			 */
			cart.total_amt.price_t += (product.qty * product.price_t)  // 通常価格（税込）
			cart.total_amt.price_m += (product.qty * product.price_m)  // 会員価格（税込）
			cart.total_amt.price_b += (product.qty * product.price_b)  // キャンペーン価格適用前の通常価格（税込）
		});

		// 合計金額
		if (cart.params.is_member) {
			cart.total_amt.value = cart.total_amt.price_m;
		} else {
			cart.total_amt.value = cart.total_amt.price_t;
		}

		/****************************************************
		 * 通常価格の合計金額が「cart.postage.free_border」
		 * 以上の場合、送料無料
		 ****************************************************/
		if (cart.total_amt.price_t >= cart.postage.free_border) {
			cart.postage.value = 0;
		}

		/**
		 * 合計金額・送料合計
		 */
		$('#CartTotalPrice').val(cart.total_amt.value + cart.postage.value);
		$('#CartPostage').val(cart.postage.value);
		$('.total_price').text(commaNumber(cart.total_amt.value + cart.postage.value));
		$('span.postage').text(commaNumber(cart.postage.value));
	},

	/**
	 * renderTotalPriceDeliveryTo
	 * お届け先設定のある場合の送料・合計金額レンダリング
	 *
	 * [沖縄送料]（送付先住所が沖縄の場合）
	 * cart.postage.okinawa
	 *
	 * [送料無料の条件]
	 * ・合計金額が「cart.postage.free_border」以上
	 * ・送料無料商品カートイン時（cart.postage.free_product == true）
	 * ・定期同梱時（cart.postage.teiki_include == true）
	 * ・送料無料キャンペーン定期用時（cart.postage.free_campaign == true）
	 */
	renderTotalPriceDeliveryTo : function() {
		debug(new Date() + ' ** [start] cart.common.renderTotalPriceDeliveryTo');

		var total_postage = 0;
		$.each(cart.delivery_to, function(key, value){
			// 複数配送時のみお届け先毎の合計金額・送料を表示
			if (cart.params.is_multi) {
				var jObj = $('#view_delivery_to_' + key);
			}

			if (cart.delivery_to_products[key] != undefined) {
				/**
				 * お届け先別商品表示の更新
				 */
				if (cart.params.is_multi) {
					jObj.find('.to_product_list').empty();
				}

				var delivery_total_amt   = 0;
				var standard_total_amt_t = 0;
				var delivery_total_amt_t = 0;
				var delivery_total_amt_m = 0;
				var delivery_total_amt_b = 0;
				var is_standard = false;
				var is_teiki    = false;
				var is_youmail  = true;
				var postage     = (value.address1.match(/沖縄/)) ? cart.postage.okinawa : cart.postage.base;

				$.each(cart.delivery_to_products[key], function(product_id, qty){

					// 商品名・数量
					if (cart.params.is_multi) {
						var productName = cart.products[product_id].name;
						var tag = '';
						// PC版はリスト、スマホ版はテーブル
						if (isSP == true) {
							tag = '<tr class="payShip-step-itemList"><th>' + productName + '</th><td>数量：' + qty + '</td>';
						}else {
							tag = '<li class="payShip-step-itemList">' + productName + '［数量：' + qty + '］';
						}
						jObj.find('.to_product_list').append(tag);
					}

					/**
					 * 合計金額
					 */
					var price_t = cart.products[product_id].price_t;
					var price_m = cart.products[product_id].price_m;
					var price_b = cart.products[product_id].price_b;
					delivery_total_amt_t += (qty * price_t);
					delivery_total_amt_m += (qty * price_m);
					delivery_total_amt_b += (qty * price_b);

					// セパレートで通常商品の場合、送料が必要となる場合がある。
					if (cart.delivery_to[key].type == 'separated') {
						if (cart.products[product_id].is_teiki == false) {
							// 通常商品の合計金額
							standard_total_amt_t += price_t * qty;
							// 送料無料商品判定
							if (cart.products[product_id].free_product) {
								postage = 0;
							}
						}
					}else {
						// 送料無料商品判定
						if (cart.products[product_id].free_product) {
							postage = 0;
						}
					}

					/**
					 * キャンペーン適用
					 */
					if (cart.products[product_id].c_type != undefined && cart.products[product_id].c_type > 0) {
						cart.params.is_campaign = true;
						cart.params.is_discount = cart.products[product_id].is_discount;
					}

					// 通常商品判定
					if (cart.products[product_id].is_teiki == false) {
						is_standard = true;
					}
					// 定期商品判定
					if (cart.products[product_id].is_teiki == true) {
						is_teiki = true;
					}

					if (cart.products[product_id].is_teiki == false && cart.products[product_id].deliver_flg != '2') {
						is_youmail = false;
					}

				});

				/**
				 * お届け先別送料計算
				 */
				if (cart.delivery_to[key].type == 'separated') {
					// セパレートの場合、通常商品のみで送料が必要となる場合がある。
					if (standard_total_amt_t >= cart.postage.free_border) {
						postage = 0;
					}
				} else {
					// その他は全ての合計金額で送料判定
					if (delivery_total_amt_t >= cart.postage.free_border) {
						postage = 0;
					}
				}

				/****************************************************
				 * 適用する合計金額 と キャンペーン値引き額をセット
				 * ログイン時 or 新規会員登録希望時 は 会員価格を適用
				 ****************************************************/
				cart.total_amt.price_t += delivery_total_amt_t;  // 通常価格（税込）
				cart.total_amt.price_m += delivery_total_amt_m;  // 会員価格（税込）
				cart.total_amt.price_b += delivery_total_amt_b;  // キャンペーン価格適用前の通常価格（税込）
				if (cart.params.is_member) {
					delivery_total_amt = delivery_total_amt_m;
				} else {
					delivery_total_amt = delivery_total_amt_t;
				}
				cart.total_amt.value += delivery_total_amt;

				/**
				 * 複数配送時はお届け先別の情報を表示
				 */
				if (cart.params.is_multi) {
					// お届け先別合計金額
					jObj.find('.deliveryToTotalAmt').text(commaNumber(delivery_total_amt));
					// お届け先別送料
					// PC版は無料、スマホ版は0円
					var viewPostage = '';
					if (isSP == true) {
						viewPostage = postage;
					} else {
						viewPostage = (postage > 0) ? commaNumber(postage) + '円' : '<span class="red">無料</span>';
					}
					jObj.find('.deliveryToPostage').html(viewPostage);
					// 商品指定のあるお届け先を表示
					jObj.show();
				}

				// 全てのお届け先の送料合計
				total_postage += postage;

				// お届け先指定タイプのセット（通常・定期）
				cart.delivery_to[key].is_standard = is_standard;
				cart.delivery_to[key].is_teiki = is_teiki;
				cart.delivery_to[key].is_youmail = is_youmail;

			} else {
				/**
				 * 複数配送時、商品指定のないお届け先は非表示
				 */
				if (cart.params.is_multi) {
					$('#view_delivery_to_' + key).hide();
				}
			}
		});
		
		// 複数配送時のお届け先番号の表示
		if (cart.params.is_multi) {
			var delivery_to_count = 0;
			$('.multiDeliveryToBlock').each(function(){
				if ($(this).css('display') != 'none') {
					// お届け先番号
					delivery_to_count++;
					$(this).find('.deliveryToCount').text(delivery_to_count);
				}
			});
		}

		// 送料
		cart.postage.value = total_postage;

		// 確認画面で定期同梱時は送料無料
		if (cart.action === 'confirm' && cart.params.is_doukon && cart.params.doukon_selected) {
			cart.postage.value = 0;
		}

		/**
		 * 合計金額・送料合計
		 */
		$('#CartTotalPrice').val(cart.total_amt.value + cart.postage.value);
		$('#CartPostage').val(cart.postage.value);
		$('.total_price').text(commaNumber(cart.total_amt.value + cart.postage.value));
		$('span.postage').text(commaNumber(cart.postage.value));
	},

	/**
	 * renderDoukonMsg
	 * 定期同梱時のメッセージ表示・非表示
	 */
	renderDoukonMsg :function() {
		debug(new Date() + ' ** [start] cart.common.renderDoukonMsg');

		if (cart.postage.value > 0 && cart.params.is_doukon && cart.select_delivery_to == 'my') {
			$('#payShip-postageFree').fadeIn();
			$('#payShip-postageFreeMsg').fadeIn();
		} else {
			$('#payShip-postageFree').fadeOut();
			$('#payShip-postageFreeMsg').fadeOut();
		}
	},

	/**
	 * openWindow()
	 * ポップアップウィンドウを開く
	 *
	 * @param  id
	 * @return
	 */
	openWindow : function(id) {
		debug(new Date() + ' ** [start] cart.common.openWindow');

		$.blockUI({
			message: $('#' + id),
			css: {
				border  : 'none',
				width   : '770px',
				height  : '84%',
				top     : '10%',
				left    : '50%',
				cursor  : 'auto',
				'margin-left'   : '-385px',
				backgroundColor : 'transparent',
				'overflow'      : 'auto'
			},
			overlayCSS:  {
				cursor  :'auto',
				opacity : '0.8',
				backgroundColor : '#fff'
			}
		});
	},

	/**
	 * openPlusWindow()
	 * 糖質0円用ポップアップウィンドウを開く
	 *
	 * @param  id
	 * @return
	 */
	openPlusWindow : function(id) {
		debug(new Date() + ' ** [start] cart.common.openPlusWindow');

		$.blockUI({
			message: $('#' + id),
			css: {
				border  : 'none',
				width   : '100%',
				height  : '90%',
				top     : '10%',
				left    : '50%',
				cursor  : 'auto',
				'margin-left'   : '-50%',
				backgroundColor : 'transparent',
				'overflow'      : 'auto'
			},
			overlayCSS:  {
				cursor  :'auto',
				opacity : '0.8',
				backgroundColor : '#000'
			}
		});
	},


	/**
     * setDatePicker
     * カレンダー表示・選択後、時間帯指定チェック
     *
	 * @param key  お届け先キー
     */
    setDatePicker: function(key){
		debug(new Date() + ' ** [start] cart.common.setDatePicker');

		var jObj = $('#standard_delivery_date_' + key);

		// カレンダー初期化
		jObj.find('.datepicker').datepicker('destroy');

		// 最短発送日
		var shortest = cart.delivery_to[key].shortest.standard;

		// 初期選択
		var default_date = null;
		if (jObj.find('.valueStandardAppointDate').val() == '') {
			jObj.find('.btnShowCalender').hide();
		} else {
			default_date = new Date(jObj.find('.valueStandardAppointDate').val().replace(/-/g, '/'));
		}

		/**
		 * datepicker
		 */
		jObj.find('.datepicker').datepicker({
			minDate          : new Date(shortest.replace(/-/g, '/')), // 最短お届け日（yyyy/mm/dd）
			numberOfMonths   : 2,
			hideIfNoPrevNext : true,
			showButtonPanel  : false,
			maxDate          : '+2M',
			dateFormat       : 'yy-mm-dd',
			defaultDate      : default_date,
			onSelect: function(dateText, inst){
				// お届け日情報の更新
				var appointDate = date('Y年m月d日', strtotime(dateText));
				jObj.find('.valueStandardAppointDate').val(dateText);
				jObj.find('.payShip-aboutDate3').text(appointDate);
				jObj.find('.viewStandardAppointDate').fadeIn();
				jObj.find('.btnShowCalender').fadeIn();
				// 選択後カレンダーを非表示
				jObj.find('.datepicker').slideUp(dateText);
				// お届け日指定日時をDOMにセット
				cart.delivery_to[key].appoint.standard = date('Y-m-d', strtotime(dateText));
				// 最短お届け指定フラグDOMの更新
				cart.delivery_shortests[key].standard = (cart.delivery_to[key].appoint.standard == shortest);
				// お届け日時間指定のチェック
				cart.common.chkSettimeFlag(key, 'standard');
			}
		});
	},

	/**
	 * chkSettimeFlag
	 * 時間帯指定不可チェック
	 *
	 * settime_flg
	 * 8  : 全て指定可
	 * 14 : 最短お届け日指定の場合、14時以降で時間帯指定可
	 * 18 : 最短お届け日指定の場合、18時以降で時間帯指定可
	 * 99 : 全て指定不可
	 *
	 * @param key  お届け先キー
	 * @param type standard：通常お届け, periodical：定期お届け
	 */
	chkSettimeFlag : function(key, type) {
		debug(new Date() + ' ** [start] cart.common.chkSettimeFlag');

		var jObj = $('#' + type + '_delivery_date_' + key + ' .settime');

		// スマホ用、初期状態のselectタグ内のオプションをバックアップ
		// この部分はページを開いたときに一回しか実行されない
		if (isSP === true &&
			(!cart.__tmpTimeZoneOption || typeof cart.__tmpTimeZoneOption === 'undefined' || cart.__tmpTimeZoneOption === null)) {
			cart.__tmpTimeZoneOption = jObj.find('select.' + type + '_timezone').html();
		}
		cart.__selectedTimeZoneOption = jObj.find('select.' + type + '_timezone option:selected').val();  // スマホ

		// お届け先の時間帯指定フラグ
		var settime_flag = cart.delivery_to[key].settime_flag;
		// 最短日を指定しいるかのフラグ
		var shortest = cart.delivery_shortests[key][type];

		/**
		 * お届け時間帯指定オプション（値・メッセージ）の初期化
		 */
//		jObj.find('input.' + type + '_timezone').removeAttr('disabled');  // jquery1.6.2 IE6動作しない
		jObj.find('input.' + type + '_timezone').prop('disabled', false);
		jObj.find('select.' + type + '_timezone option').remove();	// スマホ
		jObj.find('select.' + type + '_timezone').append(cart.__tmpTimeZoneOption);  // スマホ
		jObj.find('select.' + type + '_timezone').val(cart.__selectedTimeZoneOption);  // スマホ
		jObj.find('label').attr('style', '');
		jObj.siblings('.settime_alert').remove();
		jObj.siblings('.timeSendComment').remove();
		jObj.show();

		/**
		 * 時間帯指定不可の地域は、最短日指定かどうかにかかわらず時間帯指定不可
		 */
		if (settime_flag == '99')
		{
			// お届け時間帯の値を「指定しない」にリセット。
			jObj.find('input[value="0"]').attr('checked', 'checked');
			jObj.find('select.' + type + '_timezone').val(0);
			// 時間帯指定不可メッセージを表示。
			jObj.before('<span class="settime_alert">ご指定のお届け先はお届け時間帯をお選びいただけません</span>')
			// お届け時間帯指定ラジオボタン非表示
			jObj.hide();
		}
		/**
		 * 最短日指定の場合は、時間帯指定不可チェック
		 */
		else if (shortest) {
			var msg = '';
			/**
			 * 「14時～16時」以降指定可
			 */
			if (settime_flag == '14' || settime_flag == '18') {
				// 指定不可のお届け時間帯を選択していた場合、お届け時間帯の値を「指定しない」にリセット。
				if (jObj.find('input:checked,select.' + type + '_timezone').val() == 1 || jObj.find('input:checked,select.' + type + '_timezone').val() == 2) {
					jObj.find('input[value="0"]').attr('checked', 'checked');
					jObj.find('select.' + type + '_timezone').val(0);
				}

				/**
				 * 指定不可のお届け時間帯を非表示
				 */
				// 午前中指定不可
				jObj.find('input[value="1"]').attr('disabled', true);
				jObj.find('label[for="' + type + '_timezone1"]').attr('style', 'color: #BBBBBB;');
				jObj.find('select.' + type + '_timezone option[value="1"]').remove(); // スマホ
				// 12時～14時不可
				jObj.find('input[value="2"]').attr('disabled', true);
				jObj.find('label[for="' + type + '_timezone2"]').attr('style', 'color: #BBBBBB;');
				jObj.find('select.' + type + '_timezone option[value="2"]').remove(); // スマホ
				
				// 時間帯指定不可メッセージを表示。
				msg = '<div class="timeSendComment"><p>ご指定のお届け日は「14時～16時」以降の時間帯を指定いただけます。</p></div>';
			}

			/**
			 * 「18時～20時」以降指定可
			 */
			if (settime_flag == '18') {
				// 指定不可のお届け時間帯を選択していた場合、お届け時間帯の値を「指定しない」にリセット。
				if (jObj.find('input:checked,select.' + type + '_timezone').val() == 3 || jObj.find('input:checked,select.' + type + '_timezone').val() == 4) {
					jObj.find('input[value="0"]').attr('checked', 'checked');
					jObj.find('select.' + type + '_timezone').val(0);
				}

				/**
				 * 指定不可のお届け時間帯を非表示
				 */
				// 14時～16時不可
				jObj.find('input[value="3"]').attr('disabled', true);
				jObj.find('label[for="' + type + '_timezone3"]').attr('style', 'color: #BBBBBB;');
				jObj.find('select.' + type + '_timezone option[value="3"]').remove(); // スマホ
				// 16時～18時不可
				jObj.find('input[value="4"]').attr('disabled', true);
				jObj.find('label[for="' + type + '_timezone4"]').attr('style', 'color: #BBBBBB;');
				jObj.find('select.' + type + '_timezone option[value="4"]').remove(); // スマホ
				// 時間帯指定不可メッセージを表示。
				msg = '<div class="timeSendComment"><p>ご指定のお届け日は「18時～20時」以降の時間帯を指定いただけます。</p></div>';
			}

			/**
			 * メッセージ表示
			 */
			if (msg != '') {
				jObj.after(msg);
			}
		}
	},

	/**
	 * clickDekoobiPreview
	 * フォトおびポップアッププレビュー
	 */
	clickDekoobiPreview : function() {
		$('.preview_link').live('click',function() {
			debug(new Date() + ' ** [start] cart.common.clickDekoobiPreview');

			var time = new Date().getTime();
			var id = $(this).attr('id').replace('decoobi_preview_', '');
			var src = '/decoobi/' + cart.shopInfo.prefix + 'preview/'+ id +'/'+ time;
			$('#previewPopupBorder').find('img#image').attr('src', src).load(function(){
				$('#previewPopupBorder').show();

				$('#previewPopupBorder').css({
					'width' : '600px',
					'padding': '5px 5px 25px 5px',
					'border': '1px solid #000000',
					'background-color' : '#ffffff'
				});
			});
			$.blockUI({
				message: $('#previewPopupBlock'),
				fadeIn: 500,
				overlayCSS : {
					backgroundColor: '#ffffff'
				},
				css : {
					border:'none',
					cursor: 'auto',
					width: '0px',
					top: '50%',
					left: '50%',
					margin: '-110px 0 0 -300px'
				}
			});

			// 背景をクリックしてポップアップを閉じる
			$('.blockOverlay').click(function() {
				setTimeout($.unblockUI, 1);
			});
			// 背景をクリックしてポップアップを閉じる
			$('#previewPopupBorder').find('img#close').click(function() {
				setTimeout($.unblockUI, 1);
			});

			return false;
		});
	},

	/**
	 * chgQty
	 * お買い物かご・お支払い方法入力画面の数量変更チェンジイベント
	 * 
	 */
	chgQty : function () {
		$('.product_qty').change(function(){
			debug(new Date() + ' ** [start] cart.common.chgQty');

			var key   = $(this).attr('id').replace(/product_qty_/,'');
			var qty   = toHankakuNumber($(this).val());
			var price = (cart.params.is_member) ? cart.products[key].price_m : cart.products[key].price_t;
			var subtotal = qty * price;

			// 数量チェック
			if (!cart.common.chkProductQty(key, qty)) {
				$(this).val(cart.products[key].qty);
				return;
			} else {
				qty = parseInt(qty, 10);
				$(this).val(qty);
			}

			// イベントの無効化
			cart.common.unbindViewEvent();

			var url = '/carts/chgProductQty/';

			// キャッシュ無効・確実に値を変更する為に同期
			$.ajaxSetup({
				cache : false,
				async : false
			});

			$.post(
				url,
				{
					'id' : key,
					'qty' : qty
				},
				function(data, status) {
					if (data != 'success') {
						alert('数量変更に失敗しました');
					} else {
						$('#cart_item_' + key + ' .unit_price_total').text(commaNumber(subtotal));

						// DOMの数量更新
						cart.products[key].qty = qty;
						// 送料のリセット
						cart.postage.value = cart.postage.base;
						// レンダリング
						cart.common.renderCart();

						// 定期同梱送料無料メッセージの表示・非表示
						cart.common.renderDoukonMsg();
					}

					// イベントの有効化
					cart.common.bindViewEvent();
				},
				"text"
			);
		});
	},

	/**
	 * chkProductQty
	 * 数量チェック
	 * 
	 */
	chkProductQty : function (product_id, qty) {
		debug(new Date() + ' ** [start] cart.common.chkProductQty');

		var jObj = $('#cart_item_' + product_id);

		jObj.find('.qtyMsgBlock').hide();
		// バリデーション
		var validate = true;
		// 数値チェック
		if (qty.match(/[^0-9]/g)) {
			validate = false;
			jObj.find('.qtyMsgBlock .qtyMsg').text('数字でご指定ください');
		}
		// 1個以下または999個以上の場合はエラー
		if (qty > 999 || qty < 1) {
			validate = false;
			jObj.find('.qtyMsgBlock .qtyMsg').text('1～999でご指定ください');
		}

		// 入力チェックエラー時はエラー吹き出しメッセージ表示
		if (validate == false) {
			jObj.find('.qtyMsgBlock').fadeIn();
		}

		return validate;
	},

	/**
	 * clickDeleteProduct
	 * お買い物かご 商品削除ボタン クリックイベント
	 *
	 */
	clickDeleteProduct : function() {
		debug(new Date() + ' ** [start] cart.common.clickDeleteProduct');
		
		/* スマフォのHTML構造上、セレクタを一まとめにしたときにTRを拾ってしまうため、
		 * スマフォかPCかで分岐させています。
		 */
		var product_id = null;
		if (isSP == true) {
			var product_id = $(this).closest('div.item').attr('id').replace('cart_item_', '');
		} else {
			var product_id = $(this).closest('tr').attr('id').replace('cart_item_', '');
		}
		cart.common.deleteProduct(product_id);
		return false;
	},

	/**
	 * clickUndoProduct
	 * お買い物かご 削除した商品を戻すボタン クリックイベント
	 *
	 */
	clickUndoProduct : function() {
		debug(new Date() + ' ** [start] cart.common.clickUndoProduct');
		var product_id = $(this).closest('div').attr('id').replace('remove_item_', '');
		cart.common.undoProduct(product_id);
		return false;
	},

	/**
	 * clickChgTeikiProduct
	 * 定期商品への変更 クリックイベント
	 *
	 * @param
	 * @return
	 */
	clickChgTeikiProduct : function() {
		debug(new Date() + ' ** [start] cart.common.clickChgTeikiProduct');
		var id   = $(this).attr('id').replace(/cart_item_change_/,'');
		var from = id.replace(/_to_.+$/, '');
		var to   = id.replace(/^[^_]+_to_/, '');

		cart.common.chgProduct(from, to);

		// PC版お買い物かごはページトップ遷移なし。
		if (cart.action === 'view' && !isSP) {
			return false;
		}
	},

	/**
	 * deleteProduct
	 * 商品削除
	 *
	 * @param  product_id
	 * @return
	 */
	deleteProduct : function(product_id) {
		debug(new Date() + ' ** [start] cart.common.deleteProduct');

		// イベントの無効化
		cart.common.unbindViewEvent();

		var url = '/carts/deleteProduct/';

		// キャッシュ無効
		$.ajaxSetup({cache: false});

		$.post(
			url,
			{
				'productID' : product_id
			},
			function(data, status) {
				if (data != 'success') {
					// エラー
				} else {
					$('#cart_item_' + product_id).fadeOut();
					$('#cart_item_teikimsg_' + product_id).fadeOut("normal", function(){
						// 削除後の段階で定期アップセルのボタンがなければ説明文を消す
						if($('tr[id ^= cart_item_teikimsg_]:visible').size() < 1) {
							$('#description-teiki').hide();
						}
					});
					cart.removeProducts[product_id] = cart.products[product_id];
					delete cart.products[product_id];


					// レンダリング
					cart.common.renderCart();
				}

				// イベントの有効化
				cart.common.bindViewEvent();
			},
			"text"
		);
	},

	/**
	 * undoProduct
	 * 削除した商品を戻す
	 *
	 * @param  product_id
	 * @return
	 */
	undoProduct : function(product_id) {
		debug(new Date() + ' ** [start] cart.common.undoProduct');

		// イベントの無効化
		cart.common.unbindViewEvent();

		var url = '/carts/undoProduct/';

		// キャッシュ無効
		$.ajaxSetup({cache: false});

		$.post(
			url,
			{
				'productID' : product_id
			},
			function(data, status) {
				if (data != 'success') {
					// エラー
				} else {
					$('#cart_item_' + product_id).fadeIn();
					$('#cart_item_teikimsg_' + product_id).fadeIn();
					cart.products[product_id] = cart.removeProducts[product_id];
					delete cart.removeProducts[product_id];

					// レンダリング
					cart.common.renderCart();

					// 商品復活後、定期アップセルのボタンがあれば説明文を表示する
					if($('tr[id ^= cart_item_teikimsg_]:visible').size() > 0) {
						$('#description-teiki').show();
					}
				}

				// イベントの有効化
				cart.common.bindViewEvent();
			},
			"text"
		);
	},

	/**
	 * chgProduct
	 * 商品情報を定期商品に変更
	 *
	 * @param  from
	 * @param  to
	 */
	chgProduct: function(from, to) {
		debug(new Date() + ' ** [start] cart.common.chgProduct');

		// イベントの無効化
		cart.common.unbindViewEvent();

		// ローディング
		if (cart.action == 'confirm') {
			cart.init.overlayLoading();
			if (isSP === true) {
				$.mobile.showPageLoadingMsg();
			} 
		}

		var url = '/carts/chgProduct/' + from + '/' + to + '/';

		// キャッシュ無効
		$.ajaxSetup({cache: false});

		$.getJSON(
			url,
			null,
			function (json, status) {
				if (json.status != 'success') {
					// エラー

				} else {

					// 既存判定
					var existFlg = false;
					if (cart.products[to] != undefined) {
						existFlg = true;
					}

					// 変更前の商品名
					var beforeProdName = cart.products[from].name;

					cart.products = json.data;
					var qty = cart.products[to].qty;
					var price = (cart.params.is_member) ? cart.products[to].price_m : cart.products[to].price_t;
					var subtotal = qty * price;

					/************************************************
					 * 既にカート内に変更後の商品がある場合は、数量加算
					 * 新規カートインとなる場合は、変更後の商品情報を描画
					 ************************************************/
					if (existFlg) {
						/**
						 * 既存ありの場合、数量変更
						 */
						if (!(isSP === true && cart.action === 'view')) {
							// スマフォ版買い物かご画面ではselectを使っている関係で影響を受けてしまうため、この処理を回避
							$('#cart_item_' + to).find('.product_qty').text(qty);
						}
						
						// スマフォで定期アップセルすると10個以上になる場合、合計値のoptionを追加する。
						if (cart.action === 'view' && isSP === true && qty >= 10) {
							// 個数のoptionが10以上のものがあればまず削除
							if ($('#cart_item_' + to).find('.product_qty').children().length > 10) {
								$('#cart_item_' + to).find('.product_qty').children().last().remove();
							}
							$('#cart_item_' + to).find('.product_qty').append($('<option>').attr({value: qty}).text(qty));
						}
						$('#cart_item_' + to).find('.product_qty').val(qty);
						$('#cart_item_' + to).find('.unit_price_total').text(commaNumber(subtotal));
					} else {
						/**
						 * 変更後の商品情報を描画
						 */
						// 変更前のクローンを生成する
						var beforeProduct = $('#cart_item_' + from).clone(true);
						beforeProduct.attr('id', 'cart_item_' + to);

						/************************************************
						 * お買い物かごのみ
						 ************************************************/
						if (cart.action == 'view') {
							// 数量入力ボックスの値更新
							beforeProduct.find('#product_qty_' + from).attr('id', 'product_qty_' + to);
							var before_name = beforeProduct.find('#product_qty_' + to).attr('name').replace('[' + from + ']', '[' + to + ']');
							beforeProduct.find('#product_qty_' + to).attr('name', before_name);
							beforeProduct.find('.product_qty').val(qty);
							
							if (isSP) {
								//SPの場合アップセルボタン削除
								beforeProduct.find('.bestArea').remove();
							}

							// 削除済アイテムブロックの更新
							$('#remove_item_' + from).attr('id', 'remove_item_' + to);
							$('#remove_item_' + to).find('.productName').text(cart.products[to].name);
							$('#remove_item_' + to).find('.tankaInc').text(commaNumber(cart.products[to].price_t));
							$('#remove_item_' + to).find('.itemForm-photo').attr('src', '/' + cart.products[to].thumbnail);
						}

						/************************************************
						 * お買い物かご・確認画面共用
						 ************************************************/
						// 変更後の商品情報をセット

						// 商品名と画像がSP版の各ページでHTML構造が違うため、それぞれ別個で処理
						if (isSP === true && cart.action !== 'confirm') {
							//  SP版お買物かご
							beforeProduct.find('.productName').after('<p class="ico"><img alt="" src="/img/sp/common/ico_course_regularly.png"></p>');
							beforeProduct.find('.productName').text(cart.products[to].name);
						} else if (isSP === true && cart.action === 'confirm') {
							// SP版確認画面
							beforeProduct.find('.confirmProductNameSP').after('<p class="ico"><img alt="" src="/img/sp/common/ico_course_regularly.png"></p>');
							beforeProduct.find('.confirmProductNameSP').text(cart.products[to].name);
						} else {
							// PC版共通
							beforeProduct.find('.productName').before('<img alt="" src="/img/sys/cart/icon-regular.gif">');
							beforeProduct.find('.productName').text(cart.products[to].name);
						}
						beforeProduct.find('.tankaInc').text(commaNumber(cart.products[to].price_t));
						beforeProduct.find('.memberInc').text(commaNumber(cart.products[to].price_m));
						beforeProduct.find('.unit_price_total').text(commaNumber(subtotal));
						beforeProduct.find('.itemForm-photo').attr('src', '/' + cart.products[to].thumbnail);

						// 変更前の商品情報の下に描画
						$('#cart_item_' + from).after(beforeProduct);
					}

					// 変更前商品の削除
					$('#cart_item_' + from).remove();
					$('#cart_item_teikimsg_' + from).remove();
					$('#remove_item_' + from).remove();

					// 定期アップセルのボタンが無ければ説明文を消す
					if($('tr[id ^= cart_item_teikimsg_]:visible').size() < 1) {
						$('#description-teiki').hide();
					}

					/************************************************
					 * 確認画面のみ
					 ************************************************/
					// 確認画面定期アップセル完了メッセージの表示
					if (cart.action == 'confirm') {
						// お届け先別商品情報DOM更新
						cart.delivery_to_products[cart.select_delivery_to][to] = qty;
						delete cart.delivery_to_products[cart.select_delivery_to][from];

						// ローディングオーバレイ解除
						$.unblockUI();
						if (isSP) {
							$.mobile.hidePageLoadingMsg();
						}

						// 変更前の商品名のセット
						$('#teikiChangeFromProd').text(beforeProdName);
						$('#teikiChangeElement').fadeIn();

						// お届け先商品情報のレンダリング
						$('#standard_products').empty();
						$('#periodical_products').empty();
						$.each(cart.products, function(i, product){
							var tag_product = '<tr><td class="fontSpace1">・' + product.name + '</td><td class="amount">数量：' + product.qty + '</td></tr>';
							if (cart.select_delivery_type == 'separated') {
								if (!product.is_teiki) {
									$('#standard_products').append(tag_product);
								}
								if (product.is_teiki) {
									$('#periodical_products').append(tag_product);
								}
							} else {
								$('#periodical_products').append(tag_product);
								$('.standardDeliveryTo').hide();
								$('.periodicalDeliveryTo').show();
							}
						});

						// 定期変更ボタンの非表示
						$('#cart_item_change_' + from + '_to_' + to).remove();

						// 確認画面定期変更が可能な場合は「注文する」ボタン非表示
						if ($('#confirm_teiki_change img').size() == 0) {
							$('#nonchange_confirm_submit').remove();
							$('#confirm_submit').show();
						}
					}

					// 送料のリセット
					cart.postage.value = cart.postage.base;
					// レンダリング
					cart.common.renderCart();
					
					if (cart.action == 'confirm' || isSP === true) {
						$.unblockUI();
					}
				}

				// イベントの有効化
				cart.common.bindViewEvent();
			}
		);
	},

	/**
	 * clickAddProduct
	 * 商品追加（ポップアップカート or レコメンド）
	 *
	 * @param
	 * @param
	 */
	clickAddProduct : function () {
		$('.addCartBtn, .addRelatedProduct').live('click', function(){
			debug(new Date() + ' ** [start] cart.common.clickAddProduct');
			var is_popup = true;
			if ($(this).attr('class') === 'addRelatedProduct') {
				is_popup = false;
			}
			$('#popupProductId').text('');
			var id = $(this).attr('id').replace(/addCartBtn_/,'');
			var uniq_name = id.replace(/_.+$/,'');
			if ($('#addCartAsGift_' + id) && uniq_name) {
				if ($('#addCartAsGift_' + id).attr('checked')) {
					cart.common.addProduct(uniq_name, 1, is_popup);
				} else {
					cart.common.addProduct(uniq_name, 0, is_popup);
				}
			} else {
				cart.common.addProduct(uniq_name, 0, is_popup);
			}
		});
	},

	/**
	 * addProduct
	 * フロント側ページからの商品追加
	 * （ギフト）
	 *
	 * @param  uniq_name
	 * @param  is_gift
	 * @param  is_popup
	 */
    addProduct : function(uniq_name, is_gift, is_popup) {
		debug(new Date() + ' ** [start] cart.common.addProduct');

		var url = '/carts/addProduct/' + uniq_name + '/' + is_gift + '/';

		// キャッシュ無効
		$.ajaxSetup({cache: false});

		$.getJSON(
			url,
			null,
			function (json, status) {
				if (json.status != 'success') {
					// 失敗
					if (json.data == 'disabled') {
						cart.common.popupCart(__('Error:Disabled Product'), false);
					} else if (json.data == 'max') {
						cart.common.popupCart(__('Error:Max Product'), false);
					} else {
						cart.common.popupCart(__('Error:Add Cart'), false);
					}

				} else {
					// 商品情報DOMの更新
					cart.products = json.data;
					// 成功
					if (is_popup) {
						cart.common.popupCart(__('Add Cart'), uniq_name);
					} else {
						cart.common.createRecommendProduct(uniq_name);
					}
				}
			}
		);
    },

	/**
	 * popupCart
	 * カートインポップアップの表示
	 *
	 * @param message   商品追加メッセージ
	 * @param uniq_name 商品ユニーク名
	 */
	popupCart: function(message, uniq_name) {
		debug(new Date() + ' ** [start] cart.common.popupCart');

		var div  = '' ;

		// uniq_name が取得できた場合、数量変更画面を表示
		if (uniq_name) {
			div = '#popupCart';

			// 商品情報
			var product = null;
			$.each(cart.products, function(index, value){
				if (value.uniq_name == uniq_name) {
					product = value;
				}
			});

			if (product) {
				// カート内数量
				var num = product.qty;

				// 表示項目のセット
				$('#popupProductId').html(product.id);
				$('#popupProductTitle').html(product.name);

				if (product.price_b && product.is_discount) {
					// キャンペーン価格
					$('#popupProductPrice').html(commaNumber(parseInt(product.price_b)));
					if (cart.params.is_member) {
						$('#popupProductDiscountPrice').html(commaNumber(parseInt(product.price_m)));
					} else {
						$('#popupProductDiscountPrice').html(commaNumber(parseInt(product.price_t)));
					}
					$('#popupProductDiscountTitle').html('特別価格');
				} else {
					// 通常価格
					$('#popupProductPrice').html(commaNumber(parseInt(product.price_t)));
					$('#popupProductDiscountPrice').html(commaNumber(parseInt(product.price_m)));
					$('#popupProductDiscountTitle').html('WEB会員価格');
				}

				// 商品値引きのメッセージ表示
				var discount = 0;
				if (cart.params.is_member) {
					if (product.discount_m) {
						discount = product.discount_m;
					}
				} else {
					if (product.discount_t) {
						discount = commaNumber(parseInt(product.discount_t));
					}
				}

				if (discount > 0) {
					var campaignMsg = product.c_name + 'の価格が適用されました<br />';
					$('#popupCampaignMsg').html(campaignMsg + discount + '円引き');
				}

				$('#popupProductNum').html(num);
				$('#popupSubject').html(message);
				$('#popupProductImage').empty();
				if (product.thumbnail) {
					$('#popupProductImage').append('<img src="/' + product.thumbnail + '" alt="" width="62" height="62" />');
				}
			} else {
				div = '#popupMessage';
				message = __('Error:Add Cart');
				$('#message').html(message);
			}
		}
		// id が取得できない場合はメッセージのみ表示
		else
		{
			div = '#popupMessage';
			$('#message').html(message);
		}

		// ポップアップカート表示
		$.extend($.blockUI.defaults.overlayCSS, {backgroundColor: '#ffffff'});
		$.extend($.blockUI.defaults.css, {border:'none', textAlign: 'left', cursor: 'auto', top: '30%'});
		$.blockUI({message: $(div), fadeIn: 500});

		// 背景をクリックしてポップアップを閉じる
		$('.blockOverlay').attr('title', 'お買い物を続ける').click(function() {
			setTimeout($.unblockUI, 1);
		});
	},

	/**
	* cntProduct
	* 数量変更
	*
	* @param  num   現在数量
	* @param  type  true: カウントアップ、 false：カウントダウン
	* @return num   変更後の数量
	*/
	cntProduct: function(num, type) {
		debug(new Date() + ' ** [start] cart.common.cntProduct');

		if (type) {
			num++;
		} else {
			num--;
		}

		if(num < 0) {
			num = 0;
		} else if (num > cart.shopInfo.limit_qty) {
			num = cart.shopInfo.limit_qty;
		}

		return num;
	},

	/**
	* showPopup
	* ポップアップ表示
	*
	*/
	showPopup: function() {

		///////////////////////////////////
		// 数量変更ポップアップ
		///////////////////////////////////
		
		// イシュア対応 
		if(cart.action == undefined && shopCode == "0001"){
		var templateCart =
        '<div class="inner">\
	      <span id="popupProductId" style="display: none;"></span>\
	      <div class="title"><img src="' + global.baseUrl + 'img/cartin-popup/ttl_cartin_popup_issua.jpg" alt="以下の商品が買い物かごに入りました。（数量が0の時には入りません）" width="446" height="40" /></div>\
	      <div class="item clearfix">\
		    <p class="image" id="popupProductImage"></p>\
		    <dl class="data">\
			<dt id="popupProductTitle"></dt>\
			<dd>\
				販売価格：<span id="popupProductPrice"></span>円<br />\
				<span id="popupProductDiscountTitle"></span>：<span id="popupProductDiscountPrice"></span>円<br />\
				<span id="popupCampaignMsg"></span>\
			</dd>\
		    </dl>\
		    <div class="operate">\
			<div class="amount">\
			<p id="popupProductNum"><span>数量：</span>1</p>\
			<div>\
			<a href="javascript:void(0);" id="countUp"><img src="' + global.baseUrl + 'img/cartin-popup/btn_add.jpg" alt="1つ増やす" width="20" height="14" /></a>\
			<a href="javascript:void(0);" id="countDown"><img src="' + global.baseUrl + 'img/cartin-popup/btn_reduce.jpg" alt="1つ減らす" width="20" height="14" /></a>\
			</div>\
			</div>\
			<p class="move"><a href="' + global.baseUrl + 'carts/issua_view" class="popupToCart"><img src="' + global.baseUrl + 'img/cartin-popup/btn_move_cart_issua.jpg" alt="買い物かごへ進む" width="154" height="42" /></a></p>\
		    </div>\
		    <div class="clear"></div>\
	        </div>\
	        <div class="continue">\
		    <img src="' + global.baseUrl + 'img/cartin-popup/img_lion_issua.jpg" alt="引き続きお買い物をお楽しみいただく場合は「お買い物を続ける」をクリックしてください" width="420" height="82" />\
		    <a href="javascript:void(0);" class="popupClose"><img src="' + global.baseUrl + 'img/cartin-popup/btn_continue.jpg" alt="お買物を続ける" width="124" height="30" /></a>\
	        </div>\
            </div>';
            
		} else {
		var templateCart =
			'<div class="inner">\
			<span id="popupProductId" style="display: none;"></span>\
			<div class="title"><img src="/img/cartin-popup/ttl_cartin_popup.jpg" alt="以下の商品が買い物かごに入りました。（数量が0の時には入りません）" width="446" height="40" /></div>\
			<div class="item clearfix">\
			<p class="image" id="popupProductImage"></p>\
			<dl class="data">\
			<dt id="popupProductTitle"></dt>\
			<dd>\
			販売価格：<span id="popupProductPrice"></span>円<br />\
			<span id="popupProductDiscountTitle"></span>：<span id="popupProductDiscountPrice"></span>円<br />\
			<span id="popupCampaignMsg"></span>\
			</dd>\
			</dl>\
			<div class="operate">\
			<div class="amount">\
			<p id="popupProductNum"><span>数量：</span>1</p>\
			<div>\
			<a href="javascript:void(0);" id="countUp"><img src="/img/cartin-popup/btn_add.jpg" alt="1つ増やす" width="20" height="14" /></a>\
			<a href="javascript:void(0);" id="countDown"><img src="/img/cartin-popup/btn_reduce.jpg" alt="1つ減らす" width="20" height="14" /></a>\
			</div>\
			</div>\
			<p class="move"><a href="/carts/view/" class="popupToCart"><img src="/img/cartin-popup/btn_move_cart.jpg" alt="買い物かごへ進む" width="154" height="42" /></a></p>\
			</div>\
			<div class="clear"></div>\
			</div>\
			<div class="continue">\
			<img src="/img/cartin-popup/img_lion.jpg" alt="引き続きお買い物をお楽しみいただく場合は「お買い物を続ける」をクリックしてください" width="420" height="82" />\
			<a href="javascript:void(0);" class="popupClose"><img src="/img/cartin-popup/btn_continue.jpg" alt="お買物を続ける" width="124" height="30" /></a>\
			</div>\
			</div>';
			}

		$('body').append('<div id="popupCart" class="cartPopup" style="display:none;"></div>');
		$('#popupCart').html(templateCart);


		///////////////////////////////////
		// メッセージ表示ポップアップ
		///////////////////////////////////
		if(cart.action == undefined && shopCode == "0001"){
		var templateMessage =
        '<div class="inner">\
	      <div style="background:#FF7ABD; padding:5px;">\
		    <p id="message" style="color:#fff; font-weight:bold;"></p>\
	      </div>\
	      <div class="continue">\
		    <img src="' + global.baseUrl + 'img/cartin-popup/img_lion_issua.jpg" alt="引き続きお買い物をお楽しみいただく場合は「お買い物を続ける」をクリックしてください" width="420" height="82" />\
		    <a href="javascript:void(0);" class="popupClose"><img src="' + global.baseUrl + 'img/cartin-popup/btn_continue.jpg" alt="お買物を続ける" width="124" height="30" /></a>\
	      </div>\
        </div>';
				} else {
				
		var templateMessage =
			 '<div class="inner">\
			  <div style="background:#f60; padding:5px;">\
			  <p id="message" style="color:#fff; font-weight:bold;"></p>\
			  </div>\
			  <div class="continue">\
			  <img src="/img/cartin-popup/img_lion.jpg" alt="引き続きお買い物をお楽しみいただく場合は「お買い物を続ける」をクリックしてください" width="420" height="82" />\
			  <a href="javascript:void(0);" class="popupClose"><img src="/img/cartin-popup/btn_continue.jpg" alt="お買物を続ける" width="124" height="30" /></a>\
			  </div>\
			  </div>';
			}

		$('body').append('<div id="popupMessage" class="cartPopup" style="display:none;"></div>');
		$('#popupMessage').html(templateMessage);
	},

	/**
	 * clickClosePopupCart
	 *
	 */
	clickClosePopupCart : function() {
		// 買い物を続ける場合、商品数量を更新後、ポップアップ画面を閉じる
		$('.popupClose').live('click',function() {
			var id  = $('#popupProductId').html();
			var num = $('#popupProductNum').html();
			if (id) {
				cart.common.chgPopupCartQty(id, num, false);
			}
			$.unblockUI();
		});
	},

	/**
	 * clickPopupToCart
	 *
	 */
	clickPopupToCart : function() {
		// 買い物かごへ進む
		$('.popupToCart').live('click',function() {
			var id  = $('#popupProductId').html();
			var num = $('#popupProductNum').html();
			cart.common.chgPopupCartQty(id, num, true);
			return false;
		});
	},

	/**
	 * clickCountUp
	 * ポップアップカートの数量加算
	 *
	 */
	clickCountUp : function() {
		// 数量カウントダウン
		$('#countUp').live('click',function() {
			var num = $('#popupProductNum').html();
			num = cart.common.cntProduct(num, true);
			$('#popupProductNum').html(num);
		});
	},

	/**
	 * clickCountDown
	 * ポップアップカートの数量減算
	 *
	 */
	clickCountDown : function() {
		// 数量カウントダウン
		$('#countDown').live('click',function() {
			var num = $('#popupProductNum').html();
			num = cart.common.cntProduct(num, false);
			$('#popupProductNum').html(num);
		});
	},

	/**
	 * chgPopupCartQty
	 *
	 */
	chgPopupCartQty : function (id, qty, toCart) {
		debug(new Date() + ' ** [start] chgPopupCartQty');

		var url = '/carts/chgProductQty/';

		// キャッシュ無効
		$.ajaxSetup({cache: false});

		$.post(
			url,
			{
				'id'  : id,
				'qty' : qty
			},
			function(data, status) {
				if (data != 'success') {
					alert('数量変更に失敗しました');
					return;
				} else {
					// お買い物かごへ
					if (toCart) {
						var url = '/carts/' + cart.shopInfo.prefix + 'view/';
						window.location.pathname = url;
						return;
					}

					// DOMの数量更新
					cart.products[id].qty = qty;

					// レンダリング
					cart.common.renderCart();
					return;
				}
			},
			"text"
		);
	},

	/**
	 * createDeliveryToProducts
	 * 商品毎のお届け先情報から、cart.delivery_to_productsを再生成
	 *
	 */
	createDeliveryToProducts : function () {
		debug(new Date() + ' ** [start] cart.common.createDeliveryToProducts');

		/**
		 * 単独配送
		 */
		if (cart.action === 'address_and_payment') {
			var select_address = cart.select_delivery_to;
			cart.delivery_to_products = {};
			cart.delivery_to_products[select_address] = {};
			$.each(cart.products, function(i, product) {
				// お届け先別商品情報DOMの更新
				cart.delivery_to_products[select_address][product.id] = product.qty;
			});
		}

		/**
		 * 複数配送
		 */
		if (cart.action === 'multi_address_and_payment') {
			cart.delivery_to_products = {};
			// PC版はtr、スマホ版はdiv.item
			$('#products').find('tr,div.item').each(function(){
				var select_address = $(this).find('.product_select_address').attr('value');
				var key = $(this).attr('id').replace('row_product_', '');
				var split_product_id = key.split('_');
				var product_id = split_product_id[0];
				var qty = eval($(this).find('.qty').text());

				// お届け先のDOMが存在しなければ初期値セット
				if (cart.delivery_to_products[select_address] == undefined) {
					cart.delivery_to_products[select_address] = {};
				}

				// 既にDOMにセットされていれば数量加算
				if (cart.delivery_to_products[select_address][product_id] != undefined) {
					qty = cart.delivery_to_products[select_address][product_id] + qty;
				}

				// お届け先別商品情報DOMの更新
				cart.delivery_to_products[select_address][product_id] = qty;

				// お届け先キー毎の選択値
				cart.delivery_to_selected[key] = select_address;
			});
		}
	},

	/**
	 * createRecommendProduct
	 * レコメンド商品の追加
	 *
	 */
	createRecommendProduct : function(uniq_name) {
		var recObj = {};
		var recID  = null;
		var recProduct = {};
		var recRemovedObj = {};

		uniq_name = $.trim(uniq_name);
		$.each(cart.products, function(i, product) {
			if (product.uniq_name == uniq_name) {
				recProduct = product;
				recID    = product.id;
			}
		});

		/*********************************************
		 * 数量が1個以上の場合は、数量加算。1個の場合は商品追加
		 *********************************************/
		if (recProduct.qty > 1) {
			/**
			 * 数量加算
			 */
			recObj = $('#cart_item_' + recID);
			recObj.find('.product_qty').val(recProduct.qty);
		} else {
			/**
			 * 商品追加
			 */
			// 一つ目の商品情報からクローンの生成
			recObj = $('#productsTbody tr:last-child').clone(true);
			var cloneID = recObj.attr('id').replace('cart_item_', '');
			recObj.attr('id', 'cart_item_' + recID);
			// 商品画像
			recObj.find('.itemForm-photo').attr('src', '/' + recProduct.thumbnail);
			// 商品名
			var qtyName = recObj.find('.product_qty').attr('name').replace('[' + cloneID + ']', '[' + recID + ']');
			recObj.find('.productName').text(recProduct.name);
			// 数量
			recObj.find('.product_qty').attr('id', 'product_qty_' + recID);
			recObj.find('.product_qty').attr('name', qtyName).val(1);
			// 価格表示
			recObj.find('.tankaInc').text(commaNumber(recProduct.price_t));
			recObj.find('.memTankaInc').text(commaNumber(recProduct.price_m));
			// 商品テーブル最下部に追加
			$('#productsTbody').append(recObj);

			/**
			 * 削除から戻す商品情報追加
			 */
			recRemovedObj = $('#removeProduct div.cart-back-item:last-child').clone(true);
			recRemovedObj.attr('id', 'remove_item_' + recID).hide();
			// 商品画像・商品名・単価
			recRemovedObj.find('.itemForm-photo').attr('src', '/' + recProduct.thumbnail);
			recRemovedObj.find('.productName').text(recProduct.name);
			recRemovedObj.find('.tankaInc').text(commaNumber(recProduct.price_t));
			$('#removeProduct').append(recRemovedObj);
		}

		/**
		 * 小計表示
		 */
		var price = (cart.params.is_member) ? recProduct.price_m : recProduct.price_t;
		recObj.find('.unit_price_total').text(commaNumber(price * recProduct.qty));

		/**
		 * 合計金額の再計算
		 */
		cart.common.renderCart();
	},

	/**
	 * chgGift
	 * お買い物かごでのギフト指定変更
	 *
	 */
	chgGift : function() {
		$('.chgGift').click(function(){
			var productID = $(this).closest('tr').attr('id').replace('cart_item_', '');
			var uniqName  = cart.products[productID].uniq_name;
			var jObj = $('#cart_item_' + productID);

			var url = '/carts/chgGift/' + uniqName + '/';

			// キャッシュ無効
			$.ajaxSetup({cache: false});

			$.getJSON(
				url,
				null,
				function (json, status) {
					if (json.status === 'success') {
						if (jObj.find('.chgGift').prop('checked')) {
							jObj.find('.iconGift').fadeIn();
							jObj.find('.iconObi').fadeIn();
						} else {
							jObj.find('.iconGift').fadeOut();
							jObj.find('.iconObi').fadeOut();
						}
						
						if (json.isGift) {
							$('.progressBar-cart').hide();
							$('.progressBar-gift').show();
						} else {
							$('.progressBar-cart').show();
							$('.progressBar-gift').hide();
						}
					}
				}
			);
		});
	},

	/**
	 * renderTotalPrice
	 * トライアルカート用合計金額計算用メソッド
	 * 
	 * LPのお客様情報入力画面と確認画面で使用。
	 * 「全てトライアル商品なので配送費用がかからない」ことを前提としており、
	 * 単純に各商品の合計金額しか計算しない。
	 * 万一、一般商品をカートインさせると正しくない金額を表示するため、
	 * 一般商品をカートインさせる場合は作り直すこと。
	 */
	renderTrialTotalPrice : function() {
		debug(new Date() + ' ** [start] cart.common.renderTrialTotalPrice');

		var totalPrice = 0;

		// 合計金額計算
		$.each($('.trialProductPrice'), function() {
			totalPrice += parseInt($.trim($(this).text()).replace(',', ''));
		});
		//合計金額をnumber_formatして出力
		$('.trialTotalPrice').text(totalPrice.toString().replace( /([0-9]+?)(?=(?:[0-9]{3})+$)/g , '$1,' ));
	}

}

