/* $Id: SearchAllUtil.java 623 2013-01-10 12:40:07Z ohura $ */
package smart_gs.all_text_search;

import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import smart_gs.logical.UsersNote;
import smart_gs.logical.UsersNoteTree;
import smart_gs.logical.SmartDocument;
import smart_gs.logical.Spread;
import smart_gs.logical.SpreadTree;
import smart_gs.smleditor.swingui.SecondIDATPanel;
import smart_gs.smleditor.swingui.GSEditor;
import smart_gs.smleditor.swingui.GSEditorTextPane;
import smart_gs.smleditor.swingui.GSTabbedPane;
import smart_gs.smleditor.swingui.GSTreeTextEditor;
import smart_gs.smleditor.swingui.GSTreeTextEditortPaneManager;
import smart_gs.smleditor.swingui.IDATPanel;
import smart_gs.smleditor.swingui.FirstIDATPanel;
import smart_gs.smleditor.swingui.ThirdIDATPanel;
import smart_gs.spread_selection.SpreadSelector;
import smart_gs.swingui.GSTabbedPaneManager;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.text_search.logical.TextSearchConstants;
import smart_gs.util.StringUtils;

public class SearchAllUtil {
	protected int documentType;
	protected int spreadnumber;
	protected int textnumber;
	protected int tabnumber;
	protected JFrame currenteditor;
	protected int scope = 0;
	protected String spreadSelection;
	protected long replaceallcounter;
	
	public SearchAllUtil(int scope,String spreadSelection){
		this.scope = scope;
		this.spreadSelection = spreadSelection;
	}
	
	public void findfirst(int documentType_){
		documentType = documentType_;
		spreadnumber = 0;
		textnumber = 0;
		tabnumber = 0;
		if(!find(true,null,false)){
			JOptionPane.showMessageDialog(new JFrame(), "String Not Found", "Information", JOptionPane.INFORMATION_MESSAGE);
		}
	}

	public void setstart(){
		textnumber = 0;
		spreadnumber = 0;
		tabnumber =0;
	}
	
	public void setTextNumber(int textnumber){
		this.textnumber = textnumber;
	}
	public void setSpreadnumber(int spreadnumber){
		this.spreadnumber = spreadnumber;
	}
	public void setTabnumber(int tabnumber){
		this.tabnumber = tabnumber;
	}
	public void setCurrentEditor(JFrame currenteditor){
		this.currenteditor = currenteditor;
	}
	public boolean  nextrelaceall(){
		tabnumber++;
		boolean isFind = false;
		isFind = find(true,null,true);
		if(!isFind){
//			tabnumber = 0;
//			isFind = find(true,null,true);
		}
		return isFind;
	}
	
	public boolean relaceallnonewwindows(final String replace){
		replaceallcounter = 0;
		ArrayList<UsersNote> arrList = (ArrayList<UsersNote>) UsersNoteTree.getInstance().getUsersNotes();
		List<Spread> list = getSpreadsToSearch();
		if( documentType == TextSearchConstants.FIRSTIDAT ||
				documentType == TextSearchConstants.SECONDIDAT ||
				documentType == TextSearchConstants.THIRDIDAT ||
				documentType == TextSearchConstants.ALLDOCUMENT){
				for(int i=0;i<list.size();i++){
					Spread spread = list.get(i);
					if(spread == null){
						continue;
					}
					replaceallprocess(spread,replace);
				}
		}
		if(scope != 0){
			JOptionPane.showMessageDialog(SearchAllDialogManager.getDialog(), replaceallcounter + " matches replaced", "Information", JOptionPane.INFORMATION_MESSAGE);
			return false;
		}
		if(documentType == TextSearchConstants.TEXT || documentType == TextSearchConstants.ALLDOCUMENT){
			for(int i=0;i<arrList.size();i++){
				UsersNote usersNote = arrList.get(i);
				if(usersNote == null){
					continue;
				}
				replacealltextprocess(usersNote,replace);
			}
		}
		JOptionPane.showMessageDialog(SearchAllDialogManager.getDialog(), replaceallcounter + " matches replaced", "Information", JOptionPane.INFORMATION_MESSAGE);
		return false;
	}
	
	public List<Spread> getSpreadsToSearch(){
		if(scope == 0){
			return SpreadTree.getInstance().getSpreads();
		}
		else if(scope == 1){
			return SpreadTree.getInstance().getCurrentDirectory().getSpreads();
		}
		else if(scope == 2){
			SpreadSelector selector = new SpreadSelector( SpreadTree.getInstance().getSpreads(), spreadSelection);
			return selector.select();
		}
		return null;
	}
	
	
	public boolean next(final String replace){
		tabnumber++;
		boolean isFind = false;
		isFind = find(true,replace,false);
		if(!isFind){
			textnumber = 0;
			spreadnumber = 0;
			tabnumber = 0;
			isFind = find(true,replace,false);
		}
		return isFind;
	}
	public boolean prev(final String replace){
		tabnumber--;
		textnumber--;
		boolean isFind = false;
		isFind = find(false,replace,false);
		if(!isFind){
			List<Spread> list = getSpreadsToSearch();
			ArrayList<UsersNote> arrList = (ArrayList<UsersNote>) UsersNoteTree.getInstance().getUsersNotes();
			textnumber = (arrList.size() -1);
			spreadnumber = (list.size() - 1);
			tabnumber = 99;
			isFind = find(false,replace,false);
		}
		return isFind;
	}
	public boolean find(boolean way,final String replace,boolean relaceallmode){
		ArrayList<UsersNote> arrList = (ArrayList<UsersNote>) UsersNoteTree.getInstance().getUsersNotes();
		List<Spread> list = getSpreadsToSearch();
		if(way){
			if( documentType == TextSearchConstants.FIRSTIDAT ||
				documentType == TextSearchConstants.SECONDIDAT ||
				documentType == TextSearchConstants.THIRDIDAT ||
				documentType == TextSearchConstants.ALLDOCUMENT){
				for(int i=spreadnumber;i<list.size();i++){
					Spread spread = list.get(i);
					if(spread == null){
						continue;
					}
					if(findprocess(spread,way,replace,relaceallmode)){
						spreadnumber = i;
						return true;
					}else{
						if(relaceallmode){
							tabnumber = 0;
						}
						continue;
					}
				}
			}
			if(scope != 0){
				return false;
			}
			if(documentType == TextSearchConstants.TEXT || documentType == TextSearchConstants.ALLDOCUMENT){
				if(textnumber < 0){
					textnumber = 0;
				}
				for(int i=textnumber;i<arrList.size();i++){
					UsersNote usersNote = arrList.get(i);
					if(usersNote == null){
						continue;
					}
					if(findtextprocess(usersNote,way,replace,relaceallmode)){
						return true;
					}else{
						continue;
					}
				}

			}
			return false;
		}else{
			if( documentType == TextSearchConstants.FIRSTIDAT ||
				documentType == TextSearchConstants.SECONDIDAT ||
				documentType == TextSearchConstants.THIRDIDAT ||
				documentType == TextSearchConstants.ALLDOCUMENT){
				for(int i=spreadnumber;i>=0;i--){
					Spread spread = list.get(i);
					if(spread == null){
						continue;
					}
					if(findprocess(spread,way,replace,relaceallmode)){
						spreadnumber = i;
						return true;
					}else{
						tabnumber = 99;
						continue;
					}
				}
			}
			if(scope != 0){
				return false;
			}
			if(documentType == TextSearchConstants.TEXT || documentType == TextSearchConstants.ALLDOCUMENT){
				for(int i=textnumber;i>=0;i--){
					UsersNote usersNote = arrList.get(i);
					if(usersNote == null){
						continue;
					}
					if(findtextprocess(usersNote,way,replace,relaceallmode)){
						textnumber = i;
						return true;
					}else{
						continue;
					}
				}

			}

			return false;
		}
	}
	protected boolean issearch=false;
	protected boolean findprocess(Spread spread,boolean way,final String replace,boolean relaceallmode){
		Component selectedComponent = null;
		// WorkspaceWindow.getInstance().tabbedPaneSave();
		
	    GSEditor editor = findWindow(spread.getURI());
	    // すでにWindowが開いている場合はその設定にゆだねる

	    // ALLはどこで見つかったかを記憶しておく
	    ArrayList<Integer> foundnumberList = new ArrayList<Integer>();
	    //Windowsを開く前に予め検索対象の文字列があるか確認する。
	    if(documentType == TextSearchConstants.FIRSTIDAT){
    		boolean html = false;
    		if(editor != null){
    			GSTabbedPane tabbedPane = editor.getSMLTabbedPane();
    			if(tabbedPane.getSelectedComponent() instanceof FirstIDATPanel){
	    			if(editor.getGSEditorToolBar().getMode() == 2){
	    				html = true;
	    			}
    			}
    			if(html){
    				if(!findcheck(tabbedPane.getFirstIDATSource(),true)){
            			return false;
            		}
    			}else{
            		if(!findcheck(spread.getFirstIDAT().getSource(),html)){
            			return false;
            		}
    			}
    		}else{
        		if(!findcheck(spread.getFirstIDAT().getSource(),html)){
        			return false;
        		}
    		}
		}else if(documentType == TextSearchConstants.SECONDIDAT){
    		boolean html = false;
    		if(editor != null){
    			GSTabbedPane tabbedPane = editor.getSMLTabbedPane();
    			if(tabbedPane.getSelectedComponent() instanceof SecondIDATPanel){
	    			if(editor.getGSEditorToolBar().getMode() == 2){
	    				html = true;
	    			}
    			}
    			if(html){
    				if(!findcheck(tabbedPane.getSecondIDATSource(),true)){
            			return false;
            		}
    			}else{
            		if(!findcheck(spread.getSecondIDAT().getSource(),html)){
            			return false;
            		}
    			}
    		}else{
	    		if(!findcheck(spread.getSecondIDAT().getSource(),html)){
	    			return false;
	    		}
    		}
		}else if(documentType == TextSearchConstants.THIRDIDAT){
    		boolean html = false;
    		if(editor != null){
    			GSTabbedPane tabbedPane = editor.getSMLTabbedPane();
    			if(tabbedPane.getSelectedComponent() instanceof ThirdIDATPanel){
	    			if(editor.getGSEditorToolBar().getMode() == 2){
	    				html = true;
	    			}
    			}
    			if(html){
    				if(!findcheck(tabbedPane.getFirstIDATSource(),true)){
            			return false;
            		}
    			}else{
            		if(!findcheck(spread.getThirdIDAT().getSource(),false)){
            			return false;
            		}
    			}

    		}else{
	    		if(!findcheck(spread.getThirdIDAT().getSource(),false)){
	    			return false;
	    		}
    		}
		}else if(documentType == TextSearchConstants.ALLDOCUMENT){
			boolean allFind = false;
			{
	    		boolean html = false;
	    		if(editor != null){
	    			GSTabbedPane tabbedPane = editor.getSMLTabbedPane();
	    			if(tabbedPane.getSelectedComponent() instanceof FirstIDATPanel){
		    			if(editor.getGSEditorToolBar().getMode() == 2){
		    				html = true;
		    			}
	    			}
	    			if(html){
	    				if(findcheck(tabbedPane.getFirstIDATSource(),true)){
			    			allFind = true;
			    			foundnumberList.add(new Integer(1));
	            		}
	    			}else{
	            		if(findcheck(spread.getFirstIDAT().getSource(),false)){
			    			allFind = true;
			    			foundnumberList.add(new Integer(1));
	            		}
	    			}
	    		}else{
		    		if(findcheck(spread.getFirstIDAT().getSource(),false)){
		    			allFind = true;
		    			foundnumberList.add(new Integer(1));
		    		}
	    		}
				
			}
			{
	    		boolean html = false;
	    		if(editor != null){
	    			GSTabbedPane tabbedPane = editor.getSMLTabbedPane();
	    			if(tabbedPane.getSelectedComponent() instanceof SecondIDATPanel){
		    			if(editor.getGSEditorToolBar().getMode() == 2){
		    				html = true;
		    			}
	    			}
	    			if(html){
	    				if(findcheck(tabbedPane.getSecondIDATSource(),true)){
			    			allFind = true;
			    			foundnumberList.add(new Integer(2));
	            		}
	    			}else{
	            		if(findcheck(spread.getSecondIDAT().getSource(),false)){
			    			allFind = true;
			    			foundnumberList.add(new Integer(2));
	            		}
	    			}
	    		}else{
		    		if(findcheck(spread.getSecondIDAT().getSource(),false)){
		    			allFind = true;
		    			foundnumberList.add(new Integer(2));
					}
	    		}
			}
			{
	    		boolean html = false;
	    		if(editor != null){
	    			GSTabbedPane tabbedPane = editor.getSMLTabbedPane();
	    			if(tabbedPane.getSelectedComponent() instanceof ThirdIDATPanel){
		    			if(editor.getGSEditorToolBar().getMode() == 2){
		    				html = true;
		    			}
	    			}
	    			if(html){
	    				if(findcheck(tabbedPane.getFirstIDATSource(),true)){
			    			allFind = true;
			    			foundnumberList.add(new Integer(3));
	            		}
	    			}else{
	            		if(findcheck(spread.getThirdIDAT().getSource(),false)){
			    			allFind = true;
			    			foundnumberList.add(new Integer(3));
	            		}
	    			}
	    		}else{
		    		if(findcheck(spread.getThirdIDAT().getSource(),false)){
		    			allFind = true;
		    			foundnumberList.add(new Integer(3));
		    		}
	    		}
			}
    		if(!allFind){
    			return false;
    		}
		}
	    boolean isNewWindow = false;
	    if(editor == null){
	    	editor = GSEditor.createCompactGSEditor(spread);
	    	isNewWindow = true;
	    }
		GSTabbedPane tabbedPane = editor.getSMLTabbedPane();
		int count = tabbedPane.getComponentCount();
		if(documentType == TextSearchConstants.FIRSTIDAT){
			if(way){
				for(int j=tabnumber;j<count;j++){
					Component component = tabbedPane.getComponent(j);
					if(component instanceof FirstIDATPanel){
						selectedComponent = component;
						tabnumber = j;
						break;
					}
				}
			}else{
				if(tabnumber >= count){
					tabnumber = (count - 1);
				}	for(int j=tabnumber;j>=0;j--){
					Component component = tabbedPane.getComponent(j);
					if(component instanceof FirstIDATPanel){
						selectedComponent = component;
						tabnumber = j;
						break;
					}
				}
			}
			
		}else if(documentType == TextSearchConstants.SECONDIDAT){
			if(way){
				for(int j=tabnumber;j<count;j++){
					Component component = tabbedPane.getComponent(j);
					if(component instanceof SecondIDATPanel){
						selectedComponent = component;
						tabnumber = j;
						break;
					}
				}
			}else{
				if(tabnumber >= count){
					tabnumber = (count - 1);
				}
				for(int j=tabnumber;j>=0;j--){
					Component component = tabbedPane.getComponent(j);
					if(component instanceof SecondIDATPanel){
						selectedComponent = component;
						tabnumber = j;
						break;
					}
				}
				
			}
		}else if(documentType == TextSearchConstants.THIRDIDAT){
			if(way){
				for(int j=tabnumber;j<count;j++){
					Component component = tabbedPane.getComponent(j);
					if(component instanceof ThirdIDATPanel){
						selectedComponent = component;
						tabnumber = j;
						break;
					}
				}
			}else{
				if(tabnumber >= count){
					tabnumber = (count - 1);
				}				for(int j=tabnumber;j>=0;j--){
					Component component = tabbedPane.getComponent(j);
					if(component instanceof ThirdIDATPanel){
						selectedComponent = component;
						tabnumber = j;
						break;
					}
				}
			}
		}else if(documentType == TextSearchConstants.ALLDOCUMENT){
			if(way){
				for(int j=tabnumber;j<count;j++){
					Component component = tabbedPane.getComponent(j);
					if(component instanceof FirstIDATPanel){
						if(foundnumberList.contains(new Integer(1))){
							selectedComponent = component;
							tabnumber = j;
							break;
						}
					}else if(component instanceof SecondIDATPanel){
						if(foundnumberList.contains(new Integer(2))){
							selectedComponent = component;
							tabnumber = j;
							break;
						}
					}else if(component instanceof ThirdIDATPanel){
						if(foundnumberList.contains(new Integer(3))){
							selectedComponent = component;
							tabnumber = j;
							break;
						}
					}
				}
			}else{
				if(tabnumber >= count){
					tabnumber = (count - 1);
				}
				for(int j=tabnumber;j>=0;j--){
					Component component = tabbedPane.getComponent(j);
					if(component instanceof FirstIDATPanel){
						if(foundnumberList.contains(new Integer(1))){
							selectedComponent = component;
							tabnumber = j;
							break;
						}
					}else if(component instanceof SecondIDATPanel){
						if(foundnumberList.contains(new Integer(2))){
							selectedComponent = component;
							tabnumber = j;
							break;
						}
					}else if(component instanceof ThirdIDATPanel){
						if(foundnumberList.contains(new Integer(3))){
							selectedComponent = component;
							tabnumber = j;
							break;
						}
					}
				}
								
			}
		}
		if(selectedComponent != null){
			SearchAllDialogManager.clearselect();
			tabbedPane.setSelectedIndex(tabnumber);
			SearchAllDialogManager.setEditor(editor,editor.getGSEditorToolBar());
			SearchAllDialogManager.visible();
			if(selectedComponent instanceof IDATPanel){
				final GSEditorTextPane textPane = ((IDATPanel)selectedComponent).getTextPane();
				// フォーカスイベントを通知
				if(!editor.isVisible()){
					editor.setLocationByPlatform(true);
				}
				editor.setVisible(true);
				textPane.getGSHTMLEditorTextPane().requestFocusInWindow(); 
				if(!relaceallmode){
					editor.addWindowListener(new WindowAdapter() {
					  @Override
					  public void windowOpened(WindowEvent e) {
						  SearchAllDialogManager.search(replace);
					  }
					});
					if(!isNewWindow){
						SearchAllDialogManager.search(replace);
					}
				}
			}
			return true;
		}
		if(way){
			if(count >= tabnumber){
				tabnumber = 0;
//				spreadnumber++;
			}else{
				tabnumber++;
			}
		}else{
			if(tabnumber == 0){
				tabnumber = count;
				spreadnumber--;
			}else{
				tabnumber--;
			}
		}
		return false;
	}
	

	public boolean findtextprocess(UsersNote usersNote,boolean way,final String replace,boolean relaceallmode){
		GSTreeTextEditor editor = GSTreeTextEditortPaneManager.getGSTreeTextEditort(String.valueOf(((SmartDocument)usersNote).getId()));
	    // すでにWindowが開いている場合はその設定にゆだねる

	    //Windowsを開く前に予め検索対象の文字列があるか確認する。
		boolean html = false;
		boolean isNewWindow = false;
		if(editor != null){
			if(editor.getGSEditorToolBar().getMode() == 2){
				html = true;
			}
			if(html){
				if(!findcheck(editor.getGSEditorTextPane().getSource(),true)){
					return false;
				}
			}else{
        		if(!findcheck(editor.getGSEditorTextPane().getPainText(),true)){
					return false;
        		}
			}
		}else{
			if(!findcheck(usersNote.getSource(),false)){
				return false;
			}
			
		}
	    if(editor == null){
	    	editor = new GSTreeTextEditor(usersNote,usersNote.getName());
	    	isNewWindow = true;
	    }
		SearchAllDialogManager.clearselect();
		SearchAllDialogManager.setEditor(editor,editor.getGSEditorToolBar());
		SearchAllDialogManager.visible();
		final GSEditorTextPane gsEditorTextPane = editor.getGSEditorTextPane();
		// フォーカスイベントを通知
		if(!editor.isVisible()){
			editor.setLocationByPlatform(true);
		}
		editor.setVisible(true);
		gsEditorTextPane.getGSHTMLEditorTextPane().requestFocusInWindow();
		if(!relaceallmode){
			if(isNewWindow){
				editor.addWindowListener(new WindowAdapter() {
					  @Override
					  public void windowOpened(WindowEvent e) {
						  SearchAllDialogManager.search(replace);
					  }
				});
			}else{
//				SearchAllDialogManager.search();
				WindowEvent aEvent = new WindowEvent(editor, WindowEvent.WINDOW_OPENED);
				Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(aEvent);
			}
		}
		if(way){
			textnumber++;
		}else{
			textnumber--;
		}
		return true;
	}
	
	protected boolean replaceallprocess(Spread spread,final String replace){
		// WorkspaceWindow.getInstance().tabbedPaneSave();
		boolean isFind = false;
		
		GSEditor editor = findWindow(spread.getURI());
		WorkspaceWindow workspaceWindow = null;
		if(editor != null){
			editor.getSMLTabbedPane().save();
		}else{
			workspaceWindow = findWorkspaceWindow(spread.getURI());
		}
		// Editorが開いている場合は、その中身を替える
		// 開いていない場合はsoreadをの中身を替える.
		if(documentType == TextSearchConstants.FIRSTIDAT){
	    	ReplaceALLInfo replaceALLInfo;
	    	if(editor != null || workspaceWindow != null){
	    		GSTabbedPane gsTabbedPane = null;
	    		if(editor != null){
	    			gsTabbedPane = editor.getSMLTabbedPane();
	    		}else if(workspaceWindow != null){
	    			gsTabbedPane = workspaceWindow.getTabbedPane();
	    		}
	    		if(gsTabbedPane != null){
		    		// No Windowsモードは全てをTextとして扱うため、Editをtrueに着替える
	    			gsTabbedPane.getFirstIDAT().setEdit(true);
		    		replaceALLInfo = replace(gsTabbedPane.getFirstIDAT().getSource("body"),replace);
		    		if(replaceALLInfo.isReplace()){
		    			int oldCaretPosition = gsTabbedPane.getFirstIDAT().getCaretPosition();
		    			gsTabbedPane.getFirstIDAT().setSource(replaceALLInfo.getSource());
		    			gsTabbedPane.getFirstIDAT().setCaretPosition(oldCaretPosition);
			    		isFind = true;
			    	}
	    		}
	    	}else{
	    		replaceALLInfo = replace(spread.getFirstIDAT().getSource(),replace);
		    	if(replaceALLInfo.isReplace()){
		    		spread.getFirstIDAT().setSource(replaceALLInfo.getSource());
		    		isFind = true;
		    	}
	    	}
		}else if(documentType == TextSearchConstants.SECONDIDAT){
	    	ReplaceALLInfo replaceALLInfo;
	    	if(editor != null || workspaceWindow != null){
	    		GSTabbedPane gsTabbedPane = null;
	    		if(editor != null){
	    			gsTabbedPane = editor.getSMLTabbedPane();
	    		}else if(workspaceWindow != null){
	    			gsTabbedPane = workspaceWindow.getTabbedPane();
	    		}
	    		if(gsTabbedPane != null){
		    		// No Windowsモードは全てをTextとして扱うため、Editをtrueに着替える
	    			gsTabbedPane.getSecondIDAT().setEdit(true);
		    		replaceALLInfo = replace(gsTabbedPane.getSecondIDAT().getSource("body"),replace);
		    		if(replaceALLInfo.isReplace()){
		    			int oldCaretPosition = gsTabbedPane.getSecondIDAT().getCaretPosition();
		    			gsTabbedPane.getSecondIDAT().setSource(replaceALLInfo.getSource());
		    			gsTabbedPane.getSecondIDAT().setCaretPosition(oldCaretPosition);
			    		isFind = true;
			    	}
	    		}
	    	}else{		    	
	    		replaceALLInfo = replace(spread.getSecondIDAT().getSource(),replace);
		    	if(replaceALLInfo.isReplace()){
		    		spread.getSecondIDAT().setSource(replaceALLInfo.getSource());
		    		isFind = true;
		    	}
	    	}
		}else if(documentType == TextSearchConstants.THIRDIDAT){
	    	ReplaceALLInfo replaceALLInfo;
	    	if(editor != null || workspaceWindow != null){
	    		GSTabbedPane gsTabbedPane = null;
	    		if(editor != null){
	    			gsTabbedPane = editor.getSMLTabbedPane();
	    		}else if(workspaceWindow != null){
	    			gsTabbedPane = workspaceWindow.getTabbedPane();
	    		}
	    		if(gsTabbedPane != null){
		    		// No Windowsモードは全てをTextとして扱うため、Editをtrueに着替える
	    			gsTabbedPane.getThirdIDAT().setEdit(true);
		    		replaceALLInfo = replace(gsTabbedPane.getThirdIDAT().getSource("body"),replace);
		    		if(replaceALLInfo.isReplace()){
		    			int oldCaretPosition = gsTabbedPane.getThirdIDAT().getCaretPosition();
		    			gsTabbedPane.getThirdIDAT().setSource(replaceALLInfo.getSource());
		    			gsTabbedPane.getThirdIDAT().setCaretPosition(oldCaretPosition);
			    		isFind = true;
			    	}
	    		}
	    	}else{
		    	replaceALLInfo = replace(spread.getThirdIDAT().getSource(),replace);
		    	if(replaceALLInfo.isReplace()){
		    		spread.getThirdIDAT().setSource(replaceALLInfo.getSource());
		    		isFind = true;
		    	}
	    	}
		}else if(documentType == TextSearchConstants.ALLDOCUMENT){
	    	ReplaceALLInfo replaceALLInfo;
	    	if(editor != null || workspaceWindow != null){
	    		GSTabbedPane gsTabbedPane = null;
	    		if(editor != null){
	    			gsTabbedPane = editor.getSMLTabbedPane();
	    		}else if(workspaceWindow != null){
	    			gsTabbedPane = workspaceWindow.getTabbedPane();
	    		}
	    		if(gsTabbedPane != null){
		    		// No Windowsモードは全てをTextとして扱うため、Editをtrueに着替える
	    			gsTabbedPane.getFirstIDAT().setEdit(true);
		    		replaceALLInfo = replace(gsTabbedPane.getFirstIDAT().getSource("body"),replace);
		    		if(replaceALLInfo.isReplace()){
		    			int oldCaretPosition = gsTabbedPane.getFirstIDAT().getCaretPosition();
		    			gsTabbedPane.getFirstIDAT().setSource(replaceALLInfo.getSource());
		    			gsTabbedPane.getFirstIDAT().setCaretPosition(oldCaretPosition);
			    		isFind = true;
			    	}
	    		}
	    	}else{
	    		replaceALLInfo = replace(spread.getFirstIDAT().getSource(),replace);
		    	if(replaceALLInfo.isReplace()){
		    		spread.getFirstIDAT().setSource(replaceALLInfo.getSource());
		    		isFind = true;
		    	}
	    	}
	    	if(editor != null || workspaceWindow != null){
	    		GSTabbedPane gsTabbedPane = null;
	    		if(editor != null){
	    			gsTabbedPane = editor.getSMLTabbedPane();
	    		}else if(workspaceWindow != null){
	    			gsTabbedPane = workspaceWindow.getTabbedPane();
	    		}
	    		if(gsTabbedPane != null){
		    		// No Windowsモードは全てをTextとして扱うため、Editをtrueに着替える
	    			gsTabbedPane.getSecondIDAT().setEdit(true);
		    		replaceALLInfo = replace(gsTabbedPane.getSecondIDAT().getSource("body"),replace);
		    		if(replaceALLInfo.isReplace()){
		    			int oldCaretPosition = gsTabbedPane.getSecondIDAT().getCaretPosition();
		    			gsTabbedPane.getSecondIDAT().setSource(replaceALLInfo.getSource());
		    			gsTabbedPane.getSecondIDAT().setCaretPosition(oldCaretPosition);
			    		isFind = true;
			    	}
	    		}
	    	}else{		    	
	    		replaceALLInfo = replace(spread.getSecondIDAT().getSource(),replace);
		    	if(replaceALLInfo.isReplace()){
		    		spread.getSecondIDAT().setSource(replaceALLInfo.getSource());
		    		isFind = true;
		    	}
	    	}
	    	if(editor != null || workspaceWindow != null){
	    		GSTabbedPane gsTabbedPane = null;
	    		if(editor != null){
	    			gsTabbedPane = editor.getSMLTabbedPane();
	    		}else if(workspaceWindow != null){
	    			gsTabbedPane = workspaceWindow.getTabbedPane();
	    		}
	    		if(gsTabbedPane != null){
		    		// No Windowsモードは全てをTextとして扱うため、Editをtrueに着替える
	    			gsTabbedPane.getThirdIDAT().setEdit(true);
		    		replaceALLInfo = replace(gsTabbedPane.getThirdIDAT().getSource("body"),replace);
		    		if(replaceALLInfo.isReplace()){
		    			int oldCaretPosition = gsTabbedPane.getThirdIDAT().getCaretPosition();
		    			gsTabbedPane.getThirdIDAT().setSource(replaceALLInfo.getSource());
		    			gsTabbedPane.getThirdIDAT().setCaretPosition(oldCaretPosition);
			    		isFind = true;
			    	}
	    		}
	    	}else{
		    	replaceALLInfo = replace(spread.getThirdIDAT().getSource(),replace);
		    	if(replaceALLInfo.isReplace()){
		    		spread.getThirdIDAT().setSource(replaceALLInfo.getSource());
		    		isFind = true;
		    	}
	    	}
		}
		return isFind;
	}

	public boolean replacealltextprocess(UsersNote usersNote,final String replace){
		boolean isFind = false;
		GSTreeTextEditor editor = GSTreeTextEditortPaneManager.getGSTreeTextEditort(String.valueOf(((SmartDocument)usersNote).getId()));
		ReplaceALLInfo replaceALLInfo;
    	if(editor != null){
    		GSEditorTextPane gsEditorTextPane = null;
    		if(editor != null){
    			gsEditorTextPane = editor.getGSEditorTextPane();
    		}
    		if(gsEditorTextPane != null){
	    		// No Windowsモードは全てをTextとして扱うため、Editをtrueに着替える
    			gsEditorTextPane.setEdit(true);
	    		replaceALLInfo = replace(gsEditorTextPane.getSource("body"),replace);
	    		if(replaceALLInfo.isReplace()){
	    			int oldCaretPosition = gsEditorTextPane.getCaretPosition();
	    			gsEditorTextPane.setSource(replaceALLInfo.getSource());
	    			gsEditorTextPane.setCaretPosition(oldCaretPosition);
		    		isFind = true;
		    	}
    		}
    	}else{
    		replaceALLInfo = replace(usersNote.getSource(),replace);
	    	if(replaceALLInfo.isReplace()){
	    		usersNote.setSource(replaceALLInfo.getSource());
	    		isFind = true;
	    	}
    	}
		return isFind;
	}

	protected ReplaceALLInfo replace(String source,String replace){
		ReplaceALLInfo replaceALLInfo = new ReplaceALLInfo();
		boolean isFind = false;
		String queryText = SearchAllDialogManager.getSearchTextField();
		// isCaseSensitiveの値に従ってqueryText, planeTextを変換
		String ccQuery = convertCase(queryText, SearchAllDialogManager.isCaseCheckBox());
		String text = source;
		StringBuffer buf = new StringBuffer();
		boolean tagmode = false;
		StringBuffer matchBuf = new StringBuffer();
		for(int i=0;i<text.length();i++){
			if(text.charAt(i) == '<'){
				tagmode = true;
				buf.append(matchBuf.toString());
				matchBuf = new StringBuffer(); 
			}
			if(tagmode){
				buf.append(text.charAt(i));
			}else{
				matchBuf.append(text.charAt(i));
				int matchIndex;
				if(SearchAllDialogManager.isRegularCheckBox()){
					Pattern p = Pattern.compile(ccQuery);
					Matcher m = null;
					if(SearchAllDialogManager.isCaseCheckBox()){
						m = p.matcher(matchBuf.toString());
					}else{
						m = p.matcher(matchBuf.toString().toLowerCase());
					}
					if(m.find()){
						replaceallcounter++;
						buf.append(m.replaceAll(replace));
						isFind = true;
						matchBuf = new StringBuffer(); 
					}
				}else{
					if(SearchAllDialogManager.isCaseCheckBox()){
						matchIndex = matchBuf.toString().indexOf(ccQuery);
					}else{
						matchIndex = matchBuf.toString().toLowerCase().indexOf(ccQuery);
					}
					if(matchIndex != -1){
						replaceallcounter++;
						buf.append(StringUtils.replaceString(matchBuf.toString(),ccQuery,replace));
						isFind = true;
						matchBuf = new StringBuffer(); 
					}
				}
			}
			if(text.charAt(i) == '>'){
				tagmode = false;
			}
		}
		buf.append(matchBuf.toString());
		replaceALLInfo.setSource(buf.toString());
		replaceALLInfo.setReplace(isFind);
		return replaceALLInfo;

	}

	public GSEditor findWindow(String url){
		GSTabbedPane newTabbedPane = GSTabbedPaneManager.getGSTabbedPane(url);
		if(newTabbedPane == null){
			return null;
		}
		if(newTabbedPane.getParentFrame() instanceof GSEditor){
			return (GSEditor)newTabbedPane.getParentFrame();
		}
		return null;
	}

	public WorkspaceWindow findWorkspaceWindow(String url){
		GSTabbedPane newTabbedPane = GSTabbedPaneManager.getGSTabbedPane(url);
		if(newTabbedPane == null){
			return null;
		}
		if(newTabbedPane.getParentFrame() instanceof WorkspaceWindow){
			if(((WorkspaceWindow)newTabbedPane.getParentFrame()).getSpread().getURI().equals(url)){
				return (WorkspaceWindow)newTabbedPane.getParentFrame();
			}
		}
		return null;
	}

	private  boolean findcheck(String source,boolean isSource){
		String queryText = SearchAllDialogManager.getSearchTextField();
		String planeText = null;
		if(isSource){
			planeText = source;
		}else{
			planeText = source2Text(source);
		}
		// isCaseSensitiveの値に従ってqueryText, planeTextを変換
		String ccQuery = convertCase(queryText, SearchAllDialogManager.isCaseCheckBox());
		String ccText = convertCase(planeText, SearchAllDialogManager.isCaseCheckBox());
    	
    	if(SearchAllDialogManager.isRegularCheckBox()){
			try{
				Pattern p = Pattern.compile(ccQuery);
				Matcher m = p.matcher(ccText);
			    while(m.find()){
			    	return true;
			    }
			}catch(Exception e){
				e.printStackTrace();
				return false;
			}
		}else{
			if (ccText.indexOf(ccQuery) != -1) {
				return true;
			}
		}
    	return false;
	}
	
	private static String source2Text(String source) {
		String planeText = source;
		planeText = StringUtils.replaceString(planeText, "<br>", "\n");
		Pattern pattern = Pattern.compile("<.+?>", Pattern.DOTALL);
		Matcher matcher = pattern.matcher(planeText);
		planeText = matcher.replaceAll("");
		return planeText;
	}

	private static String convertCase(String source, boolean isCaseSensitive) {
		if (source == null) {
			return null;
		}
		if (isCaseSensitive) {
			return source;
		}
		return source.toLowerCase();
	}
}
