$(function(){
	function GetQueryString()
	{
	    if( 1 < window.location.search.length )
	    {
	        // 最初の1文字 (?記号) を除いた文字列を取得する
	        var query = window.location.search.substring( 1 );

	        // クエリの区切り記号 (&) で文字列を配列に分割する
	        var parameters = query.split( '&' );

	        var result = new Object();
	        for( var i = 0; i < parameters.length; i++ )
	        {
	            // パラメータ名とパラメータ値に分割する
	            var element = parameters[ i ].split( '=' );

	            var paramName = decodeURIComponent( element[ 0 ] );
	            var paramValue = decodeURIComponent( element[ 1 ] );

	            // パラメータ名をキーとして連想配列に追加する
	            result[ paramName ] = decodeURIComponent( paramValue );
	        }

	        return result;
	    }

	    return null;
	}
var qs = GetQueryString();
	
	var items_basepath = "https://boat-time.com/wp-content/editor-templates/js/items/";
	//var items_basepath = "js/items/";
	$.fn.list = function(options) {
		var defaults = {
				div : this,
				title : "メーカーを選んでください",
				name : "maker_name",
				width : 170,
				height : 300,
				default_items : [],
				now_items : [],
				keyword_length : 0,
				target_number : -1,
				children_id : ["div#child_model","div#child_model2","div#child_model3"],
				child_title : "モデルを選択してください",
				child_name : "model",
				child_target_number : 0,
				isOpen:false
			};
		var ops = $.extend({}, defaults, options);
		_init = function(){
			/* init */
			// 二重生成阻止
			if(!ops.open_list){
				// click open div
					$(ops.div).append($("<div id='list_open' class='textbox_style'><select name="+ops.name+" placeholder="+ops.title+"></select></div>"));
	
				// select list div 
				ops.default_items = list_item;
				var flg = document.createDocumentFragment();
						$(flg).append($("<option id='big_load_ttl'>読み込み中...</option>"));
					for(var i=0,l=list_item.length;i<l;i++) {
						$(flg).append($("<option id='item"+i+"' value='"+list_item[i][0]+"'>"+list_item[i][0]+"</option>"));
					};
					$('select[name='+ops.name+']').append(flg);
				
				// children
						ops.child_length = ops.children_id.length;
					for(var i=0,l=ops.child_length;i<l;i++) {
						console.log(ops.children_id[i]);
						$(ops.children_id[i]).append($("<div id='child_list_open"+i+"' class='child_list textbox_style'><select name="+ ops.child_name + i +" placeholder="+ops.child_title+"></select></div>"));
						
						flg = document.createDocumentFragment();
						$(flg).append($("<option>"+ops.child_title+"</option>"));
						$('select[name='+ops.child_name+i+']').append(flg);
					}
					
					list.query();
	
			};
 		};
		_css = function(){
			for(var i=ops.child_length;i--;) {
					$('select[name='+ops.child_name+i+']').css({
						"width" : (ops.width)  + "px"
					});
				}
 		};
		_event = function(){
			/* event */
			var ops_ = ops;
			$('select[name='+ops.name+']').on("change",function(){
				list.selected($(this).children(':selected').attr("id"));
			}); 
		};
		
		list = {
			selected : function(selectID) {
				var ary_key;
				if(selectID){
				
					ary_key = selectID.replace("item","");
					if(ops.default_items[+ary_key][2]){
						list.load(items_basepath + ops.default_items[+ary_key][2] + ".js");
					}
					else{
						child_list.allUpdate([]);
					}
				}else{
					
				}
			},
			load : function(src) {
				var key = (src != "") ? src.replace(items_basepath,"").replace(".js","") : "";
				//if( key == "" ){
					var flg0 = document.createDocumentFragment();
						ops.child_length = ops.children_id.length;
					for(var i=0,l=ops.child_length;i<l;i++) {
						$(flg0).append($("<option>読込中...</option>"));
						$('select[name='+ops.child_name+i+']').html(flg0);
					}
				//}
				if(children_list[key]) {
					list.complete(src);
					return;
				}
				var el = document.createElement('script');
					el.type = 'text/javascript';
					(function(){
						var f = arguments.callee;
						console.log("完了");
						setTimeout(function(){
							console.log("次");
							list.complete(src);console.log("次2");
						}, 1000);
					})();
					var keyf = Math.floor(Math.random() * 10000);
					el.src = src + "?key=" + keyf;
				var scripts = document.getElementsByTagName('script');
					//scripts.onLoad = this.complete(src);
					scripts[scripts.length - 1].parentNode.appendChild(el, scripts);
			},
			complete : function(src){
				console.log(src);
				var key = (src != "") ? src.replace(items_basepath,"").replace(".js","") : "";
				if(!children_list[key]) {
					setTimeout(function(){
							child_list.allUpdate(children_list[key]);
							if(ops.query) {
								child_list.query();
							}
						}, 500);
				} else {
					child_list.allUpdate(children_list[key]);
					if(ops.query) {
						child_list.query();
					}
					ops.child_length = ops.children_id.length;
						for(var i=0,l=ops.child_length;i<l;i++) {
							$(ops.children_id[i]).find("select").children("option:first").attr("selected","selected");
						}
				}
				
			},
			query : function() {
				// クエリがあるとき
				if(qs != null) {
					ops.query = true;
					$("select[name='"+ops.name+"']").val(qs["maker_name"]);
					list.selected($("select[name='"+ops.name+"']").children(':selected').attr("id"));
				}
			}
		};
		// child
		child_list = {
			allUpdate : function(ary) {
				ops.child_keyword_length = 0;
				ops.child_now_items = ary;
				ops.child_default_items = ary;
				var flg = document.createDocumentFragment();
						$(flg).append($("<option>"+ops.child_title+"</option>"));
				if(ary.length != 0) {
					for(var i=0,l=ary.length;i<l;i++) {
						$(flg).append($("<option value='"+ary[i][0]+"'>"+ary[i][0]+"</option>"));
					};
				} else {
					$(flg).append($("<option value=''>該当する項目はありません。</option>"));
				};
				// 
				ops.target_number = 0;
				
				for(var i=ops.child_length;i--;) {
					$('select[name='+ops.child_name+i+']').empty().append($(flg).clone(true));
				}
			},
			query : function() {
				ops.query = false;
				if(qs["model0"] != "" || qs["model0"] == undefined) $('select[name='+ops.child_name+'0]').val(qs["model0"]);
				if(qs["model1"] != "" || qs["model1"] == undefined) $('select[name='+ops.child_name+'1]').val(qs["model1"]);
				if(qs["model2"] != "" || qs["model2"] == undefined) $('select[name='+ops.child_name+'2]').val(qs["model2"]);
				
				
			}
		};
		
		_init();
		_css();
		_event();
	};
	$("div#list_maker").list();
});


$(window).load(function(){
  $("#big_load_ttl").html("メーカーを選んでください");
});
