/*
	URLルール
	key : type		value : service or product
	key : bc		value : patent or rd
	key : mc		setting.js　参照の事
	key : view		setting.js　参照の事
	
	GETパラメータの値が「.」を含んでいても吸収している
*/

/* GLOBAL 変数 */
var bc		= 'patent';
var type	= 'service';
var mc		= 'Patent';
var view	= null;
//var mdomain = 'http://www.patent-office.jp/';
//var mdomain = 'http://develop.patent-office.jp:8080/';
//var mdomain = 'http://192.168.11.51:8088/'
//var mdomain = 'http://astamuse.com/';
var mdomain='http://www.patent-office.jp/';

/* パラメーター取得 */
para = getPathParam();
if(para.bc != '' && para.bc != null) bc = para.bc.replace(/\./g, "_");
if(para.type != '' && para.type != null ) type = para.type.replace(/\./g, "_");
if(para.mc != '' && para.mc != null ) mc = para.mc.replace(/\./g, "_");
if(para.view != '' && para.view != null ) view = para.view.replace(/\./g, "_");

// alert(bc + " + " + type + " + " + mc + " + " + view);

/* adItemList に付与されているID内の"."を"_"に変更 */
this.replaceIdDot = function(){
	$(".adItemList").each(function(){
		var tarId = $(this).attr("id");
		tarId = tarId.replace(/\./g, "_");
		$(this).attr("id", tarId);
	});
	
	/* Liftによって付与された画像パスのノイズを除去 */
	$(".adItemList img").each(function(){
		var imgsrc = $(this).attr("src");
		imgsrc = imgsrc.replace(/;.*/, "");
		$(this).attr("src", imgsrc);
	});
};


/* ページのデフォルト設定 fix */
this.setDefaultView = function(){
	typeChange(type);
	bigCatChange(bc);
	modMiddleCat(type, bc);
	
	var obj = $("#middleCategory a[name=" + mc + "]");
	if(obj.length != 0){ // 中項目が整合性をもって存在している場合

		setTimeout(function(){
			obj.attr("class", "selected");
			showCategoryList(type, bc, mc);
			if(view == '' || view == null || typeof view == 'undefined'){ // 詳細カテゴリーが指定されていない場合
				mobj =  eval("catTree." + type + "." + bc + "." + mc);
				if(hasChildObj(mobj)){
					var children = createChildArray(mobj);
				}else{
					children = mc;
				}
				setTargetCategory(children);
			}else{
				obj = $("#categoryListTable a[name=" + view + "]");
				if(obj.length != 0){ // パラメーター指定の詳細カテゴリーが整合性をもって存在している場合
					$("#categoryListTable a").removeAttr("class");
					obj.attr("class", "selected");
					setTargetCategory(view);
				}else{
					setTargetCategory(mc)
				}
			}
		},1000);
	}else{
		str = "<tr><td><p>中カテゴリーをご選択下さい</p></td></tr>";
		$("#categoryListTable tr").remove();
		$("#categoryListTable").append(str);
	}
};


/* 商材タイプの選択のリンクにリッスン fix */
this.setSelectType = function(type){
	$("#categorySelect li a").click(function(){
		type = $(this).attr("name");
		typeChange(type);
		modMiddleCat(type, bc);
	});
};

/* 中カテゴリーのリンクにリッスン fix */
this.setClickMC = function(){
	$("#middleCategory a").click(function(){
		var cnt = 0;
		$("#middleCategory a").removeAttr("class");
		$(this).attr("class", "selected");
		type = $("#categorySelect a[class='tabSelected']").attr("name");
		mc = $(this).attr("name");
		showCategoryList(type, bc, mc);
		obj =  eval("catTree." + type + "." + bc + "." + mc);
		flag = hasChildObj(obj);
		if(!flag){
			showTargetCategory(mc);
		}else{
			var ar = createChildArray(obj);
			showTargetCategory(ar);
		}
	});
}

/* 詳細カテゴリ一のリンクにリッスン fix */
this.setViewCategory = function(){
	$("#categoryListTable a").click(function(){
		$("#categoryListTable a").removeAttr("class");
		$(this).attr("class", "selected");
		tarId = $(this).attr("name");
		showTargetCategory(tarId);
	});
};


/* 「もっと詳細を見る」にリッスン fix */
this.setViewMore = function(tarCat){
	$(".switch", "#" + tarCat).click(function(){
		$("#mainCol, #subCol").removeAttr("style");
		pobj = $(this).parents(".adItem");
		$(".append", pobj).toggle("slow", function(){
			equalHeight($(".applyHeight"));
		});
		if($(this).html().match(/openDetailBtn/)){
			$(this).html("<img src='/request_information/img_cmn/closeDetailBtn.gif' />");
		}else{
			$(this).html("<img src='/request_information/img_cmn/openDetailBtn.gif' />");
		};
	});
};


/* 資料請求チェックボックスにリッスン */
this.documentRequest = function(tarCat){
	$(".documentCheck, .mailCheck, .telCheck, .salesCheck", "#" + tarCat).click(function(){
		pobj = $(this).parents(".adItem");
		uniq = $(this).attr("value");
		uniq = uniq.replace(/\./g, "_");
		id = $(this).attr("class") + "";
		id = id.replace(/Check/, "") + "RequestStock";

		if(this.checked){
			itemName = $("h3", pobj).text();
			$("table" , "#" + id).append(
				$("<tr />").append(
					$("<td />").text(itemName).attr("id", uniq)
				)
			);
		}else{
			$("#" + id + " tr:has(td[id='" + uniq + "'])").remove();
		}
	});
};


/* 確定ボタンにリッスン（チェックされているボタンをcookieに保存） */
this.setSubmitClick = function(){
	$("input[type='submit']").click(function(){
		/* cookieに残存しているchckをinput hiddenで出力 */
		if(document.cookie && document.cookie != ''){
			var cookies = document.cookie.split(';');
			for( var i = 0; i < cookies.length; i++ ){
				var cookie = $.trim(cookies[i]);
				if (rex = cookie.match(/(chck[0-9]*)=(.*)/)){
					rex1 = rex[1];
					rex2 = rex[2];
					$.cookie(rex1, null);
					$("body").append($("<input />").attr("value", rex2).attr("type", "checkbox").attr("class", "hiddenCheck").attr("checked",true));
				}
			}
		}
		
		$(".documentCheck, .mailCheck, .telCheck, .salesCheck, .hiddenCheck").each(function(i){
			if($(this)[0].checked){
				name = $(this).attr("value");
				$.cookie("chck" + i, name);
			}
		});
	});
};




/* 商材タブの表示切り替え */
this.typeChange = function(type){
	$("#categorySelect li a[name != '" + type + "']").removeAttr("class");
	$("#categorySelect li a[name = '" + type + "']").attr("class", "tabSelected");
	$("#categoryListTable tr").remove();
	var str = "<tr><td><p>中カテゴリーをご選択下さい</p></td></tr>";
	$("#categoryListTable").append(str);

};

/* メインライティングの切り替え */
this.bigCatChange = function(bc){
	var imgName = bc.substr(0,1).toUpperCase() + bc.substr(1, bc.length);
	$("#mainPic img").attr("src", "/request-information/img_cmn/mainPic" + imgName + ".png");
};


/* 中カテゴリーの書き出し */
this.modMiddleCat = function(type, bc){
	var str = "";
	var obj = eval("catTree." + type + "." + bc);
	$("#mainCol, #subCol").removeAttr("style");
	str = createTableList(obj);
	$("#middleCategory tr").remove();
	$("#middleCategory").append(str);
	equalHeight($(".applyHeight"));
	setClickMC();
};

/* 詳細カテゴリーの書き出し */
this.showCategoryList = function(type, bc, mc){
	var cnt = 0;
	var str = "";
	var obj = eval("catTree." + type + "." + bc + "." + mc);
	if(typeof obj != 'undefined' ){
		str = createTableList(obj);
	}else{
		str += "<tr><td><p>表示するカテゴリーはありません</p></td></tr>";
	}
	
	$("#mainCol, #subCol").removeAttr("style");
	$("#categoryListTable tr").remove();
	$("#categoryListTable").append(str);
	equalHeight($(".applyHeight"));
	$("#middleCategory a[name='" + mc + "']").attr("class", "selected");
	setViewCategory();
};

/* cookieをもとにチェックボックスをチェック */
this.checkCookieForCheckbox = function(){
	if(document.cookie && document.cookie != ''){
		var cookies = document.cookie.split(';');
		for( var i = 0; i < cookies.length; i++ ){
			var cookie = $.trim(cookies[i]);
			if (arr = cookie.match(/(chck[0-9]*)=(.*)/)){
				tkey = arr[1];
				tval = arr[2] + "";
				
				obj = $("input[value=" + tval + "]");
				if(obj.length){
					$.cookie(tkey, null);
					obj.attr("checked", true);
				}
				
//				/* h3からタイトルを抜き出す処理 */
//				var id;
//				tarName = tval.replace(/\.[0-9]*$/, '');
//				tarMethod = tval.replace(/^[0-9]*\.[0-9]*\./, '');
//				itemName = $("#saveField a[name='" + tarName + "']").html();
//				switch(eval(tarMethod)){
//					case 1:
//						id = "documentRequestStock";
//						break;
//					case 2:
//						id = "mailRequestStock";
//						break;
//					case 3:
//						id = "telRequestStock";
//						break;
//				}
//				
//				if(!$("table #" + tval.replace(/\./g, "_"), "#" + id).length){
//					$("table" , "#" + id).append(
//						$("<tr />").append(
//							$("<td />").attr("id", tval.replace(/\./g, "_")).text(itemName)
//						)
//					);
//				}
			}
		}
	}
};

/* 初期表示のカテゴリに対して各種イベントをリッスンさせる */
this.setTargetCategory = function(tarCat){
	if(IsArray(tarCat)){
		for(i = 0; i < tarCat.length; i++ ){
			var obj = $("#" + tarCat[i]);
			listen(tarCat[i]);
			$("#categorySelect a[name='" + tarCat[i] + "']").attr("class", "selected");
		}
	}else{
		var obj = $("#" + tarCat);
		listen(tarCat);
		$("#categorySelect a[name='" + tarCat + "']").attr("class", "selected");
	}

	function listen(cat){
		modImgSpace(cat);
		setViewMore(cat);
		documentRequest(cat);
		checkCookieForCheckbox();
		$("#" + cat).css("display", "block");
	}
}

/* 特定のカテゴリーのみ表示させる 引数はarrayかstr */
this.showTargetCategory = function(tarCat){
	$("#mainCol, #subCol").removeAttr("style");
	$(".adItemList").css("display", "none");
	/* 以下の処理は煩雑な組み方ではあるがブラウザの処理を考慮しての処理順序 */
	ids = "";
	
	if(IsArray(tarCat)){
		for(i = 0; i < tarCat.length; i++ ){
			var obj = $("#" + tarCat[i]);
			if(obj.length == 0){
				exeAjax(tarCat[i]);
			}else{
				obj.css("display", "block");
			}
			
			$("#categorySelect a[name='" + tarCat[i] + "']").attr("class", "selected");
		}
		
		
	}else{
		var obj = $("#" + tarCat);
		if(obj.length == 0){
			exeAjax(tarCat);
		}else{
			obj.css("display", "block");
		}
		
		$("#categorySelect a[name='" + tarCat + "']").attr("class", "selected");
		
	}
	
	var cnt = 0;
//	var si = setInterval(show(tarCat),300);
//	clearInterval(si);

	function exeAjax(cat){
		var stflag = false;
		obj = $("#" + cat);
		cat = cat.replace(/_/g, ".");
		$.ajax({
			type: "GET",
			url: mdomain + "/campaign/campaign/createTag.html",
			dataType: "html",
			data : {
				"field" : cat
				},
			success: function(str){
				cat = cat.replace(/\./g, "_");
				str = str.replace(/^<\?.*\?>\n<.*dtd.*>\n<xml:group>/, '');
				str = str.replace(/<\/xml:group>/, '');
				str = str.replace(/<div id="(.*)" class="adItemList">/, "<div id='" + cat + "' class='adItemList'>");
				
				$("#categorySelect").after(str);
				setTimeout(function(){
					modImgSpace(cat);
					setViewMore(cat);
					documentRequest(cat);
					checkCookieForCheckbox();
					$("#" + cat).css("display", "block");
				}, 1000);
			},
			error : function(){
				if($(".adItemList:visible").length == 0){
					str = "<div class='adItemList' id='none' style='display:block;'><p>現在このカテゴリー商品は準備中です</p></div>";
					$("#categorySelect").after(str);
				}
			}
			
		});
		
	}

	function domReady(tarCat){
		var flag = false;
		var cnt = 0;
		if(IsArray(tarCat)){
			for( i = 0 ; i < tarCat.length; i++){
				var obj = $("#" + tarCat[i]);
				if(obj.length != 0) cnt ++;
			}
			if(cnt == tarCat.length){
				flag = true;
			}else{
				flag = false;
			}
		}else{
			var obj = $("#" + tarCat);
			if(obj.length == 0){
				flag = true;
			}else{
				flag = false;
			}
		}
		return flag;
	}
	
	
	function show(tarCat){
		flag = domReady(tarCat);
		cnt++
		$("#adLoading").html(cnt);
		if(flag){
		//	$("#adLoading").remove();
			if(IsArray(tarCat)){
				for(i = 0; i < tarCat.length; i++ ){
					var obj = $("#" + tarCat[i]);
					obj.css("display", "block");
				}

			}else{
				var obj = $("#" + tarCat);
				obj.css("display", "block");

			}
		}
	}
	
};

/* ページ呼び出しの際に商材のタイトル一覧を取得します */
this.getItemTitleData = function(){
	$.ajax({
		type : "GET",
		url: mdomain + "campaign/campaign/createTitles?marketingMediationInterest=all",
		dataType : "html",
		success : function(str){
				str = str.replace(/^<\?.*\?>\n<.*dtd.*>\n<xml:group>/, '');
				str = str.replace(/<\/xml:group>/, '');
				$("#saveField").append(str);
		}
	});
}



/* メイン画像がある時にレイアウトを調整する fix */
this.modImgSpace = function(tarCat){
	setTimeout(function(){
		$(".adItem:has(img.mainImage)", "#" + tarCat).each(function(){
			$(".imgcol", this).css({ "width": 180, "display": "block" });
			$(".catch, .viewmore", this).css("margin-left", 200);
		});
	}, 200);
};

/* 画像リサイズ処理 調整後のサイズを配列で返します fix */
function resize(imgObj, defWidth, defHeight){
	imgWidth = imgObj.width();
	imgHeight = imgObj.height();
	if( imgWidth > imgHeight ){
		keisuu = ( imgWidth > defWidth ) ? defWidth / imgWidth : 1;
		rWidth = parseInt(imgWidth * keisuu);
		rHeight = parseInt(imgHeight * keisuu);
		if(rHeight > defHeight){
			rKeisuu = defHeight / rHeight;
			rHeight = rHeight * rKeisuu;
			rWidth = rWidth * rKeisuu;
		}
	}else{
		keisuu = ( imgHeight > defHeight ) ? defHeight / imgHeight : 1;
		rWidth = parseInt(imgWidth * keisuu);
		rHeight = parseInt(imgHeight * keisuu);
	}
	imgObj.css({ "width": rWidth, "height":rHeight});
	sizearray = new Array(rWidth, rHeight);
	return sizearray;
}


/* GETパラメータを解析 オブジェクトで返します fix
	2009/10/13　URL仕様変更のため現在使っていません */
function getParam(){
	var params = {};
	var url = document.URL;
	var str = url.match(/\?.*/) + "";
	str = str.replace(/\?/, '');
	paras = str.split("&");
	for(var i = 0; i < paras.length; i++ ){
		row = paras[i].split("=");
		if(row[0]){
			key = row[0];
			params[key] = row[1];
		}
	}
	return params;
}



/* パスパラメータを解析 オブジェクトで返します fix */
function getPathParam(){
	var params = {};
	var keys = [ "type", "bc", "mc", "view" ];
	var url = document.URL;
	var str = url.match(/\/list\/.*/) + "";
	str = str.replace(/\/list\//, '');
	paras = str.split("/");
	for(var i = 0; i < paras.length; i++ ){
		var v = paras[i];
		if(v != '' && v != null && v != 'null'){
			if(v.indexOf("html", 0) == -1){
				k = keys[i];
				params[k] = v;
			}
		}
	}
	return params;
}



/* ３カラムのテーブルリストの中身を表示 */
function createTableList(obj){
	var cnt = 0;
	var str = '';
	for(var key in obj){
		cnt ++;
		if(cnt % 3 == 1) str += "<tr>";
		str += "<td><a href='javascript:void(0);' name='" + key + "'>" + labelArray[key] + "</a></td>";
		if(cnt % 3 == 0 ) str += "</tr>\n";
	}
	
	if(cnt != 0){
		blank = 3 - ( cnt % 3 );
		if(blank != 0 && blank != 3){
			for( var i = 0; i < blank; i++ ){
				str += "<td></td>";
			}
			str +="</tr>";
		}
	}else{
		str = "<tr><td><p>表示するカテゴリーはありません</p></td></tr>";
	}
	return str;
}


/* 右カラムと左カラムを揃える fix */
function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
};

/* 対象が配列かどうか */
function IsArray(array){
  return !(
    !array || 
    (!array.length || array.length == 0) || 
    typeof array !== 'object' || 
    !array.constructor || 
    array.nodeType || 
    array.item 
  );
}


/* オブジェクトが子オブジェクトを持っているか判定　持っていたらtrue fix */
function hasChildObj(obj){
	var cnt = 0;
	for(var i in obj){
		cnt++;
	}
	
	
	if(cnt){
		return true;
	}else{
		return false;
	}
}

/* オブジェクトの子要素の名前を配列にして返す */
function createChildArray(obj){
	var ar = new Array();
	for(var i in obj){
		ar.push(i);
	}
	return ar;
}

/* オブジェクトを再帰的に走査 → 使ってない*/
function traceRoot(obj, str, parentKey){
	var pobj;
	if(obj){
		for( var i in obj ){
			if( i != '' || i != null || typeof i != 'undefined' ){
				if( i == str){
					pobj = parentKey + "." + i;
					return pobj.slice(1, pobj.length);
				}else{
					if(s = elmSearch(obj[i], str, parentKey + "." + i)){
						return s;
						break;
					}
				}
			}
		}
	}
}

/* 大項目カテゴリーのセレクトボックスにリッスン fix 仕様変更により不要に。
this.setSelectBC = function(){
	$("#bigCategory").change(function(){
		type = $("#categorySelect a[class='tabSelected']").attr("name");
		bc = $(this).val();
		modMiddleCat(type, bc);
		$("#categoryListTable tr").remove();
		$("#categoryListTable").append($("<tr><td><p>中カテゴリーを選択してください</p></td></tr>"));
	});
};
*/

/* メイン画像の表示処理 fix → 現在使用していない
this.mainImageResize = function(){
	$(".imgcol img").each(function(){
		defSize = 120;
		resize($(this), defSize, defSize);
	});
};
*/

/* 各種リッスン */
$(document).ready(function(){
	setSubmitClick();
	setSelectType();
	setDefaultView();
	getItemTitleData();
	$('#requestStock').scrollFollow({ "speed": 2500, "delay" : 200, "easing":"easeOutBack" });
	$("#itemTypeSelect").corner("3px");
	$(".requestLink").corner("3px");
});
