var Cart;
var ErrorWindow;

$(function(){

/** ヘルプのリンク先 */
var _helpURL = "/quality/basic_information/how_to.html";
/** バランスチェックのリンク先. */
var _checkURL = "/quality/basic_information/check.php";

var _dictionary = {
	"サンドイッチ" : {
		"レギュラーメニュー販売時間帯":"#item-list-0-0",
		"ブレックファストメニュー販売時間帯":"#item-list-0-1",
		"ソース・シロップ・その他":"#item-list-0-2"
	},
	"サイドメニュー" : {
		"レギュラーメニュー販売時間帯":"#item-list-1-0",
		"ブレックファストメニュー販売時間帯":"#item-list-1-1",
		"ソース・シロップ・その他":"#item-list-1-2"
	},
	"ドリンクメニュー" : {
		"コールド":"#item-list-2-0",
		"ホット":"#item-list-2-1",
		"シェイク":"#item-list-2-2",
		"オプション":"#item-list-2-3"
	}
}

Cart = function(){
	// private member -------------------------------------------------
	var _imagePath = "/shared/graphic/cart/";
	var _apiURL = "/quality/basic_information/api/loadPulldownMenuJSON.php";
	/** 開いているか. */
	var _isOpen;
	/** 初期化が完了しているか. */
	var _initialized = false;
	/** 現在登録されているアイテムを格納する配列. */
	var _list = [];
	/** IDをキーにアイテム名や画像パスを取得するための辞書. */
	var _itemDictionary = {};
	/** カートに保持できる最大商品数. */
	var _max  = 5;
	/** 栄養バランスチェックのDOMエレメント. */
	var _element = $([
		"<div id='cart-content' style='width:100%; z-index:9;'>",
			"<div id='cart-balance-check'>",
				"<div class='body'>",
					"<a href='javascript:void(0);' id='cart-open-button'>",
						"<img id='cart-open-button-open' src='",_imagePath,"button_open_01.gif' alt='栄養バランスチェック' width='130' height='23' class='hover'>",
						"<img id='cart-open-button-close' src='",_imagePath,"button_close_01.gif' alt='栄養バランスチェック' width='130' height='23' class='hover'>",
					"</a>",
				"</div>",
			"</div>",
			"<div id='cart-title-closed'/>",
			"<div id='_cart_content'>",
				"<div id='cart-title'>",
					"<div class='body'><img src='",_imagePath,"title_01.gif' alt='栄養バランスチェック' width='157' height='20'>",
						"<div class='question'>",
							"<a href='",_helpURL,"' target='_blank'>",
								"<img src='",_imagePath,"image_fukidashi_01.gif' alt='？' width='47' height='51' class='hover'>",
							"</a>",
						"</div>",
					"</div>",
				"</div>",
				"<div id='cart-item-list'>",
					"<div id='cart-item-list-container' style='_margin:0px; _padding:0px;'>",
						"<div class='body'>",
							"<div id='cart-tab-container' class='tab'>",
								"<div class='menu-tab' id='cart-menu-tab-top'>",
									"<ul>",
										"<li><a href='#cart-menu-tab-content-1'><img class='tab-hover' src='",_imagePath,"button_tab_01_selected.gif' width='240' height='26' alt='サンドイッチ'></a></li>",
										"<li><a href='#cart-menu-tab-content-2'><img class='tab-hover' src='",_imagePath,"button_tab_02.gif' width='240' height='26' alt='サイドメニュー'></a></li>",
										"<li class='end'><a href='#cart-menu-tab-content-3'><img class='tab-hover' src='",_imagePath,"button_tab_03.gif' width='240' height='26' alt='ドリンクメニュー'></a></li>",
									"</ul>",
								"<div>",
							"</div>",
						"</div>",
						"<div class='menu-tab-content' id='cart-menu-tab-content-1'>",
							"<dl>",
								"<dt><img src='",_imagePath,"text_item-list_01.gif' alt='レギュラーメニュー販売時間帯' width='138' height='10'></dt>",
								"<dd><select id='item-list-0-0' class='list-pulldown'/></dd>",
							"</dl>",
							"<dl>",
								"<dt><img src='",_imagePath,"text_item-list_02.gif' alt='朝マックメニュー販売時間帯' width='162' height='10'></dt>",
								"<dd><select id='item-list-0-1' class='list-pulldown'/></dd>",
							"</dl>",
							"<dl class='end'>",
								"<dt><img src='",_imagePath,"text_item-list_03.gif' alt='ソース・シロップ・その他' width='110' height='10'></dt>",
								"<dd><select id='item-list-0-2' class='list-pulldown'/></dd>",
							"</dl>",
						"</div>",
						"<div class='menu-tab-content' id='cart-menu-tab-content-2' style='display:none'>",
							"<dl>",
								"<dt><img src='",_imagePath,"text_item-list_01.gif' alt='レギュラーメニュー販売時間帯' width='138' height='10'></dt>",
								"<dd><select id='item-list-1-0' class='list-pulldown'/></dd>",
							"</dl>",
							"<dl>",
								"<dt><img src='",_imagePath,"text_item-list_02.gif' alt='朝マックメニュー販売時間帯' width='162' height='10'></dt>",
								"<dd><select id='item-list-1-1' class='list-pulldown'/></dd>",
							"</dl>",
							"<dl class='end'>",
								"<dt><img src='",_imagePath,"text_item-list_03.gif' alt='ソース・シロップ・その他' width='110' height='10'></dt>",
								"<dd><select id='item-list-1-2' class='list-pulldown'/></dd>",
							"</dl>",
						"</div>",
						"<div class='menu-tab-content' id='cart-menu-tab-content-3' style='display:none'>",
							"<dl>",
								"<dt><img src='",_imagePath,"text_item-list_04.gif' alt='コールド' width='38' height='10'></dt>",
								"<dd><select id='item-list-2-0' class='list-pulldown'/></dd>",
							"</dl>",
							"<dl>",
								"<dt><img src='",_imagePath,"text_item-list_05.gif' alt='ホット' width='27' height='10'></dt>",
								"<dd><select id='item-list-2-1' class='list-pulldown'/></dd>",
							"</dl>",
							"<dl>",
								"<dt><img src='",_imagePath,"text_item-list_06.gif' alt='シェイク' width='36' height='10'></dt>",
								"<dd><select id='item-list-2-2' class='list-pulldown'/></dd>",
							"</dl>",
							"<dl class='end'>",
								"<dt><img src='",_imagePath,"text_item-list_03.gif' alt='ソース・シロップ・その他' width='110' height='10'></dt>",
								"<dd><select id='item-list-2-3' class='list-pulldown'/></dd>",
							"</dl>",
						"</div>",
						"<div class='menu-tab' id='cart-menu-tab-bottom'><img src='",_imagePath,"background_tab_03.gif' alt='' width='732' height='12'></div>",
					"</div>",
							"<div class='fukidashi'>",
								"<img src='",_imagePath,"image_fukidashi_02.gif' alt='調べたい商品をリストから選ぶだけ！' width='164' height='50'>",
							"</div>",
						"</div>",
					"</div>",
				"</div>",
				"<div id='cart-selected-item'>",
					"<div class='body'>",
						"<div class='item-set'>",
							(function(){
								var html = "";
								for( var i=0; i < _max; i++ ){
									html += [
										"<div id='cart-item",i,"' class='item-box",((i==_max-1)?"-end":""),"'>",
											"<dl class='item-image'></dl>",
											"<div class='item-close'>",
												"<a href='javascript:Cart.removeItemAt(",i,")'><img src='",_imagePath,"button_close_03.gif' alt='' width='14' height='13' class='hover'></a>",
											"</div>",
										"</div>"
									].join("");
								}
								return html;
							})(),
							"<div class='button-area'>",
								"<ul>",
									"<li id='cart-selector-open-button' class='item-list-close'>",
										"<a href='javascript:void(0);'>",
											"<img id='cart-selector-open-button-open' src='",_imagePath,"button_open_02.gif' alt='' width='130' height='23' class='hover'>",
											"<img id='cart-selector-open-button-close' src='",_imagePath,"button_close_02.gif' alt='' width='130' height='23' class='hover'>",
										"</a>",
									"</li>",
									"<li>",
										"<a href='",_checkURL,"'><img src='",_imagePath,"button_balance_01.gif' alt='' width='81' height='81' class='hover'></a>",
									"</li>",
								"</ul>",
							"</div>",
						"</div>",
					"</div>",
				"</div>",
			"</div>",
		"</div>"
	].join(""));
	
	// private method -------------------------------------------------
	
	/**
	 * 商品カテゴリ変更用のタブを生成するファクトリメソッドです.
	 * @param {Object} data
	 */
	function _createTab( data ){
		var list = data.pulldown_list;
		for( var i = 0; i < list.length; i++ ){
			_createPulldownMenu( $(_dictionary[data.tab_label][list[i].caption],_element), list[i] );
		}
	}
	
	/**
	 * 商品選択用のプルダウンメニューを生成するファクトリメソッドです.
	 * @param {Object} data
	 */
	function _createPulldownMenu( target, data ){
		var html = "<option selected>お選びください</option>";
		for( var i=0; i < data.options.length; i++ ){
			var option = data.options[i];
			html += "<option value='"+option.value+"'>"+option.label+"</option>";
			_itemDictionary[option.value] = option;
		}
		target.html(html);
	}
	
	/**
	 * グローバルメソッドの pulldownMenuJson を設定します.
	 * このメソッドは,initialize実行時のjsonpコールバックとして実行されます.
	 * @param {Object} json
	 */
	window.pulldownMenuJson = function( json ){
		
		// カテゴリのタブと,プルダウンを生成.
		var list = json.category_list;
		for( var i = 0; i < list.length; i++ ){
			_createTab( list[i] );
		}
		
		var keyCtrl = false;
		
		$(".list-pulldown",_element).blur(function(e){
			if (keyCtrl && this.selectedIndex != 0 ) {
				Cart.addItem($(this).val());
				this.selectedIndex = 0;
			}
			keyCtrl = false;
		});
		
		var wheel = function(e){
			keyCtrl = true;
		}
		if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
		window.onmousewheel = document.onmousewheel = wheel;
		
		$(".list-pulldown",_element).keydown(function(e){
			keyCtrl = keyCtrl || ( e.keyCode == 38 || e.keyCode == 40 );
		});
		
		$(".list-pulldown",_element).change(function(e){
			if (keyCtrl || this.selectedIndex == 0 ) return;
			Cart.addItem($(this).val());
			this.selectedIndex = 0;
		});
		
		// cookieにデータが存在する場合復元します.
		if ($.cookie('CartList') && $.cookie('ItemHolderList') != "") {
			_list = $.cookie('CartList').split(",");
		}
		
		// bodyの末尾に追加.
		_element.appendTo($("body")).fixed({　"align" : "center",　"valign" : "bottom",　"updateTrigger" : "resize"　});
		
		$("#cart-item-list-container").hide();
		
		// 開閉処理.
		if( _isOpen ){
			$("#_cart_content").show();
		}else{
			$("#_cart_content").hide();
		}
		
		_update();
		
		_setup();
		
		// 初期化完了の通知.
		_initialized = true;
		$(Cart).trigger("_initialized");
		
		if ($.browser.msie && $.browser.version == "6.0") {
			var timerID;
			$(window).scroll(function(){
				clearTimeout(timerID);
				timerID = setTimeout(function(){
					_displayUpdate();
				},50);
			})
		}
		
		_displayUpdate();
		_element.trigger("resize");
		
	}
	var pulldownMenuJson = window.pulldownMenuJson;
	
	/** カート内の描画を更新します. */
	function _update(){
		
		// 存在しない要素などを消す.
		for( var j = 0; j < _list.length; j++ ){
			if( _list[j] != "" && _itemDictionary[_list[j]] ) continue;
			_list.splice(j--, 1);
		}
		
		// 描画.
		for( var i = 0; i < _max; i++ ){
			if( _list[i] ){
				var data = _itemDictionary[_list[i]];
				$("#cart-item"+i+" > .item-image",_element).html([
					"<dd><a href='",data.link,"'><img src='",data.image,"' alt='",data.label,"' width='120' height='83'></a></dd>",
					"<dt>",data.label,"</dt>"
				].join(""));
			}else{
				$("#cart-item"+i+" > .item-image",_element).html([
					"<dd><a href='javascript:void(0);'><img src='",_imagePath,"image_select.jpg' alt='' width='120' height='83'></a></dd>",
					"<dt>&nbsp;</dt>"
				].join(""));
			}
		}
		
		$.cookie('CartList', _list.toString(), {"path":"/"} );
		
		_displayUpdate();
		
		// 変更した事を通知.
		$(Cart).trigger("_changed");
		
	}
	
	var _displayUpdate = function(){
		if( $("#_cart_content").css("display") == "none" ){
			$("#cart-open-button-open").show();
			$("#cart-open-button-close").hide();
			$("#cart-title-closed").show();
		}else{
			$("#cart-open-button-open").hide();
			$("#cart-open-button-close").show();
			$("#cart-title-closed").hide();
		}
		if( $("#cart-item-list-container").css("display") == "none" ){
			$("#cart-selector-open-button-open").show();
			$("#cart-selector-open-button-close").hide();
		}else{
			$("#cart-selector-open-button-open").hide();
			$("#cart-selector-open-button-close").show();
		}
		$("#cart-content").trigger("resize");
		if ($.browser.msie && $.browser.version == "6.0") {
			var y = _element.offset().top - 38;
			$(".drink").each(function(){
				var t = $(this);
				t.show();
				if( y < t.offset().top ){
					t.hide();
				}else{
					t.show();
				}
			});
		}
	}
	
	/**
	 * タブやその他開閉部の挙動を設定します.
	 */
	function _setup(){
		
		// 開閉挙動の設定.
		$("#cart-open-button",_element).click(function(){
			$("#_cart_content").toggle();
			$("#cart-content").trigger("resize");
			_displayUpdate();
		});
		$("#cart-selector-open-button",_element).click(function(){
			$("#cart-item-list-container").toggle();
			$("#cart-content").trigger("resize");
			_displayUpdate();
		});
		
		// RollOver.
		$ ("img.hover",_element).each (function () {
			var source = $ (this).css ("filter").indexOf ("progid") != -1 ? $ (this).css ("filter").split ("\"")[1] : this.src;
			$ ("<img>").attr ("src", source.replace (/\.([^.]+)$/, "_hover." + "$1")).appendTo ("body").hide ();
		});
		$ ("a:has(img.hover)",_element).hover (
			function () {
				$ ("img.hover", this).each (function () {
					var source = $ (this).css ("filter").indexOf ("progid") != -1 ? $ (this).css ("filter").split ("\"")[1] : this.src;
					this.src = source.replace (/\.([^.]+)$/, "_hover." + "$1");
				});
			},
			function () {
				$ ("img.hover", this).each (function () {
					var source = $ (this).css ("filter").indexOf ("progid") != -1 ? $ (this).css ("filter").split ("\"")[1] : this.src;
					this.src = source.replace (/_hover\.([^.]+)$/, "." + "$1");
				});
			}
		);
		$ ("input.hover",_element).each (function () {
			$ ("<img>").attr ("src", this.src.replace (/\.([^.]+)$/, "_hover." + "$1")).appendTo ("body").hide ();
			$ (this).hover (function () {
				this.src = this.src.replace (/\.([^.]+)$/, "_hover." + "$1");
			}, function () {
				this.src = this.src.replace (/_hover\.([^.]+)$/, "." + "$1");
			});
		});
		
		// タブの設定.
		if ($.browser.safari && (parseInt ($.browser.version) < 525)) {
			$ ("div#cart-content :last-child").addClass ("last-child");
		}
		$ ("img.tab-hover").each (function () {
			$ ("<img>").attr ("src", this.src.replace (/\.([^.]+)$/, "_hover." + "$1")).appendTo ("body").hide ();
		});
		$ ("div#cart-content div.menu-tab ul li a:has(img.tab-hover)").hover (
			function () {
				$ ("div#cart-content div.menu-tab ul li:nth-child(" + ($ ("div#cart-content div.menu-tab ul li a").index (this) % 3 + 1) + ") a img.tab-hover").each (function () {
					this.src = this.src.replace (/\.([^.]+)$/, "_hover." + "$1");
				});
			}, function () {
				$ ("div#cart-content div.menu-tab ul li:nth-child(" + ($ ("div#cart-content div.menu-tab ul li a").index (this) % 3 + 1) +") a img.tab-hover").each (function () {
					this.src = this.src.replace (/_hover\.([^.]+)$/, "." + "$1");
				});
			}
		);
		$ ("div#cart-content div.menu-tab ul li a").click (function () {
			$ ("div#cart-content div.menu-tab ul li a img").each (function () {
				this.src = this.src.replace (/_selected\.([^.]+)$/, "." + "$1");
				$ (this).addClass ("tab-hover");
				var id = $(this).parent().attr("href");
				id = id.substr( id.indexOf("#") ,id.length);
				$(id).hide();
			});
			var id = this.href.match (/#(.*)/)[1];
			$ ("div#cart-content div.menu-tab ul li a[href*=" + id + "] img").each (function () {
				this.src = this.src.replace (/[_hover]*\.([^.]+)$/, "_selected." + "$1");
				$ (this).removeClass ("tab-hover");
			});
			$ ("div#cart-content div#" + id).show ();
			if (id != "menu-tab-content-1") {
				$ ("div#cart-content div.menu-tab div").addClass ("not-first");
			} else {
				$ ("div#cart-content div.menu-tab div").removeClass ("not-first");
			}
			if ($ (this).parents ("div#menu-tab-bottom").size ()) {
				window.scrollTo (0, $ ("div#cart-content div#cart-menu-tab-top").offset ().top + 4);
			}
			return false;
		});
		
		$ ("div#cart-content div#cart-menu-tab-top ul li:first-child a").click ();
		$ ("div#cart-content div.menu-data p a").click (function () {
			$ ("div#cart-content div#cart-menu-tab-top ul li:first-child a").click ();
		});
		
		$(window).resize(function(){
			setTimeout(function(){
				if ( $.browser.msie && $.browser.version == "6.0" ) {
					$("#cart-balance-check div.body").css("left", 318 );
				}else {
					$("#cart-balance-check div.body").css("left", Math.max(773, ($(window).width() + 640) / 2));
				}
				_element.trigger("resize");
			},1);
		})
		if ( $.browser.msie && $.browser.version == "6.0" ) {
			$("#cart-balance-check div.body").css("left", 318);
		}else {
			$("#cart-balance-check div.body").css("left", Math.max(773, ($(window).width() + 640) / 2));
		}
		
	}

	// public member --------------------------------------------------
	return{
		/**
		 * 初期化処理を行います.
		 * @param	isOpen カートを開いた状態で初期化するか.
		 */
		initialize:function( isOpen ){
			// 既に初期化されている場合は,なにも行いません.
			if( _initialized ) return;
			// カートを開いた状態にしない場合,#cart-contentを隠します.]
			_isOpen = isOpen;
			// カート用情報を取得します.
			$.ajax({
	            "url" : _apiURL,
	            "dataType" : "jsonp"
	        });
		},
		/** 追加されているアイテムのIDのリストを取得します. */
		getItemList : function(){ return _list; },
		/** カートがいっぱいかを調べます. */
		isFull : function(){ return _max <= _list.length; },
		/**
		 * カートにアイテムを追加します.
		 * 既に登録可能数に達していた場合 _full イベントがトリガされます.
		 * @param	id　追加するアイテムのID
		 */
		addItem : function( id ){
			// 存在しないIDを指定した場合 return します.
			if (!_itemDictionary[id]) {
				$(Cart).trigger("_illegal_id");
				return;
			// カートが一杯であった場合は _full イベントをトリガし,終了します.
			}else if( this.isFull() ){
				$(Cart).trigger("_full");
				return;
			}
			// IDのアイテムをカートに追加します.
			_list.push( id );
			_update();
			$("#_cart_content").show();
			$("#cart-content").trigger("resize");
		},
		/**
		 * 指定したIDのアイテムをカートから削除します.
		 * 同じIDのアイテムが複数あった場合は,全て削除されます.
		 * @param	id　削除したいアイテムのID.
		 */
		removeItem : function( id ){
			_list = $.grep( _list, function(n){return(n!=id)} );
			_update();
		},
		/**
		 * 指定したインデックスのアイテムをカートから削除します.
		 * @param	index　削除したいアイテムのインデックス.
		 */
		removeItemAt : function( index ){
			if(!_list[index]) return;
			_list.splice(index,1)
			_update();
		},
		/**
		 * カートをクリアします.
		 */
		clear : function(){
			if( !_list || _list.length == 0 ) return;
			_list = [];
			_update();
		}
	}
}();

ErrorWindow = function(){
	// private member -------------------------------------------------
	/** エラー表示領域. */
	var _container = $("<div/>").fixed();
	/** 画面を覆うシート. */
	var w = $(window);
	var _sheet = $("<div/>").css({
		"position":"absolute",
		"width" : w.width(),
		"height" : w.height(),
		"background" : "#000000",
		"z-index":100
	}).css("opacity",0.5).appendTo(_container);
	w.resize(function(){
		_sheet.css({ "width" : w.width(), "height" : w.height() }); 
	});
	/** エラーウィンドウ. */
	var _error = $([
		"<div id='cart-error-container'>",
			"<div id='cart-error-head'>",
				"<div id='close'>",
					"<a href='javascript:void(0);'>",
						"<img src='/shared/graphic/cart/button_close_ov.gif' alt='閉じる' width='90' height='24'>",
					"</a>",
				"</div>",
			"</div>",
			"<div id='cart-error-content'>",
			"</div>",
		"</div>"
	].join("")).css("z-index",101).appendTo(_container).fixed({"align":"center","valign":"middle"});
	
	$("#close",_error).click(function(){
		_container.hide();
		if ($.browser.msie && $.browser.version == "6.0") {
			$("select").show();
		}
		if ( window.Check !== undefined ) {
			window.Check.show();
		}
	});
	
	function _showError(){
		if ($.browser.msie && $.browser.version == "6.0") {
			$("select").hide();
		}
		if ( window.Check !== undefined ) {
			window.Check.hide();
		}
		setTimeout(function(){
			_container.show();
			$("body").append(_container);
			$(window).trigger("resize");
		},10);
	}
	
	$(Cart).bind("_full",function(){
		$("#cart-error-content",_container).html([
			"<p>栄養バランスチェックカートが一杯です。<br>",
			"追加するには、カートから商品を削除してください。</p>"
		].join(""));
		_showError();
	});
	
	$(Cart).bind("_illegal_id",function(){
		$("#cart-error-content",_container).html([
			"<p>選択された商品が見つかりません。<br>",
			"お手数ですが、「<a href='/cservice/index.html'>お問い合わせ<a/>」ページよりお問い合わせください。</p>"
		].join(""));
		_showError();
	});
	
}();

});