/**********************************************************************
* 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
***********************************************************************/
/*
 * Initiation procedures of Document Translation are defined in this file.
 */

//* ParallelTextクラスをここでも定義するのは納得がいかない
var ParallelText = Class.create();

var parallelTextSelection = null;
var parallelTextSearch = null;

var documentTranslation = null;
var translationLogDisplay = null;
var dictionarySelection = null;
var parallelTextSelection = null;
var documentTranslationWorkspace = null;
var serviceInformation = null;
var uploadAndDownload = null;

//* 以下2つは同一のものである
var userDictionary = null;
var editDictionary = null;

Event.observe(window,'load',function(){
	
	Toggler.setToggleEvent('edit-dictionary');
	Toggler.setToggleEvent('translation');
	Toggler.setToggleEvent('dictionary-selection');
	Toggler.setToggleEvent('parallel-text-selection');
	Toggler.setToggleEvent('setting');
	Toggler.setToggleEvent('service-information');
	
	new HelpPanel("translation",
		'Document Translation service allows you to translate structured documents while keeping the original document structure (line feed, itemization etc.).<br /><br />'
		+ '1. First, click the <span style="color:red;font-weight:bold;">Setup</span> button to go to the Setting panel, and set the source language, translator, and the target language.<br /><br />'
		+ '2. Copy and paste the original document into the upper left hand textbox on the Translation panel.<br /><br />'
		+ '3. Click the <span style="color:red;font-weight:bold;">Translate</span> button to start translating the whole document.<br /><br />'
		+ '4. When you wish to modify some part of the document, (1) click <img src="img/document-translation/marker_off.jpg" />, (2) highlight the sentence that you wish to modify by scraping the sentence, (3) rewrite the part that you wish to modify, and (4) click the <span style="color:red;font-weight:bold;">Translate</span> button to obtain translation and back-translation results.<br /><br />'
		+ '5. You can save the unfinished draft by clicking the <span style="color:red;font-weight:bold;">Save Log</span> button. To resume translation on the saved document, click the <span style="color:red;font-weight:bold;">Load Log</span> button and select the saved file and click Upload Log button.<br />');
		
	new HelpPanel("edit-dictionary",
		'<b>How to Create User Dictionary</b><br /><br />'
		+ 'This area displays a dictionary that you created.');

	new HelpPanel("dictionary-selection",
		'<span style="font-weight:bold;">How to Select Dictionary</span><br /><br />'+
		'Select dictionary you wish to use.'+
		'<br><span style="color:red;font-weight:bold;">Red</span> indicates that the dictionary is SELECTED.'+
		'<br><span style="color:green;font-weight:bold;">Green</span> indicates that the dictionary is NOT SELECTED.<br/>');

	new HelpPanel("parallel-text-selection",
		'<span style="font-weight:bold;">How to Select Parallel Texts</span><br /><br />'+
		'Select parallel texts you wish to search.'+
		'<br /><span style="color:orange;font-weight:bold;">Orange</span> indicates that the dictionary is SELECTED.'+
		'<br /><span style="color:blue;font-weight:bold;">Blue</span> indicates that the dictionary is NOT SELECTED.<br />');
	
	new HelpPanel("setting",
		'<span style="font-weight:bold;">How to Set Languages and Translators</span><br /><br />'+
		'Select the source language and target language for your translation task.'+
		'<br />If you want to perform a two-hop translation, check the <span style="font-weight:bold;">Enable further translation</span> box. '+
		'<br />After the languages and translator(s) are selected, click on the <span style="font-weight:bold;">OK</span> button to finalize the setting and return to the Translation panel.<br />');
	
	serviceInformation = new ServiceInformation('service-information-form-area');
	dictionarySelection = new ExclusiveDictionarySelection('dictionaries');
	parallelTextSelection = new ParallelTextSelection('parallel-texts');
	parallelTextSearch = new ParallelTextSearch('input-text','matching-method','from','to','result');
		
	var properties = {
		leftEditorId: 'original-textarea',
		rightEditorId: 'translation-textarea',
		messagePaneId: 'ajax-translation',
		buttonManager: {
			translateButtonId: 'translate-original',
			saveLogButtonId: 'download-log',
			loadLogButtonId: 'load-document',
			editorsExpansionButtonId: 'editor-expansion-button',
			editorsReductionButtonId: 'editor-reduction-button',
			cancelTranslationButtonId: 'cancel-translation-button'
		},
		selector: {
			lang1Id: 'lang1',
			lang2Id: 'lang2',
			lang3Id: 'lang3',
			translator1Id: 'trans1',
			translator2Id: 'trans2',
			checkBoxId: 'check_box',
			initialSourceLanguage: 'en',
			initialTargetLanguage: 'ja'
		},
		backtranslationManager: {
			backtranslationHeadId: 'backtranslation-head',
			backtranslationAreaId: 'backtranslation-area'
		}
	}
	documentTranslationWorkspace = new DocumentTranslationWorkspace(properties, parallelTextSearch);
	
	//* LOAD系イベント
	ExclusiveDictionarySelection.Event.load(dictionarySelection);
	$('use-all').checked = false;
	ParallelTextSelection.Event.load(parallelTextSelection);
	
	//* その他イベント
	//* 辞書選択
	dictionarySelection.getElement().down('table').observe('click',function(event){
		ExclusiveDictionarySelection.Event.clickButton(event,dictionarySelection);
		documentTranslationWorkspace.setLargeDictionaryId(dictionarySelection.getIdsOfSelectedResources());
	});
	dictionarySelection.getElement().down('table').observe('mouseover',function(event){
		ExclusiveDictionarySelection.Event.mouseoverButton(event,dictionarySelection);
	});
	dictionarySelection.getElement().down('table').observe('mouseout',function(event){
		ExclusiveDictionarySelection.Event.mouseoutButton(event,dictionarySelection);
	});
		
	//* 用例対訳選択
	parallelTextSelection.getElement().down('table').observe('click',function(event){
		ParallelTextSelection.Event.clickButton(event,parallelTextSelection);
		ParallelText.Event.clickResourceButton(event);
	});
	parallelTextSelection.getElement().down('table').observe('mouseover',function(event){
		ParallelTextSelection.Event.mouseoverButton(event,parallelTextSelection);
	});
	parallelTextSelection.getElement().down('table').observe('mouseout',function(event){
		ParallelTextSelection.Event.mouseoutButton(event,parallelTextSelection);
	});
	$('use-all').observe('click',function(event){
		ParallelTextSelection.Event.clickAllButton(event,parallelTextSelection);
		ParallelText.Event.clickResourceAllButton(event);
	});
	$('searching').style.display='none';
	
	//* 用例対訳検索
	parallelTextSearch.getWordArea().observe('keypress',function(event){
		ParallelText.Event.keypressOnWordArea(event);
	});
	$('search').observe('click',function(event){
		ParallelText.Event.clickSearchButton(event);
	});
	parallelTextSearch.getSourceLanguageMenu().getElement().observe('change',function(event){
		ParallelTextSearch.Event.changeSourceLanguage(event,parallelTextSearch);
		ParallelText.Event.changeSourceLanguage(event);
	});
	
	//* エリア拡大・縮小イベント
	$('sub-editor-expansion-button').observe('click', function(event){
		var para_area = $$('.parallet-texts')[0];
		para_area.setStyle({
		  height: (para_area.getHeight()+25)+'px'
		});
		$('result').setStyle({height: ($('result').getHeight()+29)+'px'})
		$('searching').setStyle({height: ($('searching').getHeight()+29)+'px'})
		$('backtranslation-area').setStyle({height: ($('backtranslation-area').getHeight()+25)+'px'})
	})
	$('sub-editor-reduction-button').observe('click', function(event){
		if ($('result').getHeight() < 50) {
			alert("You can not reduce the editor area anymore.");
			return;
		}
		var para_area = $$('.parallet-texts')[0];
		para_area.setStyle({
		  height: (para_area.getHeight()-25)+'px'
		});
		$('result').setStyle({height: ($('result').getHeight()-21)+'px'})
		$('searching').setStyle({height: ($('searching').getHeight()-21)+'px'})
		$('backtranslation-area').setStyle({height: ($('backtranslation-area').getHeight()-25)+'px'})
	})
	
	editDictionary = userDictionary = new EditDictionary();
	
	uploadAndDownload = new UploadAndDownload('upload-log', 'download-log',
		documentTranslationWorkspace, dictionarySelection, parallelTextSelection, userDictionary);
		
	//* ログのダウンロード
	
	$('download-form').observe('submit',function(event){
		uploadAndDownload.setValueToDownload('valueToDownloadLog');
	});
	

});

//*if(BrowserIdentifier.isIE() || BrowserIdentifier.isFF()){
//*	Event.observe(window, 'beforeunload', function(e) {
//*		if(e.target.id!='download-form')
//*    		return e.returnValue = 'If you close this window or move to another page, \nthe current translation results will be discarded.';
//*	});
//*}else if(BrowserIdentifier.isSafari() || BrowserIdentifier.isChrome()){
//*	window.addEventListener( 'beforeunload', function( aEvent ) {
//*		if(aEvent.target.id!='download-form')
//*	    	return aEvent.returnValue = 'If you close this window or move to another page, \nthe current translation results will be discarded.';
//*	}, false );
//*}

Event.observe(window,'unload',function(){ //* ここに定義すべきじゃないかも
	var isAsyn = true;
	if (BrowserIdentifier.isSafari() || BrowserIdentifier.isChrome()) {
		isAsyn = false;
	}
	new Ajax.Request(
	'./php/ajax/document-translation/end-session.php',
	{
		method		:'post',
		asynchronous: isAsyn
	});
});

ParallelText.Event = {
	clickSearchButton: function(event){
		if(parallelTextSearch.isEmptyWordArea()) {
			//* cancel
		} else if (parallelTextSearch.unselectedTargetLanguages()) {
			//* cancel
		} else {
			ParallelText.Ajax.search();
		}
	},
	
	keypressOnWordArea: function(event){
		if (event.keyCode == 13) {
			ParallelText.Event.clickSearchButton(event);
		}
	},
	
	changeSourceLanguage: function(event){
		parallelTextSearch.changeTargetLanguages(parallelTextSelection.getTargetLanguages(parallelTextSearch.getSelectedSourceLanguage()));
	},
	
	clickResourceButton: function(event){
		//* 用例の選択によらず、言語対はドキュメント翻訳を行う言語対に固定されるので、
		//* 資源のボタンがクリックされても元言語・対象言語は変化しない．（parallel-text-main から変更）
	},
	
	clickResourceAllButton: function(event){
		ParallelText.Event.clickResourceButton(event);
	}
}

ParallelText.Ajax = {
	search: function(){
		
		$('result').style.display='None';
		$('searching').style.display='Block';
		$('searching').innerHTML = '<div style="text-align:center;"><img src="img/anime/dictionary.gif" /> Searching...</div>';
				
		var callobj = {
			inputtext: parallelTextSearch.getWordArea().value.replace(/\r\n/g," ").replace(/\n/ig," "),
			from: parallelTextSearch.getSourceLanguageMenu().getSelectedLanguage(),
			toNum: parallelTextSearch.getTargetLanguageMenu().getSelectedLanguages().size(),
			idNum: parallelTextSelection.getIdOfSelectedResources().size(),
			matching: parallelTextSearch.getMatchingMethod().value
		};
		
		//* 翻訳先言語は、編集に関連している言語のうち、元言語でないもの（１つ or ２つ）
		menuLangs = parallelTextSearch.getSourceLanguageMenu().menuLanguages;
		//add start kawauchi 090926
		//チェックが入っていなくても翻訳先言語に２つ目をＰＯＳＴするバグを修正
		if(!$("check_box").checked) menuLangs.splice(2,1);
		//add end kawauchi090926
		numOfLangs = 0;
		for(var i=0;i<menuLangs.length;i++){
			if(callobj['from'] != menuLangs[i]){
				callobj['to'+numOfLangs++] = menuLangs[i];
			}
		}
		callobj['toNum'] = menuLangs.length-1;
		
		var selectedResourceIdArray = parallelTextSelection.getIdOfSelectedResources();
				
		if(selectedResourceIdArray.size() == 0){
			$('searching').innerHTML = '';
			$('searching').style.display='None';
			$('result').innerHTML = 'Please select at least one parallel-texts service <br /> from <span style="color:red">Parallel Text Selection</span> area.'
			$('result').style.display='Block';
			
			//mod start kawauchi 090925
			//heightが設定されているか判定し、エラーを回避
			//$('result').style.height=height;
			if(typeof(height)!="undefined") $('result').style.height=height;
			//mod end kawauchi 090925
			
			return;
		}
		
		for(var i=0; i < selectedResourceIdArray.size(); i++){
			callobj['id'+i] = selectedResourceIdArray[i];
		}
		var hash = $H(callobj);
		var formText=hash.toQueryString();
		new Ajax.Request(
			'./php/ajax/parallel-text/search-multiwords.php',
			{
				method		:'post',
				//* パラメータはinputtext,from,to,dic0,dic1,dic2,dic3,dic4,dic5
				parameters	:formText,
				onSuccess	:function(httpObj){
					parallelTextSearch.getResultArea().draw(httpObj.responseText,parallelTextSelection);
					//* ライセンス情報の横断検索
					for (var i=0; i< httpObj.responseJSON.contents.size();i++) {
						serviceInformation.update(httpObj.responseJSON.contents[i]);
					}
				},
				onFailure	:function(){
					alert('Server Error.');
				},
				onComplete	:function(){
					$('searching').innerHTML = '';
					$('searching').style.display='None';
					$('result').style.display = 'Block';
					$('result').style.height = height;
				}
			});
	}
}

