/**********************************************************************
* Copyright (C) 2007 Kyoto University
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* 
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-
* 1301  USA
***********************************************************************/
/*
 * This file is the component controller file for Pictogram selection
 * including layout and selector button functions.
 */
//* $Id: pictogram-selection.js 2567 2009-04-13 08:29:24Z morita $
//* $Date:: 2009-04-13 17:29:24 +0900#$

var PictogramSelection = Class.create();
var PictogramButton = Class.create();

PictogramSelection.Constant = {
	RESOURCE_BUTTON_HEADER_ID:'pictogram-button-',
	RESOURCE_BUTTON_NAME_HEADER_ID:"pictogram-name",
	RESOURCE_BUTTON_BALLOON_HEADER_ID:'pictogram-description-balloon-'
}

//* new した後にAjax.Requestにより入手したデータをloadPictogramDataで処理する必要がある
PictogramSelection.prototype = {
	initialize: function(id){
		this.id = id;
		this.resourceArray = new Array();
		this.allResourceInfo = null;
		this.mapId2Index = {};
	},
	
	//* 辞書のデータをロードする。
	//* @param {String} message
	loadResourceData: function(jsonMessage){
		var resultArray = eval("("+jsonMessage+")");
		var checker = new StatusProcessor(resultArray,
			"Playground Error : Pictogramのデータが得られませんでした.",
			"Playground Warning : Pictogramのデータの一部が得られませんでした.");
		if(!checker.check()) return;
		resultArray = resultArray.contents;
		
		//* 辞書ボタン作成
		var i=0;
		for(;i<resultArray.size();i+=1){
			this.resourceArray[i] = new PictogramButton(i,$H(resultArray[i]));
			this.mapId2Index[resultArray[i]['id']] = i;
		}
		
		//* 説明のDIVをBODYに投げる
		i=0;
		for(;i<this.resourceArray.size();i+=1){
			var oDiv = document.createElement('div');
			oDiv.id = PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID + i;
			oDiv.setAttribute('onmouseover', 'this.show();');
			oDiv.setAttribute('onmouseout', 'this.hide();');
			oDiv.style.visibility = 'hidden';
			new Insertion.Bottom($$('body')[0],oDiv);
			this.resourceArray[i].updateInfo();
			
			$(PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID+i).hide();
		}
		
		var insertHTML = '';
		i=0;
		for(;i<this.resourceArray.size();i+=1){
			if(i%5 == 0) insertHTML += '<tr class="pictogram">';
			insertHTML += '<td>';
			insertHTML += this.resourceArray[i].getHTML();
			insertHTML += '</td>';
			if(i%5 == 4 || i == this.resourceArray.size()-1) insertHTML += '</tr>';
		}
		new Insertion.Bottom($(this.id).down('table'),insertHTML);
	
		//* サービスプロファイルをロードする
		var param = $H(this.mapId2Index)
		.keys() //* serviceId の配列に
		.select((function(id, index){
			var isLanguageGridService = resultArray[this.mapId2Index[id]]['isLanguageGridService'];
			return typeof(isLanguageGridService) != 'undefined' && isLanguageGridService > 0;
		}).bind(this))
		.map(function(id, index){ return 'ids[]=' + id; }) //* ids[]=id という文字列の配列に
		.join('&');

		new Ajax.Request(
			'./php/ajax/load-service-profiles.php',
			{
				method: 'post',
				parameters: param,
				onSuccess: (function(httpObj){
					this.loadProfileData(httpObj.responseText);
				}).bind(this),
				onFailure: function(){ alert('Server Error.'); }
			}
		);
	},
	
	//* サービスのプロファイルをロードする
	loadProfileData: function(jsonMessage){
		var resultArray = eval("("+jsonMessage+")");
		var checker = new StatusProcessor(resultArray, "Playground Error : Can't obtain information about dictionaries.");
		checker.warning = function(){return true;};
		if(!checker.check()) return;
		resultArray = $H(resultArray.contents);

		var selection = this;
		resultArray.keys().each(function(id){
			var profile = resultArray.get(id);
			var aryLimit = profile['AccessLimits'];
			if (aryLimit['status'] != 'OK') return;
			aryLimit = aryLimit['contents'];

			if (aryLimit.size() == 0) return;

			var limitInfo = [];
			aryLimit.each(function(limit){
				limitInfo.push(limit);
			});

			//* プロファイルを更新する
			var button = selection.resourceArray[selection.mapId2Index[id]];
			button.addLimitInfo(limitInfo);
			button.updateInfo();
		});
	},
	
	//* 辞書の総数を返す
	getArrayOfResources: function(){
		return this.resourceArray;
	},
	
	//* IDを返す
	getId: function(){
		return this.id;
	},
	
	//* DOM要素を返す
	getElement: function(){
		return $(this.id);
	},
	
	getSourceLanguages: function(){
		var sourceLanguages = new Array();
		this.getArrayOfResources().each(function(d){
			if(d.isSelected()){
				d.getLanguages().each(function(p){
					if(sourceLanguages.indexOf(p) == -1){
						sourceLanguages.push(p);
					}
				});
			}
		});
		return sourceLanguages;
	},
	
	getUrlOfSelectedResources: function(){
		var wsdlArray = new Array();
		this.getArrayOfResources().each(function(d){
			if(d.isSelected()) wsdlArray.push(d.getUrl());
		});
		return wsdlArray;
	},
	
	getIdOfSelectedResources: function(){
		var wsdlArray = new Array();
		this.getArrayOfResources().each(function(d){
			if(d.isSelected()) wsdlArray.push(d.getId());
		});
		return wsdlArray;
	},
	
	hasSelectedResources: function(){
		for(var i=0;i<this.getArrayOfResources().size();i++){
			if(this.getArrayOfResources()[i].isSelected()) return true;
		}
		return false;
	},
	
	getResourceNameFromWsdlUrl: function(wsdlUrl){
		for(var i=0;i<this.getArrayOfResources().size();i++){
			if(this.getArrayOfResources()[i].getUrl() == wsdlUrl)
				return this.getArrayOfResources()[i].getName();
		}
		return null;
	},
	
	getResourceNameFromId: function(resourceId){
		for(var i=0;i<this.getArrayOfResources().size();i++){
			if(this.getArrayOfResources()[i].getId() == resourceId)
				return this.getArrayOfResources()[i].getName();
		}
		return null;
	},
	
	getUrlFromId: function(resourceId){
		for(var i=0;i<this.getArrayOfResources().size();i++){
			if(this.getArrayOfResources()[i].getId() == resourceId)
				return this.getArrayOfResources()[i].getUrl();
		}
		return null;
	},
	
	//* ボタンにマウスが乗ったときのアクション
	//* @param {Number} number
	//* @param {Number} x
	//* @param {Number} y
	onMouseOverAction: function(number,x,y){
		this.resourceArray[number].showIllustration(x,y);
	},
	
	//* ボタンからマウスが離れたときのアクション
	//* @param {Number} number
	onMouseOutAction: function(number){
		this.resourceArray[number].hideIllustration();
	},
	
	//* ボタンがクリックされたときのアクション
	//* @param {Number} number
	onClickAction: function(number){
		this.resourceArray[number].toggleState();
	}
};

PictogramButton.prototype = {
	initialize: function(number,hashData){
		this.number = number;
		this.hashData = hashData;
		this.selected = false;
	},
	
	//* 活性/非活性の状態を入れ替える
	toggleState: function(){
		if(this.isSelected()){
			this.deactivate();
		} else {
			this.activate();
		}
	},
	
	//* 活性化した状態の表示
	//* @param {Number} x
	//* @param {Number} y
	showIllustration: function(x,y){
		$(PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID+this.number).setStyle({
			position : 'absolute' ,
			visibility: 'visible',
			left : x+'px' ,
			top : y+'px' 
		});
		$(PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID+this.number).show();
	},
	
	//* 非活性化した状態の表示
	hideIllustration: function(){
		$(PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID+this.number).hide();
	},
	
	getUrl: function(){
		return this.hashData.get('url');
	},
	
	getName: function(){
		return this.hashData.get('name');
	},
	
	//* IDを返す
	getId: function(){
		return this.hashData.get('id');
	},
	
	//* 活性化した状態の表示
	activate: function(){
		this.selected = true;
		$(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID+this.number).removeClassName('unselected');
		$(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID+this.number).addClassName('selected');
	},
	
	//* 非活性化した状態の表示
	deactivate: function(){
		this.selected = false;
		$(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID+this.number).addClassName('unselected');
		$(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID+this.number).removeClassName('selected');
	},
	
	//* 選択の状態を得る
	isSelected: function(){
		return this.selected;
	},
	
	//* 辞書を示すボタンのHTML文を返す
	getHTML: function(){
		return '<div class="unselected sources" id="'+PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID+this.number+'"><div class="source-name" id="'+PictogramSelection.Constant.RESOURCE_BUTTON_NAME_HEADER_ID+this.number+'">'+this.hashData.get('name')+'</div></div>';
	},
	
	//* 辞書の説明文のHTML文を返す
	getLayer: function(){
		//* Access limits edit
		//*var languages = $H(this.hashData.get('languages')).values();
		var languages = this.hashData.get('supportedLanguages');
		var info = '';
		for(var i=0;i<languages.size();i++){
			info += Language.getNameByTag(languages[i][0]);
			if(i != languages.size()-1) info += "<br />";
		}
		var popupClass = '';
		if(this.number % 5 > 2) popupClass = 'balloon bottom-right';
		else popupClass = 'balloon bottom-left';
		//*Access limits del
		//*var illustration = '<div id="'+PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID+this.number+'" onmouseover="this.show();" onmouseout="this.hide();" style="visibility:hidden;"><div class="'+popupClass+'">'+
						
						//* add for AccessLimits by morimoto
						var illustration = '<div class="'+popupClass+'">'+
						//* end for AccessLimits by morimoto
						
							'<div class="top iepngfix"></div>'+
							'<div class="comment iepngfix">'+
							'<h4>NAME</h4>'+
							this.hashData.get('name')+'<br />'+
							'<h4>Supported Languages</h4>'+
							'<div class="supported-language-pairs">'+
							info+
							'</div>';
		//* Access limits del
		//*if(this.getUrl() != "") illustration+='<h4>URL</h4>'+
		//*					'<a href="'+this.hashData.get('url')+'">'+this.hashData.get('url').truncate(40)+'</a>';
		
		//* add for AccessLimits by morimoto
		var data;
		data = this.hashData.get('url');
		if(data) {
			illustration += '<h4>URL</h4><a href="' + data + '">' + data.truncate(40) + '</a>';
		}
		data = this.hashData.get('limits');
		if(data) {
			illustration += '<h4>Access Limits</h4>';
			data.each(function(limitInfo){
				illustration += '<table><tbody>'
				+ '<tr><td>Start</td><td>' + limitInfo['startDateTime'] + '</td></tr>'
				+ '<tr><td>End</td><td>' + limitInfo['endDateTime'] + '</td></tr>'
				+ '<tr><td>Limit</td><td>' + limitInfo['limitInfo'] + '</td></tr>'
				+ '</tbody></table>';
			});
		}
		//* end for AccessLimits by morimoto
		//* Access limits del
		//*illustration+='</div><div class="bottom iepngfix"></div></div></div>';
		
		//* add for AccessLimits by morimoto
		illustration+='</div><div class="bottom iepngfix"></div></div>';
		//* end for AccessLimits by morimoto
		
		return illustration;
	},
	
	//* add for AccessLimits by morimoto
	updateInfo: function(){
		Element.update($(PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID+this.number), this.getLayer());
	},

	addLimitInfo: function(aryLimitInfo){
		this.hashData.set('limits', aryLimitInfo);
	},
	//* end for AccessLimits by morimoto
	
	getLanguages: function(){
		return this.hashData.get('path');
	},
	
	//* サポート言語対の情報のHTMLを返す
	getPairInfo: function(){
		var pairArray = $H(this.hashData.get('path')).values();
		var pairInfo = '';
		var bidirectionalPairArray = new Array();
		var monodirectionalPairArray = new Array();
		for(var i=0;i<pairArray.size();i++){
			var first = pairArray[i];
			var from = first.car();
			var to = first.cdr();
			var flag = false;
			for(var j=i+1;j<pairArray.size();j++){
				if(pairArray[j].car() == to && pairArray[j].cdr() == from){
					pairArray = pairArray.without(pairArray[j]);
					bidirectionalPairArray.push(new Pair(from,to));
					flag = true;
					break;
				}
			}
			if(!flag) monodirectionalPairArray.push(new Pair(from,to));
		}
		
		for(var i=0;i<bidirectionalPairArray.size();i++){
			pairInfo += Language.getNameByTag(bidirectionalPairArray[i].getFirst());
			pairInfo += ' <-> ';
			pairInfo += Language.getNameByTag(bidirectionalPairArray[i].getSecond());
			pairInfo += '<br />';
		}
		
		for(var i=0;i<monodirectionalPairArray.size();i++){
			pairInfo += Language.getNameByTag(monodirectionalPairArray[i].getFirst());
			pairInfo += ' -> ';
			pairInfo += Language.getNameByTag(monodirectionalPairArray[i].getSecond());
			pairInfo += '<br />';
		}
		
		return pairInfo;
	}
};

PictogramSelection.Event = {
	load: function(resourceSelection){
		new Ajax.Request(
			 './php/ajax/load-services.php',
			 {
				 method		:'post',
				 parameters	:'serviceCategory=pictogram',
				 onSuccess	:function(httpObj){
				 	resourceSelection.loadResourceData(httpObj.responseText);
					resourceSelection.getArrayOfResources().each(function(d){
						d.activate();
						PictogramSelection.Event.clickButton(null, resourceSelection);
					});
				 },
				 onFailure	:function(){
					alert('Server Error.');
				 }
			 }
		);
	},
	
	clickButton: function(event,resourceSelection){
		if (event) {
			var element = $(Event.element(event));
			if(element.id.startsWith(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID)){
				resourceSelection.onClickAction(parseInt(element.id.substring(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID.length)));
			} else if(element.id.startsWith(PictogramSelection.Constant.RESOURCE_BUTTON_NAME_HEADER_ID)){
				resourceSelection.onClickAction(parseInt(element.id.substring(PictogramSelection.Constant.RESOURCE_BUTTON_NAME_HEADER_ID.length)));
			}
		}

		this.updateLanguage(resourceSelection);
	},
	
	mouseoverButton: function(event,resourceSelection){
		function _get_position_of_ballon(element,number){
			var cellPosition = element.cumulativeOffset();
			var bodyPosition = $$('body')[0].cumulativeOffset();
			var x = cellPosition[0] - bodyPosition[0]+element.getWidth() -15;
			var y = cellPosition[1] - bodyPosition[1]+(element.getHeight())/2 - $(PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID+number).getHeight();
			if(number % 5 > 2) x = x - element.getWidth() - $(PictogramSelection.Constant.RESOURCE_BUTTON_BALLOON_HEADER_ID+number).getWidth()+40;
			return new Pair(x,y);
		}
		
  		var element = $(Event.element(event));
		if(element.id.startsWith(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID)){
			var number = parseInt(element.id.substring(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID.length));
			var positionPair = _get_position_of_ballon(element,number);
			resourceSelection.onMouseOverAction(number,positionPair.car(),positionPair.cdr());
		} else if(element.id.startsWith(PictogramSelection.Constant.RESOURCE_BUTTON_NAME_HEADER_ID)){
			element = element.up('div');
			var number = parseInt(element.id.substring(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID.length));
			var positionPair = _get_position_of_ballon(element,number);
			resourceSelection.onMouseOverAction(number,positionPair.car(),positionPair.cdr());
		}
	},
	
	mouseoutButton: function(event,resourceSelection){
		var element = $(Event.element(event));
		if(element.id.startsWith(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID)){
			resourceSelection.onMouseOutAction(parseInt(element.id.substring(PictogramSelection.Constant.RESOURCE_BUTTON_HEADER_ID.length)));
		} else if(element.id.startsWith(PictogramSelection.Constant.RESOURCE_BUTTON_NAME_HEADER_ID)){
			resourceSelection.onMouseOutAction(parseInt(element.id.substring(PictogramSelection.Constant.RESOURCE_BUTTON_NAME_HEADER_ID.length)));
		} 
	},
	
	clickAllButton: function(event,resourceSelection){
		var element = $(Event.element(event));
		var resourceArray = resourceSelection.getArrayOfResources();
		if(element.checked){
			resourceArray.each(function(d){d.activate();});
		} else {
			resourceArray.each(function(d){d.deactivate();});
		}

		this.updateLanguage(resourceSelection);
	},

	updateLanguage: function(resourceSelection) {
		var selector = $('language');
		while ( selector.firstChild ) selector.removeChild( selector.firstChild );
		resourceSelection.getSourceLanguages().each(function(lang){
			var oOpt = document.createElement( 'option' );
			oOpt.value = lang;
			oOpt.appendChild( document.createTextNode( Language.getNameByTag(lang) ) );
			selector.appendChild( oOpt );
		});
		selector.selectedIndex = 0;
	}
}

