// JavaScript Document

var ResultConfig = {
	ID_RESULT_AREA			:"jsid-resultArea",
	ID_LEFT_AREA			:"jsid-resultLeftArea",
	ID_MAIN_AREA			:"jsid-resultMainArea",
	ID_MAIN_LIST			:"jsid-resultMainList",
	ID_MAIN_POPUP			:"jsid-resultMainPopup",
	ID_MAIN_ERROR			:"jsid-resultMainError",
	ID_TOTAL_AREA			:"jsid-resultTotalArea",
	ID_MORE_BTN				:"jsid-resultMoreBtn",
	ID_MORE_LOADING			:"jsid-resultMoreLoading",
	ID_DISPLAY_OPTION		:"jsid-resultDisplayOption",
	ID_DISPLAY_PHOTO		:"jsid-resultDisplayPhoto",
	ID_DISPLAY_SUMMARY		:"jsid-resultDisplaySummary",
	ID_DISPLAY_ORDER		:"jsid-resultDisplayOrder",
	ID_SEARCH_CONTENT_AREA	:"jsid-searchContentArea",
	ID_SEARCH_CONTENT		:"jsid-resultSearchContent",
	ID_SEARCH_KEYWORD_AREA	:"jsid-searchKeywordArea",
	ID_SEARCH_KEYWORD_LIST	:"jsid-searchKeywordList",
	ID_SEARCH_KEYWORD_POPUP	:"jsid-searchKeywordPopup",
	ID_DRILLDOWN_AREA		:"jsid-resultDrilldownArea",
	ID_DRILLDOWN_LIST		:"jsid-resultDrilldownList",
	ID_DRILLDOWN_ELEMENT_PRE:"jsid-resultDrilldownElem",
	ID_WIKIPEDIA_AREA		:"jsid-resultWikipediaArea",
	ID_WIKIPEDIA_LIST		:"jsid-resultWikipediaList",
	
	CLS_RESULT_TR			:"jscls-resultTrClass",
	CLS_RESULT_TD			:"jscls-resultTdClass",
	CLS_RESULT_TD_SPACER	:"set-Spacer",
	CLS_PUBLISH_DETAIL		:"jscls-publishDetail",
	CLS_SEARCH_KEYWORD		:"jscls-searchKeywordElement",
	CLS_SET_VIZ				:"set-Viz",
	CLS_DRILLDOWN_ELEMENT	:"jscls-resultDrildown",
	CLS_DRILLDOWN_LABEL		:"jscls-resultDrilldownLabel",
	CLS_RESULT_MENU_SELECT	:"jscls-resultMenuSelect",
	CLS_RESULT_MENU_SUBMIT	:"jscls-resultMenuSubmit",
	CLS_LOADING				:"wcp-Functional-004",
	CLS_RESULT_CREATORS		:"jscls-resultCreators",
	CLS_SET_ERROR			:"set-Error",
	
	IMG_NOWPRINTING			:"/externals/images/img-nophoto-01.jpg",
	IMG_ELEMENT_COLOR_ARR	:new Array(
									   '/externals/images/icn-signal-01.png',
									   '/externals/images/icn-signal-02.png',
									   '/externals/images/icn-signal-03.png',
									   '/externals/images/icn-signal-04.png',
									   '/externals/images/icn-signal-05.png',
									   '/externals/images/icn-signal-06.png'
									   ),
	
	HTML_WIKIPEDIA_ELEMENT	:'<li id="#{id}" class="'+  FixedValues.CLS_DRAGGABLE_WIKIPEDIA +'">' +
							'<a href="javascript:void(0);" class="'+ FixedValues.CLS_DRAGGABLE_TITLE +
							'" onclick="rtAssocWikipedia(\'#{id}\')">#{title}</a>' +
							'<a href="#{url}" target="_blank"><img src="/externals/images/icn-window-01.gif" alt="#{title}" width="8" height="10" class="indicator" /></a>' +
							'</li>',
	
	HTML_ELEMENT		:'<div class="set-I">'+
						'<p class="set-Colorz">#{colors}</p>'+
						'<table cellspacing="0">'+
						'<tr>'+
						'<td class="set-Viz" style="display:#{photoDisplay};">#{image}</td>'+
						'<td class="set-Info">'+
						'<h3><a href="#{url}" onclick="javascript:linkToDetail(this.href); return false;" class="'+ FixedValues.CLS_DRAGGABLE_TITLE +'" target="_blank"></a></h3>'+
						'#{publish}'+
						'<p class="summary"><span>#{description}</span></p>'+
						'</td>'+
						'</tr>'+
						'</table>'+
						'</div>',
						
	HTML_WORKS_ELEMENT	:'<div class="set-I">'+
						'<p class="set-Colorz">#{colors}</p>'+
						'<table cellspacing="0">'+
						'<tr>'+
						'<td class="set-Info">'+
						'<h3><a href="#{url}" onclick="javascript:linkToDetail(this.href); return false;" class="'+ FixedValues.CLS_DRAGGABLE_TITLE +'" target="_blank"></a></h3>'+
						'<div class="set-Creation">'+
						'<p><em class="jscls-resultCreators"></em></p>'+
						'<p><a href="#{url}" onclick="javascript:linkToDetail(this.href); return false;">掲載本<strong>#{book_total}</strong>冊</a></p>'+
						'</div>'+
						'<p class="summary"><span>#{description}</span></p>'+
						'</td>'+
						'</tr>'+
						'</table>'+
						'</div>',
						
	HTML_ELEMENT_IMAGE	:'<div><a href="#{url}" onclick="javascript:linkToDetail(this.href); return false;"><img src="#{image_url}" alt="#{title}" width="60" /></a></div>',
	
	HTML_ELEMENT_PUBLISH:'<p><em class="jscls-resultCreators"></em><br />'+
						'#{publishers}&nbsp;<span><br />'+
						'#{publication_date}'+
						'<span class="#{detailClass}"style="display:#{detailDisplay};">,'+
						'&nbsp;#{edition},&nbsp;#{quantity},&nbsp;#{size}</span></span></p>',
						
	HTML_ELEMENT_MENU	:'<div class="set-AddList">'+
						'<p class="p-A">'+
						'<select class="select-A #{selectClassName}">#{option}</select>'+
						'</p>'+
						'<p class="p-B #{submitClassName}"><a href="javascript:void(0);"><img src="/externals/images/btn-add-01.gif" alt="に追加する" width="74" height="19" class="rollover" /></a></p>'+
						'</div>',
						
	HTML_INC_KEYWORD	:'<li class ="#{className}"><strong class="'+ FixedValues.CLS_DRAGGABLE_TITLE +'" style="cursor:move;">#{keyword}</strong><img src="/externals/images/icn-close-01.png" alt="このキーワードを外す" width="13" height="13" class="indicator wcp-Csr-Pointer jscls-closeKeyword" /></li>',
	
	HTML_EXC_KEYWORD	:'<li class="#{className} set-Exception"><img src="/externals/images/icn-keywords-04.png" alt="除外" width="30" height="13" class="exIcn indicator" /><strong class="'+ FixedValues.CLS_DRAGGABLE_TITLE +'" style="cursor:move;">#{keyword}</strong><img src="/externals/images/icn-close-01.png" alt="このキーワードを外す" width="13" height="13" class="indicator wcp-Csr-Pointer jscls-closeKeyword" /></li>',
	
	HTML_DRILLDOWN_LABEL:'<h3 class="#{className}"><a href="javascript:void(0);">#{title}</a></h3>',
	
	HTML_DRILLDOWN_ELEMENT:'<li id="#{id}" class="#{className} wcp-Csr-Pointer">#{title}（#{num}）</li>',
	
	HTML_DRILLDOWN_ELEMENT_SELECTED:'<li id="#{id}" class="#{className} wcp-Csr-Pointer"><strong>#{title}（#{num}）</strong><a href="javascript:void(0);"><img src="/externals/images/icn-close-01.png" alt="このキーワードを外す" width="13" height="13" class="indicator" /></a></li>',
					
	HTML_ELEMENT_COLOR	:'<img src="#{src}" alt="#{alt}" width="9" height="9" />',
	
	TEXT_MAIN_ERROR		:"“#{content}”に該当する情報はありませんでした。<br />"+
						"検索条件を変更して、再度検索してください。",
	
	DEFAULT_COLUMN_NUM:3
}





var SearchContent = function(){
	this.resultArea		= document.getElementById(ResultConfig.ID_RESULT_AREA);
	this.contentArea	= document.getElementById(ResultConfig.ID_SEARCH_CONTENT_AREA);
	this.leftArea		= document.getElementById(ResultConfig.ID_LEFT_AREA);
	this.container		= document.getElementById(ResultConfig.ID_SEARCH_KEYWORD_AREA);
	this.listContainer	= document.getElementById(ResultConfig.ID_SEARCH_KEYWORD_LIST);
	this.searchTitle	= document.getElementById(ResultConfig.ID_SEARCH_CONTENT);
	this.popup			= new PopupSelectBox(ResultConfig.ID_SEARCH_KEYWORD_POPUP);
	this.title			= "";
	this.total			= 0;
	this.RIGHT_WIDTH	= 205;
	
	this.container.style.display = "none";
	
	var self = this;
	this.popup.onareaout = function(){
		self.popup.close();
	}
	
	ResizeManager.addCallBack(self.fitContent, self);
}

SearchContent.prototype = {
	fitContent:function(){
		var str;
		var leftWidth = $(this.resultArea).width() - this.RIGHT_WIDTH;
		var totalStr = " （全"+this.total+"件）";
		
		if(!this.title){
			this.searchTitle.innerHTML = "検索結果";
			return;
		}
		
		var preTitle;
		var suffTitle;
		if(GlobalValues.resultType != ResultType.ASSOC_BOOK){
			str = "";
			preTitle = "「";
			suffTitle = "」の一致検索結果" + totalStr;
			var tempTitle = this.title.replace(/"/g,"");
			var strArr = tempTitle.split(",");
			var len = (strArr) ? strArr.length : 0;
			
			// exclude complete match conditions and media type condition;
			if(GlobalValues.resultType == ResultType.MATCH_BOOK) {
				len -= 3;
			}
					
			var index;
			for(var i = 0; i < len; i++){
				var word = strArr[i];
				if(word){
					index = i;
					if(str.length != 0) str += "&nbsp;&nbsp;";
					str+= word;
				}
			}
		}else{
			str = this.title;
			switch(SearchManager.assocType){
				case AssocType.SHELF:
					preTitle = "書棚「";
					suffTitle = "」の連想結果" + totalStr;
					break;
				case AssocType.WIKIPEDIA:
					preTitle = "ウィキペディア「";
					suffTitle = "」の連想結果" + totalStr;
					break;
				case AssocType.DETAIL:
					preTitle = "「";
					suffTitle = "」とつながる本からの連想結果" + totalStr;
					break;
				default:
					preTitle = "「";
					suffTitle = "」の連想結果" + totalStr;
					break;
			}
		}
		
		this.searchTitle.innerHTML = "検索中";
		var btitleHeight = $(this.searchTitle).height();
		this.searchTitle.innerHTML = preTitle + str + suffTitle;
		var atitleHeight = $(this.searchTitle).height();
		var i=str.length-1;
		
		while(atitleHeight> btitleHeight && i >= 0){
			str = str.substring(0,i-1);
			this.searchTitle.innerHTML = preTitle + str + "…" + suffTitle;
			titleWidth = $(this.contentArea).width();
			atitleHeight = $(this.searchTitle).height();
			i--;
		}
	},
	
	setContent:function(str, total){
		if(!(str instanceof String)) str = String(str);
		str = str.replace(/\</g, "&lt;");
		str = str.replace(/\>/g, "&gt;");
		this.title = str;
		this.total = total;
		
		this.fitContent();
	},
	
	clearContent:function(){
		this.searchTitle.innerHTML = "検索中...";
	},
	
	setKeywords:function(){
		if(!SearchManager.conditionObj.keywords) return;
		
		var keywords = SearchManager.conditionObj.keywords.split(",");
		var len = keywords.length;
		
		if(len == 0 ) return;
		
		this.container.style.display = "";
		for(var i = 0; i < len; i++){
			var data = keywords[i].split(":");
			var key = data[1].split("\"")[1];
			var incFlg = (data[0] == "i") ? true : false;
			this.addKeyword(key, incFlg);
		}
		
		//set listeners
		var self = this;
		var lists = this.container.getElementsByTagName("LI");
		len = lists.length;
		for(i = 0; i < len; i++){
			var list = lists[i];
			list.onclick = function(e){
				var target;
				if(!e) target = window.event.srcElement;
				else target = e.target;
				trace($(this).children(".jscls-closeKeyword")[0]);
				if(target == $(this).children(".jscls-closeKeyword")[0]){
					self.removeKeyword(this);
				}
			}
			
			list.onmouseover = function(e){
				trace("list over");
				var offset = $(this).offset();
				self.popup.open(this, offset.left, offset.top + 15);
			}
			
			list.onmouseout = function(e){
				trace("list out");
				self.popup.close();
			}
		}
		
		this.popup.resetOptions();
	},
	
	clearKeywords:function(){
		this.popup.close();
		this.container.style.display = "none";
		this.listContainer.innerHTML = "";
	},
	
	addKeyword:function(keyword, incFlg){
		var className, html;
		if(!incFlg){
			className = ResultConfig.CLS_SEARCH_KEYWORD + " " + FixedValues.CLS_DRAGGABLE_EXC_KEYWORD;
			html = TemplateManager.setTemplate(ResultConfig.HTML_EXC_KEYWORD,{keyword:keyword, className:className});
		}
		else{
			className = ResultConfig.CLS_SEARCH_KEYWORD + " " + FixedValues.CLS_DRAGGABLE_INC_KEYWORD;
		   	html = TemplateManager.setTemplate(ResultConfig.HTML_INC_KEYWORD,{keyword:keyword, className:className});
		}
		this.listContainer.innerHTML += html;
	},
	
	removeKeyword:function(target){
		target.onclick = null;
		target.onmouseover = null;
		target.onmouseout = null;
		this.listContainer.removeChild(target);
		
		var keyword = target.getElementsByTagName("STRONG")[0].innerHTML;
		
		SearchManager.assocRemoveKeySearch(keyword);
	},
	
	resetPopupSelect:function(){
		this.popup.resetOptions();
	}
}



var ResultElementPrototype = {
	id:null,
	type:null,
	title:null,
	shortTitle:null,
	menuStr:null,
	menu:null,
	content:null,
	
	getImageTitle:function(){
		return this.title.replace(/<\/*.+>|"/gi,"");
	},
	
	getColors:function(){
		if(!ShelfManager.shelfData || !ShelfManager.shelfData.shelves) return "";
		var shelves = ShelfManager.shelfData.shelves;
		
		var len = shelves.length;
		var colorStr = "";
		
		for(var i = 0; i < len; i++){
			var shelf = shelves[i];
			var elemLen = (shelf.elements) ? shelf.elements.length : 0;
			for(var j = 0; j < elemLen; j++){
				var elem = shelf.elements[j];
				if(elem.id == this.id){
					var color = ResultConfig.IMG_ELEMENT_COLOR_ARR[shelf.color];
					colorStr += TemplateManager.setTemplate(ResultConfig.HTML_ELEMENT_COLOR, {src:color, alt:shelf.name});
					break;
				}
			}
		}
		
		return colorStr;
	},
	
	getPublisher:function(publishers){
		if(!publishers) return "";
		var publisherStr = "";
		var publisherLen = publishers.length;
		for(var i = 0; i < publisherLen; i++){
			var publisher = publishers[i];
			//var name = publisher.name.split("").join(String.fromCharCode(8203));
			var name = getWrapText(publisher.name);
			publisherStr += name;
			if(i != publisherLen - 1) publisherStr += ",&nbsp;";
		}
		return publisherStr;
	},
	
	getDescriptionText:function(str){
		if(!str) return "";
		var returnStr;
		var place = arguments.callee.place;
		
		if(place == null){
			place = function(targ){
				if(targ == "<b>" || targ == "</b>") return targ;
				return "";
			}
		}
		
		if(str.constructor != String) str = String(str);
		//returnStr = str.replace(/<\/*[^<>"']+(\s[^<>"']+=['"][^'"]*['"])*>/g,place);
		returnStr = str.replace(/<\/*[a-zA-Z]+(\s[^<>"']+=['"][^'"]*['"])*>/g,place);
		
		return returnStr;
	},
	
	reloadColors:function(){
		var colors = getElementsByTagAndClass("P", "set-Colorz", this.content)[0];
		colors.innerHTML = this.getColors();
	},
	
	setSummary:function(summaryFlg){
		if(this.type == 0) this._setAuthor(summaryFlg);
		else if(this.type == 1) this._setCreators(summaryFlg);
		this._setPublishDetail(summaryFlg);
		this._setTitle(summaryFlg);
	},
	
	_setCreators:function(summaryFlg){
		if(!this.creators || this.creators.length == 0) return;
		
		var creatorsArea = getElementsByTagAndClass("EM", ResultConfig.CLS_RESULT_CREATORS, this.content)[0];
		var creatorLen = this.creators.length;
		var creatorStr = "";
		for(var i = 0; i < creatorLen; i++){
			var creator = this.creators[i];
			var name = getWrapText(creator.name);
			creatorStr += '<a href="javascript:linkToDetail(\''+ creator.url + '\');">' + name + '</a>';
			if(i != creatorLen - 1) creatorStr += ",&nbsp;";
			if(!summaryFlg && i == FixedValues.MAX_CREATOR_NUM && i != creatorLen - 1){
				creatorStr += "他" + Number(creatorLen - FixedValues.MAX_CREATOR_NUM) + "名";
				break;
			}
		}
		
		creatorsArea.innerHTML = creatorStr;
	},
	
	_setAuthor:function(){
		if(!this.author) return;
		var authorArea = getElementsByTagAndClass("EM", ResultConfig.CLS_RESULT_CREATORS, this.content)[0];
		
		authorArea.innerHTML = (this.author) ? this.author : "";
	},
	
	_setPublishDetail:function(flg){
		if(this.className != FixedValues.CLS_DRAGGABLE_BOOK) return;
		
		var detail = getElementsByTagAndClass("SPAN", ResultConfig.CLS_PUBLISH_DETAIL, this.content)[0];
		if(!detail) return;
		detail.style.display = (flg) ? "" : "none";
	},
	
	_setTitle:function(summaryFlg){
		var titleElem = getElementsByTagAndClass("A", FixedValues.CLS_DRAGGABLE_TITLE, this.content)[0];
		titleElem.innerHTML = "";
		if (summaryFlg) titleElem.innerHTML = getWrapText(this.title);
		else {
			this.shortTitle = (this.title.length < 60) ? getWrapText(this.title) : getWrapText(this.title, 60) + "…";
			
			if (this.shortTitle) {
				titleElem.innerHTML = this.shortTitle;
			}
		}
		
		//if (this.career && this.career != "") 
		//	titleElem.innerHTML += "(" + this.career + ")";
	}
}


/**
* a class which has result info
**/
var BookResultElement = function(obj, photoFlg, summaryFlg){
	if(!obj) new Error("no parameters");
	
	this.id = obj.id;
	this.type = 0;
	//this.title = obj.title.split("").join(String.fromCharCode(8203));
	this.title = obj.title;
	this.content = document.createElement("TD");
	this.className = FixedValues.CLS_DRAGGABLE_BOOK;
	this.creators = obj.creators;
	this.author = obj.author;
	
	var templateObj = {
		//id				:obj.id,
		colors			:this.getColors(),
		url				:obj.url,
		description		:this.getDescriptionText(obj.description),
		photoDisplay	:(photoFlg) ? "" : "none",
		image			:TemplateManager.setTemplate(ResultConfig.HTML_ELEMENT_IMAGE, {
											  title		:this.getImageTitle(),
											  url		:obj.url,
											  image_url	:(obj.image_url || obj.img_url == "") ? obj.image_url : FixedValues.IMG_NOWPRINTING
											  }),
		publish			:TemplateManager.setTemplate(ResultConfig.HTML_ELEMENT_PUBLISH, {
											detailClass		:ResultConfig.CLS_PUBLISH_DETAIL,
											publishers	:this.getPublisher(obj.publishers),
											publication_date:obj.publication_date,
											edition			:obj.edition,
											quantity		:obj.quantity,
											size			:obj.size,
											detailDisplay	:(summaryFlg) ? "" : "none"
											})
	}
	
	this.content.id = obj.id;
	this.content.className = ResultConfig.CLS_RESULT_TD + " "+FixedValues.CLS_DRAGGABLE_BOOK;
	this.content.innerHTML = TemplateManager.setTemplate(ResultConfig.HTML_ELEMENT, templateObj);	
}

BookResultElement.prototype = ResultElementPrototype;


var WorksResultElement = function(obj, photoFlg, summaryFlg){
	if(!obj) new Error("no parameters");

	this.id = obj.id;
	this.type = 1;
	//this.title = obj.title.split("").join(String.fromCharCode(8203));
	this.title = obj.title;
	this.content = document.createElement("TD");
	this.className = FixedValues.CLS_DRAGGABLE_WORKS;
	this.creators = obj.creators;
	
	var templateObj = {
		colors:this.getColors(),
		url:obj.url,
		description:this.getDescriptionText(obj.description),
		book_total:obj.book_total
	}
	
	this.content.id = obj.id;
	this.content.className = ResultConfig.CLS_RESULT_TD + " " + FixedValues.CLS_DRAGGABLE_WORKS;
	this.content.innerHTML = TemplateManager.setTemplate(ResultConfig.HTML_WORKS_ELEMENT, templateObj);	
}

WorksResultElement.prototype = ResultElementPrototype;


var PersonResultElement = function(obj, photoFlg, summaryFlg){
	if(!obj) new Error("no parameters");

	this.id = obj.id;
	this.type = 2;
	this.title = obj.name;
	this.content = document.createElement("TD");
	this.className = FixedValues.CLS_DRAGGABLE_PERSON;
	
	var publish = (obj.lifetime) ? obj.lifetime : "";
	if(obj.career && obj.career != "") publish += "<br />" + obj.career; 
	
	var templateObj = {
		colors:this.getColors(),
		url:obj.url,
		description:this.getDescriptionText(obj.description),
		photoDisplay	:(photoFlg) ? "" : "none",
		image:TemplateManager.setTemplate(ResultConfig.HTML_ELEMENT_IMAGE, {
										  title:this.getImageTitle(),
										  url:obj.url,
										  image_url:(obj.image_url || obj.img_url == "") ? obj.image_url : ResultConfig.IMG_NOWPRINTING
										  }),
		publish:publish
	}
	
	this.content.id = obj.id;
	this.content.className = ResultConfig.CLS_RESULT_TD + " " + FixedValues.CLS_DRAGGABLE_PERSON;
	this.content.innerHTML = TemplateManager.setTemplate(ResultConfig.HTML_ELEMENT, templateObj);	
}

PersonResultElement.prototype = ResultElementPrototype;




var MainResultConfig = {
	EXCEPT_LEFT_AREA_WIDTH:285,
	MIN_WINDOW_WIDTH:990
}


/**
* a class which operates center result area
**/
var MainResult = function(){
	this.columnNum;
	this.resultMoreNum 	= ResultConfig.DEFAULT_MORE_ROW_NUM * this.columnNum;
	this.totalNum		= 0;
	this.photoFlg		= true;
	this.summaryFlg		= false;
	this.resultOver		= false;
	this.tdWidth		= 33;
	this.resultArr		= new Array();
	this.leftArea		= document.getElementById(ResultConfig.ID_LEFT_AREA);
	this.container		= document.getElementById(ResultConfig.ID_MAIN_AREA);
	this.listContainer	= document.getElementById(ResultConfig.ID_MAIN_LIST);
	this.errorArea		= document.getElementById(ResultConfig.ID_MAIN_ERROR);
	this.displayOption	= document.getElementById(ResultConfig.ID_DISPLAY_OPTION);
	this.displayPhoto	= document.getElementById(ResultConfig.ID_DISPLAY_PHOTO);
	this.displaySummary	= document.getElementById(ResultConfig.ID_DISPLAY_SUMMARY);
	this.displayOrder	= document.getElementById(ResultConfig.ID_DISPLAY_ORDER);
	this.totalArea		= document.getElementById(ResultConfig.ID_TOTAL_AREA);
	this.moreBtn		= document.getElementById(ResultConfig.ID_MORE_BTN);
	this.moreLoading	= document.getElementById(ResultConfig.ID_MORE_LOADING);
	this.popup			= new PopupSelectBox(ResultConfig.ID_MAIN_POPUP);
	this.loading		= getElementsByTagAndClass("div", ResultConfig.CLS_LOADING, this.container)[0];
	
	this.MIN_TD_WIDTH	= 235;
	this.MIN_POPUP_POS	= 275;
	this.RESULT_ROW_NUM = 5;
	this.leftAreaWidth = $(window).width() - MainResultConfig.EXCEPT_LEFT_AREA_WIDTH;
	
	this.displayPhoto.getElementsByTagName("INPUT")[0].checked = true;
	this.displaySummary.getElementsByTagName("INPUT")[0].checked = false;
	this.totalArea.style.display		= "none";
	this.displayOption.style.display	= "none";
	this.displayOrder.style.display		= "none";
	this.loading.style.display			= "none";
	this.errorArea.style.display		= "none";
	this.moreLoading.style.display		= "none";
	
	var selects = this.displayOrder.getElementsByTagName("SELECT");
	this.bookOrder = selects[0];
	this.worksOrder = selects[1];
	this.personOrder = selects[2];
	
	this.bookOrder.selectedIndex = 0;
	this.worksOrder .selectedIndex = 0;
	this.personOrder.selectedIndex = 0;
	
	this.setListener();
	this.calcResultNum();
}

MainResult.prototype = {
	setListener:function(){
		var self = this;
		this.displayPhoto.getElementsByTagName("INPUT")[0].onclick = function(){
			self.photoFlg = !self.photoFlg;
			this.checked = self.photoFlg;
			self.changeDisplayPhoto();
		}
		
		this.displaySummary.getElementsByTagName("INPUT")[0].onclick = function(){
			self.summaryFlg = !self.summaryFlg;
			this.checked = self.summaryFlg;
			self.calcResultNum();
		}
		
		this.moreBtn.onclick = function(){
			this.style.display = "none";
			self.moreLoading.style.display = "";
			if(GlobalValues.searchMode == SearchMode.ASSOC){
				SearchManager.assocMoreSearch(self.resultMoreNum);
			}else{
				SearchManager.matchMoreSearch(self.resultMoreNum);
			}
		}
		
		this.bookOrder.onchange = function(){
			SearchManager.matchOrderSearch(this.options[this.selectedIndex].value);
		}
		
		this.worksOrder.onchange = function(){
			SearchManager.matchOrderSearch(this.options[this.selectedIndex].value);
		}
		
		this.personOrder.onchange = function(){
			SearchManager.matchOrderSearch(this.options[this.selectedIndex].value);
		}
		
		this.popup.onopen = function(){
			$(self.popup.target).addClass("hover");
		}
		
		this.popup.onclose = function(){
			$(self.popup.target).removeClass("hover");
		}
		
		this.popup.onareaout = function(){
			if(!self.resultOver) self.popup.close();
		}
			
		ResizeManager.addCallBack(self.calcResultNum, self);
	},
	
	calcResultNum:function(){
		var prevNum = this.columnNum;
		var windowWidth = $(window).width() > MainResultConfig.MIN_WINDOW_WIDTH ? $(window).width() : MainResultConfig.MIN_WINDOW_WIDTH;
		this.leftAreaWidth = windowWidth - MainResultConfig.EXCEPT_LEFT_AREA_WIDTH;
		this.columnNum = (this.summaryFlg) ? 1 : Math.floor(this.leftAreaWidth / this.MIN_TD_WIDTH);
		this.tdWidth = (this.summaryFlg) ? 100 : Math.floor(100 / this.columnNum);
		SearchManager.setResultNum(this.columnNum * this.RESULT_ROW_NUM);
		if(prevNum != this.columnNum){
			this._resizeResults();
		}
	},
	
	_resizeResults:function(){
		trace("resizeResults");
		var table = this.listContainer.getElementsByTagName("TABLE")[0];
		var tbody = this.listContainer.getElementsByTagName("TBODY")[0];
		var className = (this.summaryFlg) ? "table-B" : "table-A";
		var trs = $("."+ResultConfig.CLS_RESULT_TR);
		var len = Math.ceil(this.resultArr.length / this.columnNum) * this.columnNum;
		var odds = 0;
		var trIndex, tdIndex;
		
		if(!table) return;
		table.cellSpacing = 10;
		table.className = className;
		
		//clear contents of trs
		for(var i = 0; i < trs.length; i++){
			var cont = trs[i];
			for(var j = cont.childNodes.length - 1; j >= 0; j--){
				cont.removeChild(cont.childNodes[j]);
			}
		}
		
		for(var i = 0; i < len; i++){
			trIndex = Math.floor(i / this.columnNum);
			tdIndex = i % this.columnNum;
			var tr = trs[trIndex];
			
			if(!tr){
				var newTr = document.createElement("TR");
				newTr.className = ResultConfig.CLS_RESULT_TR;
				tbody.appendChild(newTr);
				trs[trIndex] = newTr;
				tr = newTr;
			}
			
			var element = this.resultArr[i];
			
			//set spacer
			if(!element){
				var newId = document.createElement("TD");
				newId.className = ResultConfig.CLS_RESULT_TD_SPACER + " "+ ResultConfig.CLS_RESULT_TD;
				newId.style.width = this.tdWidth + "%";
				newId.innerHTML = "&nbsp;";
				tr.appendChild(newId);
				odds++;
				continue;
			}
			
			element.setSummary(this.summaryFlg);
			element.content.style.width = this.tdWidth + "%";
			tr.appendChild(element.content);
		}
		
		//delete unwanted trs
		trIndex = Math.floor(len / this.columnNum);
		while(trIndex < trs.length){
			var deleteTr = trs[trIndex];
			deleteTr.parentNode.removeChild(deleteTr);
			trIndex++;
		}
		
		//set more number
		this.resultMoreNum = this.columnNum * this.RESULT_ROW_NUM + odds;
		if(this.resultMoreNum > this.totalNum - this.resultArr.length) this.resultMoreNum = this.totalNum - this.resultArr.length;
		
		var ems = this.totalArea.getElementsByTagName("em");
		ems[0].innerHTML = this.resultMoreNum;
	},
	
	//set associative search results
	setAssocResults:function(data, total){
		this.loading.style.display = "none";
		this.totalNum = total;
		this._setResults(data);
		this._setTotalNumber(data.length, total);
		this.openResults(0);
	},
	
	//set match search results
	setMatchResults:function(data,total){
		this.loading.style.display = "none";
		this.totalNum = total;
		this._setResults(data);
		this._setTotalNumber(data.length, total);
		this.openResults(0);
	},
	
	setErrorResults:function(content){
		// no result
		this.errorArea.style.display = "";
		$(this.errorArea).children("SPAN").html(TemplateManager.setTemplate(ResultConfig.TEXT_MAIN_ERROR, {content:content}));
	},
	
	//set more search results
	setMoreResults:function(data){
		var table = this.listContainer.getElementsByTagName("TBODY")[0];
		var trs = $("."+ResultConfig.CLS_RESULT_TR);
		var dLen = this.resultArr.length;
		
		var len = Math.ceil((dLen + data.length) / this.columnNum) * this.columnNum;
		for(var i = dLen; i < len; i++){
			var trIndex = Math.floor(i / this.columnNum);
			var tdIndex = i % this.columnNum;
			var tr = trs[trIndex];
			
			if(!tr){
				var newTr = document.createElement("TR");
				newTr.className = ResultConfig.CLS_RESULT_TR;
				table.appendChild(newTr);
				trs[trIndex] = newTr;
				tr = newTr;
			}
			
			var td = getElementsByTagAndClass("TD",ResultConfig.CLS_RESULT_TD, tr)[tdIndex];
			var resultData = data[i - dLen];
			
			//set spacer
			if(!resultData){
				var newId = document.createElement("TD");
				newId.className = ResultConfig.CLS_RESULT_TD_SPACER + " "+ ResultConfig.CLS_RESULT_TD;
				newId.style.width = this.tdWidth + "%";
				newId.innerHTML = "&nbsp;";
				tr.appendChild(newId);
				continue;
			}
			
			
			var element = this._getResultElement(resultData);
			//overwrite spacer
			if(td){
				if(td.className.indexOf(ResultConfig.CLS_RESULT_TD_SPACER) == -1){
					new Error("you're trying to overwrite wrong td");
				}
				
				element.content.style.width = this.tdWidth + "%";
				tr.insertBefore(element.content, td);
				tr.removeChild(td);
			}
			else{
				element.content.style.width = this.tdWidth + "%";
				tr.appendChild(element.content);	
			}
			
			element.setSummary(this.summaryFlg);
			this.resultArr.push(element);
		}
		
		this.openResults(dLen);
		this._setResultsListener();
		this._setTotalNumber(this.resultArr.length, this.totalNum);
	},
	
	
	_setTotalNumber:function(current, total){
		//set total number
		if(current >= total) this.moreBtn.style.display = "none";
		else this.moreBtn.style.display = "";
		this.moreLoading.style.display = "none";
		
		this.resultMoreNum = this.columnNum * this.RESULT_ROW_NUM;
		if(this.resultMoreNum > total - current) this.resultMoreNum = total - current;
		
		var strongs = this.totalArea.getElementsByTagName("strong");
		var ems = this.totalArea.getElementsByTagName("em");
		strongs[0].innerHTML = total;
		strongs[1].innerHTML = current;
		ems[0].innerHTML = this.resultMoreNum;
	},
	
	
	//set associative search results
	_setResults:function(data, total){
		if(!this.summaryFlg){
			this.columnNum = Math.floor(this.leftAreaWidth / this.MIN_TD_WIDTH);
			this.tdWidth = Math.floor(100 / this.columnNum);
		}
		
		var len = Math.ceil(data.length / this.columnNum) * this.columnNum;
		var tr;
		var table = document.createElement("TABLE");
		var tbody = document.createElement("TBODY");
		var className = (this.summaryFlg) ? "table-B" : "table-A";
		
		this.listContainer.appendChild(table);
		table.cellSpacing = 10;
		table.className = className;
		table.appendChild(tbody);
		
		for(var i = 0; i < len; i++){
			if(i % this.columnNum == 0){
				tr = document.createElement("TR");
				tr.className = ResultConfig.CLS_RESULT_TR;
				tbody.appendChild(tr);
			}
			if(i < data.length){
				var element = this._getResultElement(data[i]);
				element.content.style.width = this.tdWidth + "%";
				tr.appendChild(element.content);
				element.setSummary(this.summaryFlg);
				this.resultArr.push(element);
			}
			else{
				var td = document.createElement("TD");
				td.className = ResultConfig.CLS_RESULT_TD_SPACER + " " + ResultConfig.CLS_RESULT_TD;
				td.style.width = this.tdWidth + "%";
				td.innerHTML = "&nbsp;";
				tr.appendChild(td);
			}
		}
		
		this._setResultsListener();
		this.popup.resetOptions();
	},
	
	
	_setResultsListener:function(){
		var self = this;
		var results = $("."+ResultConfig.CLS_RESULT_TD);
		this._clearResultsListener();
		
		var mouseoverFunc = function(e){
			if($(this).hasClass(ResultConfig.CLS_RESULT_TD_SPACER) || $(this).css("opacity") != 1) return;
			
			self.resultOver = true;
			
			var offset = $(this).offset();
			var width	= $(this).width();
			var height = $(this).height();
			var popwidth = $(self.popup.content).width();
			var popheight = self.popup.height;
			var popupX, popupY;
			if(self.popup.target) $(self.popup.target).removeClass("hover");
			
			popupY = offset.top + height - popheight;
			popupX = (self.summaryFlg) 	? offset.left + 1 + width - popwidth : offset.left + 1;
			self.popup.open(this, popupX, popupY);
		}
		
		var mouseoutFunc = function(e){
			if($(this).hasClass(ResultConfig.CLS_RESULT_TD_SPACER)) return;
			
			self.resultOver = false;
			self.popup.close();
		}
		
		$("."+ResultConfig.CLS_RESULT_TD).mouseover(mouseoverFunc);
		$("."+ResultConfig.CLS_RESULT_TD).mouseout(mouseoutFunc);
	},
	
	_clearResultsListener:function(){
		$("."+ResultConfig.CLS_RESULT_TD).unbind("mouseover");
		$("."+ResultConfig.CLS_RESULT_TD).unbind("mouseout");
	},
	
	open:function(){
		this.displayOption.style.display = "";
		this.totalArea.style.display = "";
		
		var setOrder = function(targ, order){
			for(var i = 0; i < targ.options.length; i++){
				if (targ.options[i].value == order) {
					targ.selectedIndex = i;
					break;
				}
			}
		};
		
		//switch(GlobalValues.searchMode){
		switch(GlobalValues.resultType){
			//case SearchMode.ASSOC:
			case ResultType.ASSOC_BOOK:
				this.displayOrder.style.display = "none";
				this.displayPhoto.style.display = "";
				return;
			//case SearchMode.MATCH_BOOK:
			case ResultType.MATCH_BOOK:
				this.displayOrder.style.display = "";
				this.displayPhoto.style.display = "";
				this.bookOrder.style.display = "";
				this.worksOrder.style.display = "none";
				this.personOrder.style.display = "none";
				setOrder(this.bookOrder, SearchManager.conditionObj.order);
				return;
			//case SearchMode.MATCH_WORKS:
			case ResultType.MATCH_WORKS:
				this.displayOrder.style.display = "";
				this.displayPhoto.style.display = "none";
				this.bookOrder.style.display = "none";
				this.worksOrder.style.display = "";
				this.personOrder.style.display = "none";
				setOrder(this.worksOrder, SearchManager.conditionObj.order);
				return;
			//case SearchMode.MATCH_PERSON:
			case ResultType.MATCH_PERSON:
				this.displayOrder.style.display = "";
				this.displayPhoto.style.display = "";
				this.bookOrder.style.display = "none";
				this.worksOrder.style.display = "none";
				this.personOrder.style.display = "";
				setOrder(this.personOrder, SearchManager.conditionObj.order);
				return;
		}
	},
	
	
	close:function(){
		this.displayOption.style.display = "none";
		this.totalArea.style.display = "none";
		this.displayOrder.style.display = "none";
		this.displayPhoto.style.display = "none";
		this.bookOrder.style.display = "none";
		this.worksOrder.style.display = "none";
		this.personOrder.style.display = "none";
	},
	
	
	//open result elements
	openResults:function(start){
		var elements = $("."+ResultConfig.CLS_RESULT_TD);
		var len = elements.length;
		var count = start;
		for(var i = start; i < len; i++){
			$(elements[i]).css({opacity:0});
			var openElem = function(){
				var elem = elements[count];
				$(elem).animate({opacity:1}, 300);
				count++;
			}
			
			setTimeout(openElem, 100 * (i - start));
		}
	},
	
	changeDisplayPhoto:function(){
		var elements = $("."+ResultConfig.CLS_RESULT_TD);
		var len = this.resultArr.length;
		for(var i = 0; i < len; i++){
			var elem = elements[i];
			var image = getElementsByTagAndClass("TD",ResultConfig.CLS_SET_VIZ,elem)[0];
			image.style.display = (this.photoFlg) ? "" : "none";
		}
	},
	
	/*changeDisplaySummary:function(){
		this.columnNum = (this.summaryFlg) ? 1 :  Math.floor($(this.leftArea).width() / this.MIN_TD_WIDTH);
		this.tdWidth = (this.summaryFlg) ? 100 : Math.floor(100 / this.columnNum);
		
		this._resizeResults();
	},*/
	
	clearResults:function(){
		//$("."+ResultConfig.CLS_RESULT_TD).unbind("mouseover");
		//$("."+ResultConfig.CLS_RESULT_TD).unbind("mouseout");
		this._clearResultsListener();
		this.resultArr.length = 0;
		this.loading.style.display = "";
		this.loading.style.height = this.listContainer.offsetHeight + "px";
		this.totalArea.style.display = "none";
		this.errorArea.style.display = "none";
		this.listContainer.innerHTML = "";
	},
	
	changedShelfData:function(){
		var elemLen = this.resultArr.length;
		for(var i = 0; i < elemLen; i++){
			var elem = this.resultArr[i];
			elem.reloadColors();
		}
		this.popup.resetOptions();
	},
	
	
	_getResultElement:function(data){
		//trace(GlobalValues.searchMode);
		//switch(GlobalValues.searchMode){
		switch(GlobalValues.resultType){
			//case SearchMode.ASSOC:
			case ResultType.ASSOC_BOOK:
				return new BookResultElement(data, this.photoFlg, this.summaryFlg);
			//case SearchMode.MATCH_BOOK:
			case ResultType.MATCH_BOOK:
				return new BookResultElement(data, this.photoFlg, this.summaryFlg);
			//case SearchMode.MATCH_WORKS:
			case ResultType.MATCH_WORKS:
				return new WorksResultElement(data, this.photoFlg, this.summaryFlg);
			//case SearchMode.MATCH_PERSON:
			case ResultType.MATCH_PERSON:
				return new PersonResultElement(data, this.photoFlg, this.summaryFlg);
		}
	}
}


var KeyResultConfig = {
	ID_KEYWORD_AREA			:"jsid-resultKeywordArea",
	ID_KEYWORD_LIST			:"jsid-resultKeywordList",
	ID_KEYWORD_POPUP		:"jsid-resultKeywordPopup",
	ID_KEYWORD_INC_BTN		:"jsid-resultKeywordIncBtn",
	ID_KEYWORD_EXC_BTN		:"jsid-resultKeywordExcBtn",
	
	CLS_KEYWORD_ELEMENT		:"jscls-resultKeywordElement",
	CLS_KEYWORD_LABEL		:"jscls-resultKeywordLabel",
	
	HTML_KEYWORD_HEADER		:'<h3 class="#{className}">#{label}#{graph}</h3>',
							
	HTML_KEYWORD_GRAPH		:'<a href="javascript:void(0)" onclick="#{onclick}">'+
							'<img src="/externals/images/icn-mm-01.gif" alt="グラフを見る" width="13" height="13" class="indicator" />'+
							'</a>',
	
	ARR_EXC_GRAPH_LABEL		:["人物", "出版年", "行為", "その他"]
}

/**
*	a class which operates keyword area
**/
var KeywordResult = function(){
	this.incFlg			= true;
	this.container		= document.getElementById(KeyResultConfig.ID_KEYWORD_AREA);
	this.listContainer	= document.getElementById(KeyResultConfig.ID_KEYWORD_LIST);
	this.popup			= document.getElementById(KeyResultConfig.ID_KEYWORD_POPUP);
	this.incBtn			= document.getElementById(KeyResultConfig.ID_KEYWORD_INC_BTN).getElementsByTagName("INPUT")[0];
	this.excBtn			= document.getElementById(KeyResultConfig.ID_KEYWORD_EXC_BTN).getElementsByTagName("INPUT")[0];
	this.loading		= getElementsByTagAndClass("div", ResultConfig.CLS_LOADING, this.container)[0];
	this.error			= getElementsByTagAndClass("div", ResultConfig.CLS_SET_ERROR, this.container)[0];
	//this.graphForm		= document.forms[KeyResultConfig.NAME_GRAPH_FORM];
	
	this.currentKeyword = null;
	this.incBtn.checked = true;
	
	this.loading.style.display = "none";
	//this.graphForm.action = FixedValues.HREF_GRAPH;
	//this.graphForm.target = FixedValues.GRAPH_WINDOW;
	
	this.setListener();
}

KeywordResult.prototype = {
	setListener:function(){
		var self = this;
		
		$(this.listContainer).mouseout(function(){
			self.closePopup();
		});
		
		$(this.popup).mouseover(function(){
			self.openPopup();
		});
		
		$(this.popup).mouseout(function(){
			self.closePopup();
		});
		
		$(this.incBtn).click(function(e){
			self.incFlg = true;
			if(!self.currentKeyword) return;
			SearchManager.assocAddKeySearch(self.currentKeyword.innerHTML, true);
			self.closePopup();
		});
		
		$(this.excBtn).click(function(e){
			self.incFlg = false;
			if(!self.currentKeyword) return;
			SearchManager.assocAddKeySearch(self.currentKeyword.innerHTML, false);
			self.closePopup();
		});
	},
	
	setResults:function(data){
		this.loading.style.display = "none";
		if(!data || data.length == 0){
			this.error.style.display = "";
			return;
		}
		
		var len = data.length;
		var html = "";
		for(var i = 0; i < len; i ++){
			var keywordData = data[i];
			var keywordLen = keywordData.keyword ? keywordData.keyword.length : 0;
			var elemsHtml = "";
			var graphHtml = "";
			var graphFlg = true;
			var params = "";
			
			for(var j = 0; j < keywordLen; j++){
				var keyword = keywordData.keyword[j];
				elemsHtml += "<li class='" + KeyResultConfig.CLS_KEYWORD_ELEMENT + "'>" + keyword + "</li>";
				params += keyword;
				if(j != keywordLen - 1) params += ",";
			}
			
			//check exclude label list
			for(var k = 0; k < KeyResultConfig.ARR_EXC_GRAPH_LABEL.length; k++){
				if(KeyResultConfig.ARR_EXC_GRAPH_LABEL[k] == keywordData.label){
					graphFlg = false;
					break;
				}
			}
			//if graph icon should be showed
			if(graphFlg){
				graphHtml = TemplateManager.setTemplate(KeyResultConfig.HTML_KEYWORD_GRAPH,{
					onclick	: "javascript:linkToGraph('"+keywordData.label+"','"+params+"')"
				})
			}
			
			var header = TemplateManager.setTemplate(KeyResultConfig.HTML_KEYWORD_HEADER,{
													 label		: keywordData.label,
													 className	: KeyResultConfig.CLS_KEYWORD_LABEL,
													 graph		: graphHtml
													 });
													 
			html += "<li class='wcp-Csr-Pointer'>" + header +"<ul>" + elemsHtml + "</ul></li>";
		}
		this.listContainer.innerHTML = html;
		
		//set keywords listener
		var keywords = getElementsByTagAndClass("LI", KeyResultConfig.CLS_KEYWORD_ELEMENT, this.listContainer);
		var len = keywords.length;
		var self = this;
		for(var i = 0; i < len; i++){
			var keyword = keywords[i];
			$(keyword).mouseover(function(){
				if(self.currentKeyword) self.currentKeyword.style.background = "";
				
				var offset = $(this).offset();
				var height = $(this).height();
				self.popup.style.left = offset.left + 50 + "px";
				self.popup.style.top = offset.top + height +  "px";
				
				self.currentKeyword = this;
				self.openPopup();
			});
			
			$(keyword).click(function(){
				SearchManager.assocAddKeySearch(this.innerHTML, self.incFlg);
			});
		}
		
		//slide
		$("."+KeyResultConfig.CLS_KEYWORD_LABEL).click(function(e){
			if(e.target.tagName == "IMG"){
				return;
			}
			//$(this).next().toggle(400);
			toggleAnimate(this);
		});
	},
	
	clearResults:function(){
		$("."+KeyResultConfig.CLS_KEYWORD_LABEL).unbind("click");
		$("."+KeyResultConfig.CLS_KEYWORD_ELEMENT).unbind("click");
		$("."+KeyResultConfig.CLS_KEYWORD_ELEMENT).unbind("mouseover");
		this.closePopup();
		this.loading.style.display = "";
		this.error.style.display = "none";
		this.loading.style.height = this.listContainer.offsetHeight + "px";
		this.listContainer.innerHTML = "";
	},
	
	openPopup:function(){
		this.popup.style.display = "";
		if(this.currentKeyword) this.currentKeyword.style.background = "#dfd9cb";
	},
	
	closePopup:function(){
		this.popup.style.display = "none";
		if(this.currentKeyword) this.currentKeyword.style.background = "";
	},
	
	open:function(){
		this.container.style.display = "";
	},
	
	close:function(){
		this.container.style.display = "none";
	}
}




var WikipediaResult = function(){
	this.container 		= document.getElementById(ResultConfig.ID_WIKIPEDIA_AREA);
	this.listContainer	= document.getElementById(ResultConfig.ID_WIKIPEDIA_LIST);
	this.loading		= getElementsByTagAndClass("div", ResultConfig.CLS_LOADING, this.container)[0];
	this.error			= getElementsByTagAndClass("div", ResultConfig.CLS_SET_ERROR, this.container)[0];
	
	this.loading.style.display = "none";
}

WikipediaResult.prototype = {
	setResults:function(data){
		this.loading.style.display = "none";
		if(!data || data.length == 0){
			this.error.style.display = "";
			return;
		}
		
		var len = data.length;
		var html = "";
		for(var i = 0; i < len; i ++){
			html += TemplateManager.setTemplate(ResultConfig.HTML_WIKIPEDIA_ELEMENT,data[i]);
		}
		this.listContainer.innerHTML = html;
	},
	
	clearResults:function(){
		this.error.style.display = "none";
		this.loading.style.display = "";
		this.loading.style.height = this.listContainer.offsetHeight + "px";
		this.listContainer.innerHTML = "";
	},
	
	open:function(){
		this.container.style.display = "";
	},
	
	close:function(){
		this.container.style.display = "none";
	}
}




var DrilldownResult = function(){
	this.container		= document.getElementById(ResultConfig.ID_DRILLDOWN_AREA);
	this.listContainer	= document.getElementById(ResultConfig.ID_DRILLDOWN_LIST);
	this.loading		= getElementsByTagAndClass("div", ResultConfig.CLS_LOADING, this.container)[0];
	this.error			= getElementsByTagAndClass("div", ResultConfig.CLS_SET_ERROR, this.container)[0];
	this.drillArr		= new Array();
	
	this.loading.style.display = "none";
	this.container.style.display = "none";
}

DrilldownResult.prototype = {
	setResults:function(data){
		this.loading.style.display = "none";
		if(!data || data.length == 0){
			this.error.style.display = "";
			return;
		}
		
		var len = data.length;
		var html = "";
		for(var i = 0; i < len; i++){
			var drills = data[i];
			var len2 = drills.data.length;
			
			html += "<li>";
			html += TemplateManager.setTemplate(ResultConfig.HTML_DRILLDOWN_LABEL,{title:drills.title, className:ResultConfig.CLS_DRILLDOWN_LABEL});
			html += "<ul>";
			
			for(var j = 0; j < len2; j++){
				var drill = drills.data[j];
				var title = (drill.title) ? drill.title : drills.title + "分類なし";
				var id = ResultConfig.ID_DRILLDOWN_ELEMENT_PRE + i+j;
				var obj = {
					title:title,
					num:drill.count,
					className:ResultConfig.CLS_DRILLDOWN_ELEMENT,
					id:id
				}
				
				if(SearchManager.checkMatchDrilldown(drills.name, drill.value)){
					html += TemplateManager.setTemplate(ResultConfig.HTML_DRILLDOWN_ELEMENT_SELECTED, obj);
				}
				else{
					html += TemplateManager.setTemplate(ResultConfig.HTML_DRILLDOWN_ELEMENT, obj);
				}
				
				this.drillArr.push({id:id, name:drills.name, value:drill.value, title:drill.title});
			}
			
			html += "</ul></li>";
		}
		this.listContainer.innerHTML = html;
		
		
		//set listeners
		var elems = getElementsByTagAndClass("LI", ResultConfig.CLS_DRILLDOWN_ELEMENT, this.listContainer);
		var self = this;
		len = elems.length;
		for(i = 0; i < len; i++){
			elems[i].onclick = function(e){
				var target = (!e) ? window.event.srcElement : e.target;
				var nameValue = self._getDrilldownNameAndValue(this.id);
				
				if(target == this.getElementsByTagName("IMG")[0]){
					SearchManager.matchRemoveDrilldownSearch(nameValue.name, nameValue.value);
				}else{
					SearchManager.matchAddDrilldownSearch(nameValue.name, nameValue.value);
				}
			}
		}
		
		//slide
		$("."+ResultConfig.CLS_DRILLDOWN_LABEL).click(function(e){
			//$(this).next().toggle(400);
			toggleAnimate(this);
		});
	},
	
	clearResults:function(){
		$("."+ResultConfig.CLS_DRILLDOWN_LABEL).unbind("click");
		this.error.style.display = "none";
		this.loading.style.display = "";
		this.loading.style.height = this.listContainer.offsetHeight + "px";
		this.listContainer.innerHTML = "";
		this.drillArr.length = 0;
	},
	
	open:function(){
		this.container.style.display = "";
	},
	
	close:function(){
		this.container.style.display = "none";
	},
	
	_getDrilldownNameAndValue:function(id){
		var len = this.drillArr.length;
		for(var i = 0; i < len; i++){
			if(this.drillArr[i].id == id){
				return {name:this.drillArr[i].name, value:this.drillArr[i].value};
			}
		}
		return null;
	}
}


var PopupSelectBoxConfig = {
	ID_POPUP_TITLE	: "jsid-resultMainPopupTitle",
	CLS_OPTION_PRE	: "jscls-shelf"
	
}


//super class of popup box
var PopupSelectBox = function(id){
	this.content	= document.getElementById(id);
	this.titleElem	= document.getElementById(PopupSelectBoxConfig.ID_POPUP_TITLE);
	this.selectBox	= this.content.getElementsByTagName("ul")[0];
	this.submitBtn	= getElementsByTagAndClass("P", ResultConfig.CLS_RESULT_MENU_SUBMIT, this.content)[0];
	this.selectArr	= new Array();
	this.target		= null;
	this.bgDiv		= document.createElement("DIV");
	this.posX;
	this.posY;
	this.selectHeight;
	this.value;
	this.selectOpenFlg = false;
	this.currentOption = null;
	//this.width		= 0;
	this.height		= 28;
	
	this.onopen 	= null;
	this.onclose 	= null;
	this.onareaout	= null;
	
	this._observeFunc = function(){};
	
	this.content.style.display = "none";
	this.content.style.position = "absolute";
	this.content.style.zIndex = FixedValues.ZINDEX_POPUP;
	
	this.bgDiv.style.top		= $(this.selectBox).offset().top + "px";
	this.bgDiv.style.position	= "absolute";
	this.bgDiv.style.background	= "#ff0000";
	this.bgDiv.innerHTML		= "&nbsp";
	this.bgDiv.zIndex			= 10;
	$(this.bgDiv).css({opacity:0});
	
	this.content.parentNode.appendChild(this.bgDiv);
	
	this._setListener();
}

PopupSelectBox.prototype = {
	_setListener:function(){
		var self = this;
		
		this.content.onmouseover = function(){
			self.open(self.target, self.posX, self.posY);
		}
		
		this.submitBtn.onclick = function(){
			//var value = self.selectBox.options[self.selectBox.selectedIndex].value;
			var swf = getSwfElement(TopConfig.EXTERNAL_SHELF);
			var info = getElementInfo(self.target);
			if(self.value == "" || !self.value) return;
			
			trace(self.value);
			swf.addElement(self.value, info.type, info.title, info.id);
		}
		
		this.content.onmouseover = function(){
			self.open(self.target);
			
			//var optionLen = this.getElementsByTagName("li").length;
			//self.selectHeight = optionLen * self.height;
			self._startObserveMouse();
		}
		
	},
	
	_startObserveMouse:function(){
		var self = this;
		this._observeFunc = function(e){
			var mouseX, mouseY;
			mouseX = e.pageX;
			mouseY = e.pageY;
			
			//trace("observing");
			
			var offset = $(self.content).offset();
			var width = $(self.content).width();
			
			var xFlg = (offset.left < mouseX && mouseX < offset.left + width);
			var yFlg = (offset.top < mouseY && mouseY < offset.top + self.selectHeight);
			
			//when its out
			if(!xFlg || !yFlg){
				trace("**end observe");
				self._endObserveMouse();
				if(self.onareaout) self.onareaout();
			}
		}
		
		self._endObserveMouse();
		$(document).mousemove(this._observeFunc);
	},
	
	_endObserveMouse:function(){
		$(document).unbind("mousemove", this._observeFunc);
	},
	
	resetOptions:function(){
		//delete all options
		var self = this;
		while(this.selectBox.lastChild)
		{
			var targ = this.selectBox.lastChild;
			targ.onmouseover = null;
			targ.onmouseout = null;
			targ.onclick = null;
			this.selectBox.removeChild(this.selectBox.lastChild);
		}
		
		//create title element
		this.titleElem = document.createElement("li");
		this.titleElem.innerHTML = "<span>" + FixedValues.DEFUALT_SELECT_MSG + "</span>";
		this.selectBox.appendChild(this.titleElem);
		this.titleElem.onclick = function(){
			self.selectOpenFlg = !self.selectOpenFlg;
			if(self.selectOpenFlg) self.openOption();
			else self.closeOption();
		}
		
		//event handlers
		var optionOver = function(e){
			var strong = this.getElementsByTagName("strong")[0];
			if(self.currentOption) self.setHover(self.currentOption, false);
			self.setHover(strong, true);
			self.currentOption = strong;
		}
		var optionOut = function(e){
			trace("option out");
			//var strong = this.getElementsByTagName("strong")[0];
			//self.setHover(strong, false);
		}
		var optionClick = function(e){
			self._setTitle(this);
			self.closeOption();
		}
		
		
		//create first list
		var dOption = document.createElement("li");
		dOption.innerHTML = "<strong>" + FixedValues.DEFUALT_SELECT_MSG + "</strong>";
		this.selectBox.appendChild(dOption);
		dOption.onmouseover = optionOver;
		dOption.onmouseout = optionOut;
		dOption.onclick = optionClick;
		this._setOptionHover(dOption);
		
		var shelfLen = (!ShelfManager.shelfData || !ShelfManager.shelfData.shelves) ? 0 : ShelfManager.shelfData.shelves.length;
		for(var i = 0; i < shelfLen; i++){
			var shelf = ShelfManager.shelfData.shelves[i];
			
			var option = document.createElement("li");
			option.className = PopupSelectBoxConfig.CLS_OPTION_PRE + shelf.id;
			option.innerHTML = "<strong>" + shelf.name + "</strong>";
			
			option.onmouseover = optionOver;
			option.onmouseout = optionOut;
			option.onclick = optionClick;
			
			//trace(shelf.id + " " + this.value);
			if (shelf.id == this.value) {
				self._setTitle(option);
				self._setOptionHover(option);
			}
			
			this.selectBox.appendChild(option);
		}
		
		this.selectHeight = shelfLen * this.height;
	},
	
	_setOptionHover:function(option){
		var strong = option.getElementsByTagName("strong")[0];
		
		if(this.currentOption) this.setHover(this.currentOption, false);
		this.setHover(strong, true);
		this.currentOption = strong;
	},
	
	setHover:function(targ, active){
		if(active && !targ.className.match(/hover/)) targ.className += " hover";
		else if(!active && targ.className.match(/hover/)) targ.className = targ.className.replace(/\shover/, "");
	},
	
	
	_setTitle:function(targ){
		var exp = new RegExp(PopupSelectBoxConfig.CLS_OPTION_PRE + "|\\shover", "g");
		this.value = targ.className.replace(exp, "");
		trace(this.value);
		var title = targ.getElementsByTagName("strong")[0].innerHTML;
		
		this.titleElem.innerHTML = "<span>" + title + "</span>";
	},
	
	
	open:function(target,x,y){
		if(!target) throw new Error("Error");
		if(x) this.posX = x;
		if(y) this.posY = y;
		
		this.content.style.left = this.posX + "px";
		this.content.style.top = this.posY + "px";
		this.content.style.display = "";
		
		this.bgDiv.style.left = this.posX + "px";
		this.bgDiv.style.top = this.posY + "px";
		
		this.target = target;
		//this.target.appendChild(this.content);
		this._endObserveMouse();
		if(this.onopen) this.onopen();
	},
	
	
	close:function(){
		//trace(" | close");
		this.content.style.display = "none";
		this.bgDiv.style.display = "none";
		if(this.onclose) this.onclose();
	},
	
	
	openOption:function(){
		this.selectOpenFlg = true;
		this.setHover(this.selectBox, true);
		this.bgDiv.style.display = "none";
		
		var optionLen = this.content.getElementsByTagName("li").length;
		this.selectHeight = optionLen * this.height;
		/*
		var options = this.selectBox.getElementsByTagName("li");
		for(var i = 0; i < options.length; i++){
			var option = option[i];
			if(option.className == PopupSelectBoxConfig.CLS_OPTION_PRE + this.value){
				
				this.setHover(option,true);
			}
		}
		*/
		var self = this;
		$(document).click(function(e){
			if(!e) e = window.event;
			var offset = $(self.content).offset();
			var width = $(self.content).width();
			var height = $(self.content).height();
			var scrollLeft = ($('html').scrollLeft() != 0) ? $('html').scrollLeft() : $('body').scrollLeft();
			var scrollTop = ($('html').scrollTop() != 0) ? $('html').scrollTop() : $('body').scrollTop();
			
			var posX = e.clientX + scrollLeft;
			var posY = e.clientY + scrollTop;
			
			var horizontalFlg = (posX >= offset.left && posX <= offset.left + width);
			var verticalFlg = (posY >= offset.top && posY <= offset.top + height);
			
			if(horizontalFlg && verticalFlg) return;
			
			trace("close!!");
			self.closeOption.call(self);
		});
	},
	
	
	closeOption:function(){
		$(document).unbind("click");
		
		this.selectOpenFlg = false;
		this.setHover(this.selectBox, false);
		this.bgDiv.style.display = "";
		this.bgDiv.style.height = this.selectHeight + "px";
		this.bgDiv.style.width	= $(this.content).width() + "px";
	}
}


function toggleAnimate(targ){
	var next = $(targ).next();
	var currentHeight = next.height();
	
	if(targ.opened == undefined){
		targ.defaultHeight = currentHeight;
		targ.opened =true;
	}
	targ.opened = !targ.opened;
	
	next.stop();
	if(!targ.opened){
		next.css({overflow:"hidden"});
		next.animate({height:0});
	}else{
		var preHeight = targ.defaultHeight;
		next.animate({height:preHeight});
	}
}

