/* *********************************************
 * GLOBALで使えるjqueryオブジェクト
 * 詳細設定はjreadyの中
 */
var jLeftCol, jTitle, jContents; // @see ready 


function mailAlert(){
	var mdomain			= 'http://astamuse.com/';
	var popupHtmlCreate = "<p>この[contentType]の新しい発明があったときにメールを受信する</p>"
						+ "<form class='innerPopButton'><input type='button' class='yesBtn' value='はい' />"
						+ "<input type='button' class='noBtn' value='いいえ' /></form>";
						
	var popupHtmlDelete = "<p>いま購読しているこの[contentType]の新着発明のお知らせを解除する</p>"
						+ "<form class='innerPopButton'><input type='button' class='yesBtn' value='はい' />"
						+ "<input type='button' class='noBtn' value='いいえ' /></form>";
						
	var popupHtmlResCreate	= "<p>購読の設定を完了いたしました。</p>";
	var popupHtmlResDelete	= "<p>購読を解除いたしました。</p>";
	var popupHtmlError		= "<p>サーバーが混み合っており、設定できませんでした。しばらく時間をおいて再度お試し下さい<p>";
	var popupHtmlLogin		= "<p>会員登録後、本機能をご利用いただけます。<br />"
							+ "<a href='http://astamuse.com/auth/prompt.html'>会員登録</a></p>";
	
	var labels = {
		applicant	: "出願人",
		inventor	: "発明者",
		attorney	: "代理人"
		};
	
	$('#applicantNameCell a, #inventorNameCell a, #attorneyNameCell a').each(function(){
		statusCheck('new_patent_published', $(this));
	});
	
	
	// 出願人等の名前をもとに既に対象のメールアラートを購読していないかの確認
	// createLink()に続く
	function statusCheck(alertType, obj){
		var contentType = obj.parents("td").attr("id").replace("NameCell", "");
		var result;
		var alertId;
		var param = {
					'alert_type'		: alertType,
					'content_type'		: contentType,
					'content_name'		: encodeURL(obj.text())
					}
		$.ajax({
			url			: mdomain + 'mailalert/api/read',
			data		: param,
			dataType	: 'jsonp',
			jsonp		: 'callback',
			success		: function(res){
				var status = res.status;
				if( status == 'success'){
					param.alert_id = res.id;
				}else{
					status = ( res.desc == 'not login' ) ? 'notlogin' : 'error';
				}
				createLink(obj, status, param);
			}
		});
	}
	
	// 出願人等の名前の横にリンクを生成しポップアップをセット
	// @arg1 obj	: リンクを出力する対象となる<a>オブジェクト
	// @arg2 status	: successであれば購読解除のリンクを生成　errorであれば購読のリンクを生成
	// @arg3 data	: ajaxリクエストを投げるときに付与するパラメタ
	
	function createLink(obj, status, data){
		var popobj;
		var type;
		var label	= eval("labels." + data.content_type);
		var icon	= ( status == 'success' ) ? 'icCheck.png' : 'icAuthorMailMsg.gif';
		obj.after(
			$('<a class="mail"> <img src="http://static.astamuse.com/img_cmn/' + icon + '" /> </a>').click(function(){
				if( status != 'notlogin'){
					if(status == 'success'){
						popobj	= $.ampop($(this), popupHtmlDelete.replace("[contentType]", label));
						type	= 'delete';
					}else if( status == 'error'){
						popobj	= $.ampop($(this), popupHtmlCreate.replace("[contentType]", label));
						type	= 'create';
					}
					setPopupButtonAction($(this), popobj, type, data);
				}else{
					$.ampop($(this), popupHtmlLogin);
				}
			})
		);
	}
	
	
	// ポップアップの中身の挙動を定義
	//
	
	function setPopupButtonAction(anchor, popobj, type, data){
		var setting;
		var createSet = {
							type		: 'create',
							url			: mdomain + 'mailalert/api/create',
							resSuccess	: popupHtmlResCreate
						}
		
		var deleteSet = {
							type		: 'delete',
							url			: mdomain + 'mailalert/api/delete',
							resSuccess	: popupHtmlResDelete
						}
						
		var setting = ( type == 'create' ) ? createSet : deleteSet;
		
		$("input[type='button']", popobj).click(function(){
			
			if( $(this).attr("class") == 'yesBtn'){
				$(".innerPopButton", popobj).html('<img src="http://static.astamuse.com/img_cmn/loader.gif" />');
				
				$.ajax({
					url			: setting.url,
					data		: data,
					dataType	: 'jsonp',
					jsonp		: 'callback',
					success		: function(res){
						if(res.status == 'success'){
							$(".innerPopButton", popobj).replaceWith(setting.resSuccess);
							setTimeout(function(){
								popobj.fadeOut(1000, function(){
									var nextObj = anchor.prev();
									popobj.remove();
									anchor.remove();
									statusCheck('new_patent_published', nextObj);
								});
							}, 1000);
						}else{
							$(".innerPopButton", popobj).replaceWith(popupHtmlError);
							setTimeout(function(){
								popobj.fadeOut(1000, function(){
										popobj.remove();
									});
							}, 1000);
						}
					}
				});
			}else{
				popobj.remove();
			}
		});
	}
}


/** 発明者権利者をBase64デコードする関数
	@note Google等のクローラーに発明者や権利者等の情報をインデックスさせない為に、
		プログラム側でBase64エンコードしてHTMLに出力しています。
		それを、JavaScript側でBase64デコードして、表示するべき場所にセットします。
	@see base64.js
	@author PBmikiT
*/
this.authorsName = function(){
	var authorsName;
	if(window["authorsNameStr"] != undefined && authorsNameStr != ''){
		name = Base64.decode(authorsNameStr);
		$('#authorsName').replaceWith(name);
	}
	return false;
};

this.applicantsName = function(){
	var applicantsName;
	if(window["applicantsNameStr"] != undefined && applicantsNameStr != ''){
		name = Base64.decode(applicantsNameStr);
		$('#applicantsName').replaceWith(name);
	}
	
	setTimeout(function(){
		mailAlert();
	},1000);
	return false;
};



/* *********************************************
 * 印刷などのtooltips表示
 */
this.titleFunctionPopup = function(){
	$("#titleFunction .functionLink").each(function(){
		var tarPop = $(this).next("div")
		$(this).mouseover(function(kmouse){
			tooltips(kmouse,tarPop);
			tarPop.fadeIn(150)
		}).mousemove(function(kmouse){
			tooltips(kmouse, tarPop);
		}).mouseout(function(){
			tarPop.css({"display":"none"});
		});
	})
}


/* *********************************************
 * タイトル下の各種詳細表示
 */
function itemMetaSwitch(){
	var set = { 	
					registDateDetail	: { 'toOpen' : "出願日等を見る" , 'toClose' : "出願日等を隠す" },
					patentCatDetail		: { 'toOpen' : "特許分類を見る" , 'toClose' : "特許分類を隠す" },
					licenseDetail		: { 'toOpen' : "実施状況・ライセンス情報を見る", 
											'toClose' : "実施状況・ライセンス情報を隠す" },
					techTreeDetail		: { 'toOpen' : "技術分類を見る", 'toClose' : "技術分類を隠す" }
				};
				
	var def = 'techTreeDetail=toClose,registDateDetail=toOpen,patentCatDetail=toOpen,licenseDetail=toOpen';
	
	// ページを開いたときのクッキー読みだし
	var ck = $.cookie("itemMeta");
	    ck =  (!ck || ck.length < 20) ? def.split(',') : ck.split(',');

	// デフォルトの表示処理
	for(var i = 0; i < ck.length; i++ ){
		var tmp		= ck[i].split('=');
		tmp[1] 		= ( tmp[1] == 'toClose' ) ? 'toOpen' : 'toClose' ;
		$("#" + tmp[0] , jTitle).attr("class", tmp[1]);
		switchDisplay(tmp[0]);
		setClick(tmp[0]);
	}
	
	
	// クリックしたときの処理
	function setClick(tid){
		$("#" + tid, jTitle).click(function(){
			switchDisplay(tid);

			// クッキーの書き換え
			var ckVal = '';
			for( var i in set ){
				ckVal += ',' + i + "=" + $("#" + i).attr("class");
			}
			$.cookie("itemMeta", ckVal.slice(1),  { expires:365, path:'/', domain:'.astamuse.com' });
		});
	}
	
	// 表示の切替え
	function switchDisplay(tid){
		var obj		= $("#" + tid, jTitle);
		var ap		= $("#" + tid + "Appended", jTitle);
		var cl		= ( obj.attr("class") == 'toOpen' ) ? 'toClose' : 'toOpen' ;
		var str		= eval("set." + tid + "." + cl);
		
		if( cl == 'toClose'){
			ap.css("display", "block");
			obj.attr("class", cl).text(str);
		}else{
			ap.css("display", "none");
			obj.attr("class", cl).text(str);
		}
	}
}


/* *******************************************
 * メイン画像の表示処理
 * @see common.js resize()
 */
this.mainImageResize = function(){
	if($("#middle > #mainCol > #mainImage")){
		var parentWidth = $("#mainInner").width();
		var defSize = parentWidth/4;
		sizearray = resize($("#mainImage img", jContents), defSize, defSize);
		$("#mainImage img", jContents).css("display", "block");
		$("#mainImage p", jContents).width(sizearray[0]+20);
		if(sizearray[0] == 0) $(this).remove();
	}
	return false;
};


/* *********************************************
 * 左カラムのメーターの処理
 */
this.infoRestMeter = function(){
	setTimeout(function(){
		$("#userField > .inner > #industrySet > #userPageCounter .restedNum", jLeftCol).each(function(){
			var den = $(".denominator", this).text();
			if( den != 0 ){
			
				var per	= $(".numerator", this).text();
					per	= parseFloat(per);

					per = per / den;
					per = Math.min(per, 1);

					ww	= $(".meterDiv", this).width();
				var imgw = Math.round(ww * per);
					per = Math.ceil( per * 100 );
				$(".per span", this).text(per);
				$(".meterDiv img", this).animate({
					"width":imgw
				},2000,"easeInOutCirc");
			}else{
				$(".per span", this).text('--');
			}
		});
	}, 2000);
}




/* *********************************************
 * ページ中のアノテーションの個数をカウントする処理
 */
this.annoPopup = function(){

	var annoCnt = 0;
	var annoCntFormat = '000';

	$('.annotation dt', jContents).each(function(){
		var strI = annoCnt + 1 + "";
		var padNum = "";
		var cnt = eval(annoCntFormat.length)-eval(strI.length);
		for(var j = 0; j < cnt; j++){ padNum = padNum + "0"; }
		padNum = String(padNum) + String(strI);
		var annoObjHtml = $("#annoDd_"+padNum, jContents).html();
		$("body").append($("<div>").addClass("annoPopDD_" + padNum + " annoPop").text(annoObjHtml));
		var popObj = $(".annoPopDD_" + padNum);
		
		$('.annoRefer_'+padNum, jContents).mouseover(function(){
			popObj.css({opacity:0.9, display:"none"}).fadeIn(200);
		}).mousemove(function(kmouse){
			tooltips(kmouse, popObj);
		}).mouseout(function(){
			popObj.css({left:"-9999px"});
		});
		
		annoCnt++;
	});
};


/* *********************************************
 * アノテーションon,off
 */
this.annoSwitch = function(){
	$("#annoSwitch").toggle(function(){
		annoPopup();
		$(".anno a").css({"background":"#fff86b","font-weight":"bold"});
		$("#annoSwitch").toggleClass("annoSwitchOn");
	},function(){
		$("span.anno").unbind();
		$(".anno a").css({"background":"none","font-weight":"normal"});
		$("#annoSwitch").toggleClass("annoSwitchOn");
	});
}


/* *********************************************
 * techtermページで画像をポップアップ表示する処理
 */
this.techtermImgPop = function(){
//	alert("this.techtermImgPop");
	
	var defsize = $("#mainContents").width()/3
	
	$(".techTermThumbnail img").each(function(i){
		$(this).attr("id", "techtermImg" + i).attr("class", "techtermImg");
		imgsrc = $(this).attr("src");
		imgcap = $(this).attr("title");
		
		$(".techTermThumbnail").after(
			$("<p />")
			.append(
				$("<img />").attr("src", imgsrc)
			).append($("<br />"))
			.append($("<span />").text(imgcap))
			.attr("id", "ttThumb" + i)
			.attr("class" , "ttThumb")
			.css({ display: "block", position: "absolute", left:-9999, "z-index":20 })
		)
		
		sizearray = resize($("#ttThumb" + i + " img"), defsize, defsize);
		var obj = $("#ttThumb" + i);
		obj.css("width", sizearray[0]);
		
		$("#techtermImg" + i ).mouseover(function(){
			obj.css({ opacity:0.9 }).fadeIn(200);
		}).mousemove(function(kmouse){
			tooltips(kmouse, obj);
		}).mouseout(function(){
			obj.css("left", -9999);
		});
		
	});
};


/* 画像ポップアッププレビュー表示 ********************************************* */
this.instantImagePreview = function(){
//	alert("this.instantImagePreview");
	
	instantprvNum = 0;
	var maxZ = 10;
	
	$(".maintext a.instantprv").each(function(){
		url = $(this).attr("href")
		$(this).attr("href", "javascript:void(0)").removeAttr("target").attr("title", url);
	});
	
	$('.maintext a.instantprv').click(function(){
		var imgUrl = $(this).attr("title");
		var picnum = $(this).text();
		var defSize = $("#mainInner").width() / 2;
		
		srcstr = $(".floatInstPrv").find("img[src='" + imgUrl + "']").attr("src");
		if(srcstr != undefined){
			$(".floatInstPrv img[src='" + imgUrl + "']").parent().remove();
		}


		$(this).parent().append(
			$("<p />").attr("class", "floatInstPrv").click(function(){
				$(".floatInstPrv").each(function(){
					z = $(this).css("z-index");
					maxZ = ( z > maxZ ) ? z : maxZ;
				});
				maxZ ++;
				$(this).css("z-index", maxZ);
			}).append(
				$("<a />").click(function(){
					$(this).parent().remove();
				}).text(picnum + " - 閉じる")
			).append(
				$("<br />")
			).append(
				$("<img />").attr("src",imgUrl).attr("id", imgUrl)
			).css({
					"display": "block",
					"z-index": -10, // IE向け　一度bodyの下で画像を展開（IEではdisplay:hidden状態で画像のコントロールが効かない
					"position": "absolute"
				}
			).draggable()
		);

		obj = $(".floatInstPrv").find("img[src='" + imgUrl + "']");
		sizearray = resize(obj, defSize, defSize);
		obj.parent().css( { "display" : "block",
							"width" : sizearray[0],
							"z-index": maxZ+1 });
		
	});
	
};


this.instantImagePop = function(){
	$('.thumbWrap a.instantprv').each(function(i){
		var imgUrl = $(this).attr("href");
		$("body").append(
			$("<img class='imgPop" + i + "' src='" + imgUrl + "'/>").css({"position":"absolute","left":"-9999px","border":"5px solid #222","display":"none"})
		);
		var tarImg = $(".imgPop" + i );
		if(tarImg.width() == 0){
			return false;
		}else{
			var defSize = tarImg.width()/3;
			sizearray = resize(tarImg, defSize, defSize);
			tarImg.width(sizearray[0]);
			tarImg.height(sizearray[1]);
			$(this).mouseover(function(){
				tarImg.css({ opacity:0.9 }).fadeIn(200);
			}).mousemove(function(kmouse){
				tooltips(kmouse, tarImg);
			}).mouseout(function(){
				tarImg.css({"left":-9999,"display":"none"});
			});
		}
	})
}


// annotationを30文字で切り、続きを読むボタンを付ける
this.setAnnoMore = function(){
	$("#contents .annotation dd").each(function(){
		var tarText = $(this).text();
		var tarStr = tarText.substring(0,30);
		$(this).html("<p>" + tarStr + "…</p>").append(
			$("<span>(<a>続きを読む</a>)</span>").toggle(function(){
				$(this).prev("p").text(tarText);
				$("a", this).text("閉じる");
			},function(){
				$(this).prev("p").text(tarStr + "…");
				$("a", this).text("続きを読む");	
			})
		)
	})
}


//地図表示に用いる簡易エンコード
this.sinpleEncode = function(valueArray){
	
	var maxValue = Math.max.apply(null,valueArray);
	var simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	chartData = ['s:'];
	for (var i = 0; i < valueArray.length; i++) {
		var currentValue = valueArray[i];
		if (!isNaN(currentValue) && currentValue >= 0) {
			chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) * currentValue / maxValue)));
		}else{
			chartData.push('_');
		}
	}
	return chartData.join('');

}


/* *******************************************
 * アクセス状況を示す世界地図 
 * @see common.js GLOBAL pageMeta, loadingImg
 */
 
this.setMapChart = function(obj){
	var bobj = $("#gadgetMap .gadgetBody");
	bobj.css("display", "block");
	$(obj).attr("class", "close");

	if(  bobj.html() == '' ){
		bobj.append($(loadingImg));
		$.getJSON(
			"http://astamuse.com/analytics/api/content_access_by_country.json?callback=?",
			{
				content_type:pageMeta.content_type,  // @see common.js pageMeta
				content_name:pageMeta.content_name
			},
			
			this.analytics_content_access_by_country_response = function(res){
				var tarCountry = "";
				var valueArray = new Array();
				var entry;
				var ratio;
				var maxValue = 0;
				
				bobj.html("<ul></ul>");
				for(i = 0; i < res.result.entries.length ; i++){
					entry			 = res.result.entries[i];
					tarCountry 		+= entry.country_code;
					valueArray[i] 	 = entry.visits;
					maxValue 		 = Math.max(entry.visits, maxValue);
					ratio 			 = Math.round(entry.visits * 100 / res.result.sum);
					
					$("ul", bobj).append("<li>" + entry.country_name_ja + ":" + ratio + "%</li>")
				}

				//簡易エンコード
				var chartData = sinpleEncode(valueArray);
				
				//googleChartAPIを利用して作成されるimgをappendする	
				bobj.prepend("<img src='http://chart.apis.google.com/chart?"
								+ "chco=F6FFDF,ffe0a1,ff8700"
								+ "&amp;chf=bg,s,EFFCFF"
								+ "&amp;chtm=world"
								+ "&amp;chs=224x127"
								+ "&amp;cht=t"
								+ "&amp;chld=" + tarCountry
								+ "&amp;chd=" + chartData+"'/>");
				setTimeout('equalHeight($(".applyHeight"))',500);
			}
		)
	}
	$(obj).attr("onclick","closeMapChart(this);");
	
}

this.closeMapChart = function(obj){
	$("#gadgetMap .gadgetBody").css("display", "none");
	$(obj).attr("class", "open");
	$(obj).attr("onclick","setMapChart(this);");
}


/* *******************************************
 * アクセスグラフを修正 
 * @see common.js GLOBAL pageMeta, loadingImg
 */


this.setAccessChart = function(obj){
	var bobj = $("#gadgetAccess .gadgetBody");
	bobj.css("display", "block");
	$(obj).attr("class", "close");
	
	if( bobj.html() == '' ){
		bobj.append($(loadingImg));

		var data;
		$.getJSON(
			"http://astamuse.com/analytics/api/content_access_by_date.json?callback=?",
			{
				content_type:pageMeta.content_type, // @see common.js pageMeta
				content_name:pageMeta.content_name
			},
			
			this.analytics_content_access_by_date_response = function(res){
				var maxValue = 0;
				var values = '';
				var tarDay;
				var dates = '';
				var entry;
				
				for( var i = 0 ; i < res.result.entries.length; i++ ){
					entry	 = res.result.entries[i];
					values	+= ',' + entry.visits;
					tarDay	= ( entry.date.slice(6,7) == 0 ) ? entry.date.slice(7) : entry.date.slice(6);
					dates	+= ( i % 10 != 0 ) ? '|' : '|' + entry.date.slice(4,6) + "/" + tarDay;
					maxValue = Math.max(entry.visits, maxValue);
				}

				values	= values.slice(1);
				dates	= dates.slice(1);
				
				maxValue = Math.floor(maxValue/10*1.2) * 10;
				maxValue = ( maxValue == 0 ) ? 20 : maxValue;
				var halfValue = maxValue/2;
				
				var today = res.result.entries[29].date;
				today = ( today.slice(6,7) == 0 ) ? today.slice(4,6) + "/" + today.slice(7) : today.slice(4,6) + "/" + today.slice(6);
				//googleChartAPIを利用して作成されるimgをappendする	
				bobj.html("<img src='http://chart.apis.google.com/chart?"
							 + "chxt=x,y"
							 + "&amp;chxl=0:|" + dates + today + "|1:|0|" + halfValue + "|" + maxValue
							 + "&amp;cht=lc"
							 + "&amp;chs=224x127"
							 + "&amp;chxt=x,y"
							 + "&amp;chm=s,FF9904,0,-1,3"
							 + "&amp;chg=23.1,50,1,5"
							 + "&amp;chd=t:" + values 
							 + "&amp;chds=0," + maxValue + "'/>");
				setTimeout('equalHeight($(".applyHeight"))',500);
			}
		);
	}
	$(obj).attr("onclick","closeAccessChart(this);");
}


this.closeAccessChart = function(obj){
	$("#gadgetAccess .gadgetBody").css("display","none");
	$(obj).attr("class","open");
	$(obj).attr("onclick","setAccessChart(this);");
}


/* *******************************************
 * メモ機能
 */
 
function setPrivateMemo(){
	var reqUrl	= 'http://astamuse.com/memo/api/';
	var pmemo	= $("#privateMemoLink");
	var pmemoi	= $("#privateMemoInput");
	var preUrl	= ($("a", pmemo).length != 0 ) ? $("a", pmemo).attr("href") : '';
	var memoId	= ( preUrl.match(/void/) ) ? '' : preUrl.replace(/.*\?id=(.*)$/, '$1' );
	var w;
	var flag	= ( $("#userName span").text() == '' ) ? 0 : 1;
	
	
	// メモ機能に対応していないページだったときの処理
	if(typeof astamuseContentInfo != "undefined"){
		var cinfo	= astamuseContentInfo;
	}else{
		pmemo.remove();
		return false;
	}
	
	// 
	if( memoId == ''){
		setClick('create');
	}else{
		read(preUrl);
		setClick('update', memoId );
	}
	
	// メモインプットの表示
	$("a", pmemo).click(function(){
		if(flag == 0){
			pmemoi.html("ログイン後にご利用になれます");
		}else{
			var dw		= 400;
				w		= $("body").width() - $("#subCol").width() - $("#gadgetCol").width() - 60;
			    w		= Math.min( dw , w );
			$("textarea", pmemoi).css("width", w);
		}
		pmemoi.toggle("slow");
		return false;
	});
	
	
	// メモのキャンセルボタンクリック
	$(".cancelButton", pmemoi).click(function(){
		pmemoi.toggle("slow");
	});
	
	function read(apiUrl){
		// APIからメモの情報を呼び出し
		$.ajax({
			url			: apiUrl,
			type		: 'GET',
			dataType	: 'jsonp',
			jsonp		: 'callback',
			success		: function(res){
				setTimeout(function(){
					$("#privateMemoField").html("<table><tr><th>メモ</th><td>" + res.result.memo + "</td></tr></table>").fadeIn("slow");
					$("textarea", pmemoi).val(res.result.memo);
					if(res.result.show_at_print) $("input[name=isPrinted]", pmemoi).attr("checked", "checked");
				}, 1000 );
				return false;
			}
		});
		return false;
	}
	
	
	function setClick(reqType, mid){
		// メモの確定ボタンボタンクリック
		$(".submitButton", pmemoi).click(function(){
			var isPrinted = ( $("#isPrinted").attr("checked") == "checked" ) ? true : false ;
			var data = {
						content_type: cinfo.contentType,
						content_id	: cinfo.id,
						memo		: $("#privateMemoContents").val(),
						show		: isPrinted,
						id			: mid
					};
			$.ajax({
				url		: reqUrl + reqType,
				type	: 'GET',
				data	: data,
				dataType: 'jsonp',
				jsonp	: 'callback',
				success	: function(res){
					$("#privateMemoField").html($(loadingImg).css("width", w));
					if( res.status == 'success' ){
						var apiUrl 	= reqUrl + 'read?id=';

						if( reqType == 'create'){
							$(".submitButton", pmemoi).unbind('click', setClick);
							mid = res.result.id;
						}
						
						apiUrl += mid;
						
						setTimeout(function(){
							read(apiUrl);
							setClick('update', mid);
						}, 1000);
							
					}else{
						$("#privateMemoField").html("ただいまサーバーが混み合っております。もう一度おためし下さい。").fadeOut('10000');
					}
					
					pmemoi.css("display", "none");
					return false;
				}
			});
		});	
	}
	
	return false;
}


/* スライダー ********************************************* */
this.setRecommendSlide = function(){
	$(".slider").accessNews({ speed : 500, slideBy : 4 });
}


/* ソーシャルブックマークのURLを修正 ********************************************* */
this.modSocialBookMark = function(){
	var url		= encodeURL(document.URL);
	var title	= encodeURL($("title").text());
	var str;
	
	str	= $("#hatebuAnchor").attr('href');
	$("#hatebuAnchor").attr('href', str + url);
	
	str = $("#hatebuEntry").attr('src');
	$("#hatebuEntry").attr('src' , str + url);
		
	str	= "http://bookmarks.yahoo.co.jp/action/bookmark?t=" + title + "&u=" + url;
	$("#yahooBMAnchor").attr('href', str);
	
	str	=  "http://www.google.com/bookmarks/mark?op=edit&hl=ja&bkmk="
			+ url + "&title=" + title;
	$("#googleBMAnchor").attr('href', str);
	
	str	= 'http://delicious.com/save?v=5&noui&jump=close&url='
			 + url + "&title=" + title;
						
	$("#deliciousAnchor").click(function(){
		window.open(str, 'delicious', 'toolbar=no,width=550,height=550');
	});
	
	str	=  "http://clip.livedoor.com/clip/add?link="
			 + url + "&title=" + title + "&jump=ref";
	$("#livedoorBMAnchor").attr('href', str );
	
	str =  "http://bookmark.fc2.com/user/post?url=" + url + "&title=" + title;
	$("#fc2BMAnchor").attr('href', str);
	
};


/* *******************************************
 * ユーザーがログインしている時とそうでないときの表示の切り分け（後日開発に吸収） 
 * @see GLOBAL isLogined
 */

function setLoginStr(){
	var strset	= {
					userPageCounter : [ "<p class='ready'>産業分類設定後、<br/>ご利用頂けます。</p><a class='selectIndustryButton' href='javascript:void(0)'>産業分類設定</a>", "<p class='ready'>準備中</p>" ],
					relatedPersonView : [ "<p class='ready'>産業分類設定後、<br/>ご利用頂けます。</p><a class='selectIndustryButton' href='javascript:void(0)'>産業分類設定</a>", "<p class='ready'>準備中</p>" ]
					};
	var ck = $.cookie("industry");
	
	if( typeof industry == 'undefined' || typeof isLogined != 'undefined' ){
		if(!isLogined){

			if( industry == null || industry == '' ){
				$("#industrySet").css("display","none");
				$("#industryNoSet").css("display","block");
				$("#industryNoSet .industryInner").html("<p><a class='selectIndustryButton' href='javascript:void(0)'>産業分類設定</a>所属産業が未設定のため、<br/>・似た人が見たページの機能<br/>・確認済みページの可視化機能<br/>は、ご利用になれません。</p>");
				
				$("#topIndustryCat > div.editIndustryDiv").append("<a class='selectIndustryButton'>産業分類が設定されていません。</a>")
				
			}
		}else{
			infoRestMeter();
			intervalRecommend();
			clearInterval(intervalRecommend);
			setInterval(intervalRecommend,30000);
		}
	}else{
		if( typeof industry == 'undefined' || industry == null || industry == '' ){
			$("#userPageCounter", jLeftCol).html(strset.userPageCounter[0]);
			$("#relatedPersonView", jLeftCol).html(strset.relatedPersonView[0]);
		}
	}
}

/* ********************************************
 * backgroundArt（Patentページの背景情報）関連
 */
this.bgArt = function(){
	var title	= $("#backgroundArt");
	var txt		= $("#backgroundArtText");
	
	// 表示非表示の切替え
	$("a", title).toggle(function(){
		$(this).text("表示する");
		txt.css("display", "block");
	},function(){
		$(this).text("表示しない");
		txt.css("display", "none");
	});

	// 本文が無かったときにタイトルを消す
	if(txt.text()=="") title.remove();
}


/* ********************************************
 * レコメンド表示
 */

function intervalRecommend(){
	var setting = {
					patent_granted 		: "http://patent.astamuse.com/ja/granted/JP/No/",
					patent_published	: "http://patent.astamuse.com/ja/published/JP/No/",
					techterm			: "http://techterm.astamuse.com/ja/"
					};
					// todo グローバルで統一的なURLのマップを作るべき
	var rpvObj	= $("#relatedPersonView", jLeftCol);
	
	$.getJSON(
       "http://astamuse.com/recommends/api/read?callback=?",
       function(res){
           if(res.status == 'success' && res.result.all_num != 0){
				if($("ol li", rpvObj).length == 0){
					rpvObj.html("<ol><li></li></ol>");
				}
				var oldListFirst = $("ol > li:eq(" + 0 + ")", rpvObj).text();
				var newListFirst = res.result.recommends[0].content_label.replace("\r","").replace("\n","");

				if( oldListFirst != newListFirst ){
					$("ol > li", rpvObj).removeClass("newList").addClass("oldList");
					
					for(var i = 0 ; i < 10 ; i++){
						
						var t = res.result.recommends[i];
						var u = eval("setting." + t.content_type );
						t.content_label = ( t.content_label == '' ) ? t.content_name : t.content_label;
						t.content_label = t.content_label.replace("\r","").replace("\n","");

						if( oldListFirst == t.content_label ){
							$("ol > li:gt(10)", rpvObj).fadeOut(200);
							break;
						}else{
							$("ol > li.oldList:eq(0)", rpvObj).before(
								"<li class='" + t.content_type + " newList' style='display:none;'><a href='" + u + t.content_name + "'>" + t.content_label + "</a></li>"
							);
							$("ol  > li.newList:last", rpvObj).show(50+80*(i+0.5));
							$("ol  > li:gt(10)", rpvObj).fadeOut(200);
						}
					}
					
					$(".numerator").text(res.result.reads_num);
					$(".denominator").text(res.result.all_num);
					infoRestMeter();
				}else{
					return false;
				}
			}else{
				rpvObj.html("<p class='ready'>産業分類設定後、<br/>ご利用頂けます。</p><a class='selectIndustryButton'>産業分類設定</a>");
				setSelectIndustry();
			};	
		}
	);
};
				
				

/* ********************************************
 * ユーザーの閲覧回数表示 → 後日開発に吸収して貰う
 */
this.viewCountPersonal = function(){
	if(typeof viewCountPersonalNum == 'undefined') return false;
	if(viewCountPersonalNum != '' ){
		$(".focusField").after("<p class='userFocusField'>この情報を見るのは"+ viewCountPersonalNum +"回目です。</p>");
	};
}



/* ********************************************
 * 製品資料請求種類選択
 *
 */
this.setRequestPop = function(){
	$("#requestPop").css("display","none");
	$(".requestButton a").click(function(){
		var tarPop = $.ampop($(this),$("#requestPop").html());
		var popTop = tarPop.offset().top + 80;
		var popLeft = tarPop.offset().left + 185;
		tarPop.css({"width":"214px","top":popTop+"px","left":popLeft+"px","background":"#F5F7EF","display":"none"});
		tarPop.fadeIn("fast");
	});
	
	if( $(".requestPopMail").html() == "" && $(".requestPopDoc").html() == "" ){
		$(".requestButton,.docRequest").remove();	
	};
}


/* ********************************************
 * 産業分類選択用モーダル
 * @see GLOBAL industry
 */
this.setSelectIndustry = function(){
	clearInterval(intervalRecommend);
	siWindow	= $("#selectIndustryWindow");//モーダルwindow
	siDetail	= $("#selectIndustryDetail");//詳細分類
	siLarge		= $("#selectIndustryLarge");//大分類
	siLargeAnc	= $("table a", siLarge);//大分類の項目
	//countOpenType = "open_popup" ;
	
	$(".selectIndustryButton, .editIndustryButton").click(function(){
		countOpenType = "open_manual";
		exe();
	});
	
	if( typeof industry != 'undefined' && industry != null && industry != '' ){
		industry = industry.replace("ROOT","");
		var industryNum = industry.match(/[1-9]*[0-9]{1}$/);
		var industryName = $("input[name=" + industryNum + "]", siDetail).attr("alt");
		$("#userIndustryList li").html(industryName);
	}
	
	function exe(){
		$("#wrap").css("opacity",0.3);
		clearInterval(intervalRecommend);//リコメンドを呼びに行くのを一旦クリアする。
		switch ( countOpenType ){
			case "open_popup"://自動ポップアップ表示の場合
			var apiUrl = "http://astamuse.com/user/api/industry_modal_open_count?m=update&cxt=popup"
			break;
			
			case "open_manual"://自ら設定ボタンを押した場合
			var apiUrl = "http://astamuse.com/user/api/industry_modal_open_count?m=update&cxt=manual"
			break;
		}
		
		
		$.ajax({
			url:apiUrl,
			dataType 	: "jsonp",
			jsonp		: "callback",
			success		: function(res){
				res = res;
			}
		});//産業設定のデータをDBへ渡す
			
		//モーダルwindow位置計算	
		if( siWindow.css("top") == "0px" || siWindow.css("top") == "auto"){
			var wWidth	= 650;
			var wHeight = 500;
			var dHeight = document.body.clientHeight;
			var dWidth	= document.body.clientWidth;
			var wTop 	= (dHeight - $("#selectIndustryWindow").height() - 50)/2;
			
			//ie6とie7はtopの値を変える
			var userAgent = window.navigator.userAgent.toLowerCase();
    		var appVersion = window.navigator.appVersion.toLowerCase();
    		
			if (userAgent.indexOf("msie") > -1) {
        		if (appVersion.indexOf("msie 6.0") > -1) {
	            	wTop = (dHeight)/2; // ie6
        		}else if (appVersion.indexOf("msie 7.0") > -1) {
			        wTop = (dHeight - siWindow.height() - 45)/2; // ie7
        		}
			}
			var wLeft 	=(dWidth - $("#selectIndustryWindow").width())/2;;
		}
		
		// window表示
		siWindow.css({"width":wWidth,"top":wTop,"left":wLeft,"border":"5px solid #444"}).fadeIn(800,"easeOutCirc");

		// 大分類クリック時の動作
		siLargeAnc.unbind();
		siLargeAnc.click(function(){

			siLargeAnc.css({"background":"#eee","color":"#21759B"});
			$("table", siDetail).css("display","none");
			$(this).css({"background":"#21759B","color":"#fff"});

			// 詳細分類表示
			siDetail.fadeIn("fast");
			var tarCat = $(this).attr("id");
			$("#" + tarCat + "Detail", siDetail).fadeIn("fast");
			//var tarHeight = siWindow.height();
			//var tarTop = document.body.clientHeight - tarHeight - 30;
			//siWindow.animate({"top":tarTop}, 300, "swing");
		});
		
		// 詳細分類チェック時の動作
		$("table :checkbox", siDetail).unbind();
		$("table :checkbox", siDetail).click(function(){
			// チェックを付けた場合(ToDo:firefoxにてチェックボックスのチェックが外れないバグが残っています。sagawa)
			if( $(this).is(":checked") ){
				
				var tarNum = $(this).attr("name");
				$("table :checkbox:checked:not([name="+tarNum+"])", siDetail).removeAttr("checked");
				
				var tarCat = $(this).parents("table").attr("id").replace("Detail","");
				var industryData = "ROOT." + tarCat + "." + tarNum; // セミコロン忘れ
				industry = industryData; // セミコロン忘れ
				
				switch ( countOpenType ){
					case "open_popup":
					var apiUrl = "http://astamuse.com/user/api/industry?m=update&tree=" + industryData + "&cxt=popup"
					break;
					
					case "open_manual":
					var apiUrl = "http://astamuse.com/user/api/industry?m=update&tree=" + industryData + "&cxt=manual"
					break;
				}

				$.ajax({
					url			: apiUrl,
					dataType	: 'jsonp', // クロスドメインのリクエストはJSONP
					jsonp		: 'callback', // TODO callbackリクエストを受けていいかどうか
					data		: { "tree": industryData }
				});

				siWindow.fadeOut("fast");
				industry = industry.replace("ROOT",""); // セミコロン忘れ
				var industryNum = industry.match(/[1-9]*[0-9]{1}$/);
				var industryName = $("input[name=" + industryNum + "]", siDetail).attr("alt");
				$("#industryNoSet").css("display","none");
				$("#userIndustryList li").html(industryName);
				$(".editIndustryButton").css("display","block");
				$("div#userPageCounter").html("<div class='restedNum'><table><tr><th class='per'><span></span> ％</th><td><div class='meterDiv'></div><span class='numerator'></span> / <span class='denominator'></span> 件</td></tr></table></div>");
				$("#industrySet").css("display","block");
				
				setTimeout(intervalRecommend,1000);
				setInterval(intervalRecommend,30000);
				siWindow.css("display","none");
				//topのみ
				$("#topIndustryCat > div.editIndustryDiv > a.selectIndustryButton").css("display","none");
				$("#wrap").css("opacity",1);
			}
		});
		return false;
	}

	// 閉じるボタンクリック時の動作
	$("#selectIndustryClose a").unbind();
	$("#selectIndustryClose a").click(function(){
		switch ( countOpenType ){
			case "open_popup":
			var apiUrl = "http://astamuse.com/user/api/industry_modal_close_count?m=update&cxt=popup"
			break;
			
			case "open_manual":
			var apiUrl = "http://astamuse.com/user/api/industry_modal_close_count?m=update&cxt=manual"
			break;
		}
		

		$.ajax({
			url			: apiUrl,
			dataType	: "jsonp",
			jsonp		: "callback",
			success		:function(res){
				res = res;
			}
		});
		siWindow.css("display","none");
		$("#wrap").css("opacity",1);
	});
}




/* ********************************************
 * 左カラムのuserfield以下の一番上のgdgetHeaderにボーダートップをかける
 */
this.setBorderTop = function(){
	$(".gadgetHeader:eq(0)", jLeftCol).css("border-top","1px solid #c2c4bb");
}

/* ********************************************
 * サムネイルポップアップ
 */

this.thumbPreviewOver = function(obj,src){
	
	$("body").append(
		"<img style='position:absolute; display:none; border:5px solid #333; z-index:15;' id='tarThumb' src='"+ src + "' />"
	);
	var tarImg = $("#tarThumb");

	if(tarImg.width() == 0){
		return false;
	}else{
		var defSize = tarImg.width()/3;
		sizearray = resize(tarImg, defSize, defSize);
		tarImg.width(sizearray[0]);
		tarImg.height(sizearray[1]);
		tarImg.css({ opacity:0.9 }).fadeIn(200);
		$(obj).mousemove(function(kmouse){
			tooltips(kmouse, tarImg);
		})
	}
}

this.thumbPreviewOut = function(obj,src){
	$("#tarThumb").remove();
}

/* ********************************************
 * "図~"オンクリックポップアップ
 */
this.imgInlinePreview = function(obj,src){

	var picnum = $(obj).text();
	var defSize = $("#mainInner").width() / 2;
	var maxZ = 10;

		$(obj).parent().append(
			$("<p />").attr("class", "floatInstPrv").click(function(){
				$(".floatInstPrv").each(function(){
					z = $(this).css("z-index");
					maxZ = ( z > maxZ ) ? z : maxZ;
				});
				maxZ ++;
				$(this).css("z-index", maxZ);
			}).append(
				$("<a />").click(function(){
					$(this).parent().remove();
				}).text(picnum + " - 閉じる")
			).append(
				$("<br />")
			).append(
				$("<img />").attr("src",src).attr("id", src)
			).css({
					"display": "block",
					"z-index": -10, // IE向け　一度bodyの下で画像を展開（IEではdisplay:hidden状態で画像のコントロールが効かない
					"position": "absolute"
				}
			).draggable()
		);

		obj = $(".floatInstPrv").find("img[src='" + src + "']");
		sizearray = resize(obj, defSize, defSize);
		obj.parent().css( { "display" : "block",
							"width" : sizearray[0],
							"z-index": maxZ+1 });
}



/* ********************************************
 * 角丸バンド
 */
this.createCorner = function(){
	$(".titleFuncPop", jTitle).corner("3px");
	$(".focusField", jContents).corner("3px");
	$(".userFocusField").corner("3px");
	$(".gadgetHeader, #downloadPdf a",jRightCol).corner("3px");
	$("#contentsTools").corner("3px").css("position","static");
//	$("#userName",jLeftCol).corner("3px");
}

function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		$(this).css("height","auto");
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
};


/* ********************************************
 * スムーススクロール
 */
this.smoothScroll = function(obj){
	var tarName = $(obj).attr("href").replace("#","");
	$("html,body").animate({"scrollTop":$('a[name=' + tarName + ']').position().top-60},1800,"easeOutCirc")
}

this.innerLinkListScroll = function(){
	$(".innerLinkList > ul > li > a").click(function(){
			smoothScroll(this);
			return false;
	})
}

/*
/* ********************************************
 * 問い合わせポップアップ
 */



this.impressionPop = function(obj){
	var tarPop = $.ampop($(obj),$(obj).next("#impressionBoxWrap").html());
		tarPop.css({"background":"#F5F7EF","display":"none"});
		tarPop.fadeIn("fast");
}


this.impressionAjax = function(obj){
	var tarStr = $(obj).prev("textarea").val();
	var param ={
			"contact_content"	:	tarStr
		};

	$.ajax({
		url:"http://astamuse.com/contact/api/create",
		data:param,
		type:'GET',
		dataType	: 'jsonp',
		jsonp		: 'callback',
		success:function(res){
			$(obj).parents(".ampop").fadeOut("fast");
		}
	});
}


/* ********************************************
 * フィルター → 後日開発に吸収して貰う
 */

function rankingFilter(){
	var filter	= ['44Kv44Oq44OI44Oq44K5','6Zmw6IyO','5oCn5Lqk']; // 放送禁止用語群をbase64でエンコードしてます
	for( var i = 0; i < filter.length; i ++ ){
		
		var str = Base64.decode(filter[i]);
		$(".rankTable td").each(function(){
			var t = $(this).text();
			var r = new RegExp(str);
			if(t.match(r)){
				$(this).parents("tr").remove();
			};
		});
	};
}

/* ********************************************
 * 関係の強い求人サムネorテーブル表示
 */

this.relatedJobViewSelect = function(){
	$("#relatedJobThumbView").click(function(){
		if(!$("#relatedJobThumbView").hasClass("viewSelected")){
			$("#relatedJobThumbList").fadeIn("fast");
			$("#relatedJobTblList").hide();
			$("#relatedJobThumbView , #relatedJobTblView").toggleClass("viewSelected");	
		}
	});
	$("#relatedJobTblView").click(function(){
		if(!$("#relatedJobTblView").hasClass("viewSelected")){
			$("#relatedJobTblList").fadeIn("fast");
			$("#relatedJobThumbList").hide();
			$("#relatedJobThumbView , #relatedJobTblView").toggleClass("viewSelected");
		}
	});

}

/* ********************************************
 * 関係の強い求人で画像をランダムに当てはめ、画像データから10枚無作為に取り出す。
 */

this.relatedJobThumbSet = function(){

	var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13];
	var l = arr.length;
	for( var i = 0; i < 10 ; i++){
		var tarNum = Math.floor(Math.random()*l);
		var t = arr[tarNum];

		$("#relatedJobThumbList img:eq("+i+")").attr("src","http://static.astamuse.com/img_cmn/relatedJob/"+t+".jpg");
		$("#relatedJobTblList .jobThumb img:eq("+i+")").attr("src","http://static.astamuse.com/img_cmn/relatedJob/"+t+".jpg");
		
		arr[tarNum] = arr[--l];
		arr[l] = t;
		arr.pop();
	}

}

/* ********************************************
 * 奇数番目のテーブルに薄くバックグラウンド
 */

this.relatedJobTableBack = function(){
	$("#relatedJobTblList > li:odd").css("background","#fafafa");
}

/* ********************************************
 * jacユーザーの産業設定によるフィルタリング→テキストリンク
 */
this.jobLink = function(){
	var ck = $.cookie("industry");

	if( ck != null && ck != "undefind" ){
		if( ck == "ROOT.Infrastructure.4" ){
			var strArr = [
				"<a href='http://regulatoryaffairs-job.com/'>astamuseは、あなたの薬事業界への転職もサポートします！薬事関連の求人情報が満載の「薬事申請お仕事ナビ」へ今すぐアクセス！</a>",
				"<a href='http://regulatoryaffairs-job.com/'>astamuseは新たに「薬事申請転職ナビ」をスタートしました！求人情報が満載！転職サポートも充実の求人サイトへアクセス！</a>",
				"<a href='http://drugdiscovery-job.com/'>astamuseは、あなたの創薬業界への転職もサポートします！創薬関連の求人情報が満載の「創薬申請お仕事ナビ」へ今すぐアクセス！</a>",
				"<a href='http://drugdiscovery-job.com/'>astamuseは新たに「創薬転職ナビ」をスタートしました！求人情報が満載！転職サポートも充実の求人サイトへアクセス！</a>"
			]
			var tarNum = Math.floor(Math.random()*4);
			var tarNum2 = Math.floor(Math.random()*4);
			var tarStr = strArr[tarNum];
			var tarStr2 =strArr[tarNum2];
			$("#hInfoBar p").html(tarStr);
			$("#jacContentsTextLink").html(tarStr2);
			$("#infoClose").click(function(){
				$("#hInfoBar").css("display","none");
			});
			
		}else{
			return false;
		}
	}
}

$(document).ready(function(){
	/* GLOBALで利用したいjquery オブジェクト */
	jLeftCol	= $("#wrap > #middle > #subCol");
	jRightCol	= $("#wrap > #middle > #mainCol > #mainInner > #gadgetCol > #gadgetColInner" );
	jTitle		= $("#wrap > #middle > #mainCol > #mainInner > #title");
	jContents 	= $("#wrap > #middle > #mainCol > #mainInner > #mainContents > #mainConInner > #contents");

	//jobLink();
	relatedJobThumbSet();
	relatedJobTableBack();
	viewCountPersonal();
	bgArt();
	setLoginStr();
	infoRestMeter();
	setBorderTop();
	itemMetaSwitch();
	annoSwitch();
	equalHeight($(".applyHeight"));
	mainImageResize();
	setSelectIndustry();
	innerLinkListScroll();
	rankingFilter();
	relatedJobViewSelect();
	setTimeout(createCorner, 5000);
	//setTimeout(authorsName, 8000);←遅延処理するとバグります
	authorsName();
	applicantsName();
	setTimeout(titleFunctionPopup, 8000);
	setTimeout(modSocialBookMark, 10000);

	// 必要かどうか解らない関数
	setPrivateMemo();
	setRequestPop();
});

