/* ********************************************
 * グローバル変数設定
 */

var mainDomain		= location.hostname;
var cookieParams 	= { expires:365, path:'/', domain: getRootDomain() };
var pageMeta		= getPageMeta();
var loadingImg		= "<div style='padding:20px; text-align:center; border:none;'><img style='border:none;' src='http://static.astamuse.com/img_cmn/loader.gif' /></div>";

/* ********************************************
 * ampop plugin
 * author Yoji Shiraki
 * @arg1 obj = Event observing jquery object.
 * @arg2 msg = html that is contained in pop up box.
 */
 

(function($){
	$.ampop = function(obj, msg, pos){
		msg 		= '<div class="amClose"><a href="javascript:void(0)">　</a></div>' + msg;
		var cname 	= 'ampop';
		var offset 	= 10;
		var pWidth	= 250;

		var pos 		= obj.position();
		var objLeft 	= pos.left;
		var objTop 		= pos.top;
		var objHeight	= obj.height();
		var objWidth	= obj.width();
		
		var popobj	= $("<div>").html(msg).addClass(cname);
						
		$(".amClose a", popobj).click(function(){
			popobj.fadeOut(100);
			setTimeout(popobj.remove(),500);
		});

		$("body").append(popobj.css({display: "none"}));
		
		var pHeight	= popobj.height();
		if(objTop - pHeight > 0){
			var pObjTop = objTop - pHeight - objHeight - offset;
		}else{
			var pObjTop = objTop + objHeight + offset;
		}
		
		popobj.css({
				width	: pWidth,
				top		: pObjTop,
				left	: objLeft,
				position: "absolute"
				}). fadeIn(100);
		
		return popobj;
	}
	
})(jQuery);




/* ***************************************
 * ヘッダーメニューのドロップダウン notFix 
 */
this.dropdown = function(){
	var docWidth = $(document).width();
	
	$("#hmenu > ul > li").hover(
		function(){
			$(this).children("a").addClass("listOn")
			tarUl = $("ul", this);
			var tarUlLeft = $(this).parent().position().left;
			var tarLiLeft = $(this).position().left;
			var childUlWidth = tarUl.width();
			var diff = docWidth - tarUlLeft - tarLiLeft - childUlWidth;
			
			if(diff > 0){
				tarUl.fadeIn("fast");
			}else{
				tarUl.css("left", diff - 10 +"px").css("display", "block");
			}
		},function(){
			$("ul", this).css("display","none");
			$(this).children("a").removeClass("listOn")
		}
	);
};



this.decodeBase64Classes = function() {
	$(".base64").each(function(){
		var elm = $(this);
		elm.replaceWith(Base64.decode($.trim(elm.text())))
	})
}


/* ****************************** 
 * ツールチップ表示 
 */
function tooltips(kmouse, obj){
	var border_top = $(window).scrollTop(); 
	var border_right = $(window).width();
	var left_pos;
	var top_pos;
	var objWidth = obj.width();
	var objHeight = obj.height();
	var offset = 20;
	
	if(border_right - (offset *2) >= obj.width() + kmouse.pageX){
		left_pos = kmouse.pageX+offset;
	} else{
		left_pos = border_right-obj.width()-offset;
	}
	
	if(border_top + (offset *2)>= kmouse.pageY - obj.height()){
		top_pos = border_top +offset;
	} else{
		top_pos = kmouse.pageY - obj.height()-offset;
	}
	obj.css({ position:"absolute", left:left_pos, top:top_pos });
	return false;
}



/* ********************************
 * 画像リサイズ処理 
 */
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;
}



/* ***************************************
 * テキスト検索
 */
 
this.setTextSearch = function(){
	var ctype = '';
	var tarUri	= "http://search.astamuse.com/ja";
	var u		= document.URL;
	var sti = $("#searchTextItem");
	var sts = $("#searchTypeSelect");
	var tse = $("#textSearchExe");
	
	if( u.match("http://astamuse.com/")){		// トップページ
		ctype = '';
		$("#idxServiceList a[href='http://corporation.astamuse.com']").attr("href", 'http://company.astamuse.com');
	}else if( u.match(/^http:\/\/search\.astamuse\.com\/.*/) ){		// 検索結果一覧ページ
		ctype = u.replace(/http:\/\/search\.astamuse\.com\/ja\/(.*)\/.*/, '$1');
	}else if( u.match(/^http:\/\/.*\.astamuse\.com\/$/) ){		// コンテンツトップ
		ctype = u.replace(/http:\/\/(.*)\.astamuse\.com\/$/, '$1');
	}else{
		ctype = u.replace(/http:\/\/(.*)\.astamuse\.com\/.*/, '$1');
	}
	
	setSearchType(ctype);
	
	function setSearchType(c){
		if( c == 'merchandise' ){
			c = 'product';
		}else if( c == 'company' ){
			c = 'corporation';
		}else if( c == 'creative-worker' ){
			c = 'inventor';
		}else if( c == 'patent' ){
			c = 'patent_published';
		}else if( ctype == '' ){
			c = 'patent_published';
		}
		tse.attr("class", c);
		return c;
	}
	
	$("#searchText").focus(function(){
		sti.css("display", "block");
		sts.attr("class", "open");
	}).blur(function(){
		setTimeout(function(){
			sti.css("display", "none");
			sts.attr("class", "close");
		}, 200);
	});
	
	
	
	sts.click(function(){
		if($(this).attr("class") == 'close'){
			$(this).attr("class", "open");
			sti.css("display", "block");
		}else{
			$(this).attr("class", "close");
			sti.css("display", "none");
		}
	});
	
	
	
	$("a", sti).mouseup(function(){
		sti.css("display", "none");
		sts.attr("class", "close");
	}).mousedown(function(){
		var c = $(this).parents("li").attr("class");
		var t = $(this).text();
		setSearchType(c);
		tse.attr('value',  t + "検索");
	});
	
	tse.click(function(){
		var str = $("#searchText").val();
		var c	= tse.attr("class");
		tarUri += "/" + c + "/" + encodeURI(str);
		tse.parents('form').attr("action", tarUri);
		document.location = tarUri;
		return false;
	});	
	
	$("#indexTextSearch form").submit(function(){
		var str = $("#searchText").val();
		var c	= tse.attr("class");
		tarUri += "/" + c + "/" + encodeURI(str);
		$(this).attr("action", tarUri);
		document.location = tarUri;
		return false;
	});
	
	$("#header form").submit(function(){
		var str = $("#searchText").val();
		var c	= tse.attr("class");
		tarUri += "/" + c + "/" + encodeURI(str);
		$(this).attr("action", tarUri);
		document.location = tarUri;
		return false;
	});
	
	return false;
}



/*
 * 数字の桁数を0で揃える
 * @arg1 桁数を揃えたい数字（例：15）
 * @arg2 桁数指定（例：4）
 * @regurn 桁数を揃えた数字（例:0015）
 */
 
function padding(s,l){
	return( l.substr(0, (l.length-s.length) )+s );
}


/*
 * UTF-8でのURLエンコード
 * @arg1 エンコードしたい文字列
 */
function encodeURL(str) {
	var character	= '';
	var unicode		= '';
	var string		= '';
	var i			= 0;

	for (i = 0; i < str.length; i++) {
		character = str.charAt(i);
		unicode   = str.charCodeAt(i);
		if (character == ' ') {
			string += '+';
		} else {
			if (unicode == 0x2a || unicode == 0x2d || unicode == 0x2e || unicode == 0x5f || ((unicode >= 0x30) && (unicode <= 0x39)) || ((unicode >= 0x41) && (unicode <= 0x5a)) || ((unicode >= 0x61) && (unicode <= 0x7a))) {
				string = string + character;
			} else {
				if ((unicode >= 0x0) && (unicode <= 0x7f)) {
					character   = '0' + unicode.toString(16);
					string += '%' + character.substr(character.length - 2);
				} else if (unicode > 0x1fffff) {
					string += '%' + (oxf0 + ((unicode & 0x1c0000) >> 18)).toString(16);
					string += '%' + (0x80 + ((unicode & 0x3f000) >> 12)).toString(16);
					string += '%' + (0x80 + ((unicode & 0xfc0) >> 6)).toString(16);
					string += '%' + (0x80 + (unicode & 0x3f)).toString(16);
				} else if (unicode > 0x7ff) {
					string += '%' + (0xe0 + ((unicode & 0xf000) >> 12)).toString(16);
					string += '%' + (0x80 + ((unicode & 0xfc0) >> 6)).toString(16);
					string += '%' + (0x80 + (unicode & 0x3f)).toString(16);
				} else {
					string += '%' + (0xc0 + ((unicode & 0x7c0) >> 6)).toString(16);
					string += '%' + (0x80 + (unicode & 0x3f)).toString(16);
				}
			}
		}
	}
  return string;
}

/*
 * ページのcontent_name等を取得
 * @author shiraki
 */
function getPageMeta(){
	var obj = {
				mode				: '',
				content_type		: '',
				content_type_label	: '',
				content_name		: ''
				};
				

	var map = {
				published		: { slug : 'patent_published' ,		label : '発明' },
				granted			: { slug : 'patent_granted',		label : '発明' },
				patent			: { slug : 'patent',				label : '発明' },
				techterm		: { slug : 'techterm',				label : '技術用語' },
				inventor		: { slug : 'inventor',				label : '発明者' },
				product			: { slug : 'product',				label : '商品' },
				service			: { slug : 'service',				label : 'サービス' },
				software		: { slug : 'software',				label : 'ソフトウェア' },
				merchandise		: { slug : 'merchandise',			label : '商品' },
				patentattorney	: { slug : 'person',				label : '弁理士' },
				corporation		: { slug : 'corporation',			label : '企業' },
				company			: { slug : 'company',				label : '法人' },
				attorney		: { slug : 'attorney', 				label : '代理人' },
				product			: { slug : 'product', 				label : '製品' },
				engineer		: { slug : 'engineer', 				label : '技術者' },
				patentoffice	: { slug : 'patentoffice',			label : '特許事務所' }
				};
	
	
	var u = document.URL;
	obj.mode = ( u.match("127.0.0.1") ) ? 'localhost' : 'production' ;
	
	
	for( var i in map ){
		if(u.match(i)){
			obj.content_type = map[i]['slug'];
			break;
		}
	}
	
	var content_name = u.replace(/.*\/.*\/(.*)$/, "$1");

	var filter = ["詳細", "解説","経過情報","参考文献","要約","関連特許"];
	var flag = 0;
	
	for( var i = 0; i < filter.length; i++){
		var r = new RegExp(encodeURI(filter[i]));
		if( content_name.match(r) ) flag = 1;
	}
	
	if ( flag == 1 ) content_name = u.replace(/.*\/(.*)\/.*$/, "$1");
	
	var pattern = [ "\\/", "#", "\\?.*", ":.*" ];
	var reg;
	
	for( var i = 0; i < pattern.length; i++ ){
		reg = new RegExp( pattern[i] );
		content_name = content_name.replace(reg, '');
	}
	
	obj.content_name = content_name;
	return obj;
}

/* ********************************************
 * 現在のルートドメインを返します
 */
function getRootDomain(){
	var mhost	= location.host;
	var str		= mhost.match(/astamuse\.com/);
	return str = (str) ?  ".asmutamuse.com" : "." + mhost.replace(/:[0-9]*/, '') ;
}

/* ********************************************
 * ヘッダーの機能紹介
 */

this.headerTopInfo = function(){
	var u = document.URL;
	if( !u.match(/http:\/\/search\.astamuse\.com\//) ){
		if( $.cookie("headerTopInfo") == null ){
			$("#googleSearchTechTerm").css("display","none");
			setTimeout(function(){ $("#hInfoBar").slideDown(300); },5000);
			$("#infoClose").click(function(){
				$.cookie("headerTopInfo","closed",  { expires:365, path:'/', domain:'.astamuse.com' });
				$("#hInfoBar").css("display","none");
			});
		}
	}
	
	if( typeof astamuseContentInfo != 'undefined' ){
		if( astamuseContentInfo.contentType == 'patent_published' || astamuseContentInfo.contentType == 'patent_granted' ){
		 	if( $.cookie("visited") == null ){
		 		if( $("#googleSearchTechTerm").html() ){
					$("#hInfoBar p").html("お探しの技術用語はこちらですか → " + $("#googleSearchTechTerm").html());
					if( $.cookie("headerTopInfo") != null ){
						$("#hInfoBar").slideDown(300);
						$("#infoClose").click(function(){
							$("#hInfoBar").css("display","none");
						});
					}
				}
		 	}
		}
	}
}
/* ********************************************
 * 検索語句を検索ボックスに
 */

this.serchWord = function(){
	var u = document.URL;
	if( u.match(/http:\/\/search\.astamuse\.com\//) ){
		var tarWord = $("#title h1").text();
		$("#searchText").val(tarWord);
	}
}

/* ********************************************
 * 検索語句ハイライト
 */

this.searchHilite = function(){
	var w = $("#searchText").val();
	if( w != "" ){
		var tarW = '/' + w + '/g'; 
		var newW = "<span class='hilite'>" + w + "</span>";
		$("#mainContents > #mainConInner > #contents > .itemSummaryList > ul > li > a").each(function(){
			$(this).html($(this).html().replace(eval(tarW),newW))
		})
		$("#mainContents > #mainConInner > #contents > .itemSummaryList > ul .resultItem").each(function(){
			$(this).html($(this).html().replace(eval(tarW),newW))
		})
	}else{
		return false;
	}
}


/* ********************************************
 * コナミ様用広告スクリプト
 */

this.createCorporationAd = function(){
	var n, nFlag, hFlag;
	var ad	= '<div class="gadgetHeader"><h3>関連企業情報</h3></div>'
			+ '<div class="gadgetBody">[main]</div>';
			
	var str = "<p><a href='http://www.konami.co.jp/job/jk/index.php' id='konamiAd'>"
			+ "<strong>(株)コナミデジタル<br />エンタテインメント</strong>"
			+ "<br />【求人情報】コナミが法務・特許の<br />幹部候補を募集！業界経験不問</a></p>";
			
	var h 	= $("h1").text();
	var r1 	= new RegExp("コナミ");
	var r2	= new RegExp("デジタル");
	var obj = $("#gadgetAdCorportation");
	var n   = $("#applicantNameCell a").text();
	
	if( h.match(r1) && h.match(r2) ) hFlag = 1;
	if( typeof n != 'undefined' && ( n.match(r1) && n.match(r2) ) ) nFlag = 1;

	if( hFlag == 1 || nFlag == 1){
		obj.attr("class", "gadget");
		ad = ad.replace("[main]", str);
		obj.append($(ad));
	}
	
	return false;
}


$(document).ready(function(){
	dropdown();
	setTextSearch();
	decodeBase64Classes();
	serchWord();
	createCorporationAd();
	//searchHilite();
	setTimeout("headerTopInfo()",450);
});
