/************************************************************

	Lunascapeお気に入り検索スクリプト ver 1.0.1

	by Hawk(hawkweb@hawk.34sp.com) 2002/12/27

	>>仕様
	-- ダイアログで設定可能な項目 --
	・正規表現の使用/不使用
	・AND/OR（正規表現"不"使用時のみ有効）
	・英大文字小文字区別なし/あり
	・検索対象（タイトル｜URL｜コメント）
	
	-- その他 --
	・検索結果はタイトルとURLのみ一覧表示
	　コメントはURLのチップテキストとして表示される
	・検索設定の自動保存＆ロード
	・凝ったデザイン（嘘）

	>>考えていること
	・検索結果の表示項目を設定可能にする
	・さらなる動作の高速化

************************************************************/

//======= 初期化 ========================================
var luna, document, window;
var results = new Array(); //結果配列
var scrPath;

var resultHTMLPath     = "default\\search_favorites\\";
var resultHTMLFileName = "FavSearchResult.html";
var resultHTML = resultHTMLPath + resultHTMLFileName;
var dialogHTML = "default\\search_favorites\\FavSearchDialog.html";
var section = "FavSearch";
var key     = "SearchArgs";


//終了処理
function Exit(msg){
	if(msg!=null)luna.MessageBox(msg);
	document= null;
	window  = null;
	luna    = null;
	WScript.Quit();
}

var isSearching = false;
function ExitAndClose(msg){
	if(!isSearching) luna.Close(luna.ActiveIndex);
	Exit(msg);
}

//-------------------------------------------------------

luna    = new ActiveXObject("Lunascape2.LunascapeAPI");
scrPath = luna.AppPath + "resource/script/";

if(luna.Version<1.02) Exit('此脚本要求运行Lunascape 2或更高版本。');

var activeIndex = luna.ActiveIndex;

// アクティブタブがTridentの結果表示ページか？
if( ( activeIndex > 0 ) && (luna.EngineType( activeIndex ) == "{248B8F5D-FAE2-4f0e-9EC9-3B408DBF0B2B}") && ( (new RegExp(resultHTMLFileName)).test(luna.URL) ))
{
	isSearching=true;
}
else
{
	// 結果表示画面でない場合は結果表示画面用のタブを作る
	var tridentTabId = luna.OpenDocument("{248B8F5D-FAE2-4f0e-9EC9-3B408DBF0B2B}", "");
	luna.Navigate(tridentTabId, scrPath +resultHTML);
	// ページが切り替わるのでアクティブタブを更新
	activeIndex = luna.GetIndex(tridentTabId);
}

window  = luna.GetWindowObject(luna.GetDocumentID(activeIndex ));
if(window == null) Exit("错误：无法创建窗口对象。");
document= luna.GetDocumentObject(luna.GetDocumentID(activeIndex ));
if(document == null) Exit("错误：无法创建文档对象。");

var pastArg = luna.GetProfileString(section, key, "");

//======= 入力を受け取る ================================

function Setting(wrd, isR, isI){
	this.Word     = (wrd!=null)? wrd : "";
	this.IsRegExp = (isR!=null)? isR : true;
	this.IsIgnore = (isI!=null)? isI : true;

	this.Targets = {
		'Title'  : true,
		'URL'    : false,
		'Comment': false
	};
	this.Options = {
		'AND' : false,
		'OR'  : false
	};
	
	this.toString = function(){
		return  "Word='" +  this.Word +
			"',IsRegExp="+ this.IsRegExp +
			",IsIgnore="+ this.IsIgnore +
			",Targets.Title="+ this.Targets.Title + 
			",Targets.URL="+ this.Targets.URL + 
			",Targets.Comment="+ this.Targets.Comment + 
			",Options.AND="+ this.Options.AND + 
			",Options.OR=" + this.Options.OR;
	}
}
Setting.Parse = function(str){
	var sets = new this();
	var tmps = str.split(','), len=tmps.length, ltmp=[];
	for(var i=0; i<len; i++){
		eval('sets.'+ tmps[i] +';');
	}
	return sets;
}

var feature = "status:no; dialogWidth:465px; dialogHeight:175px; scroll:no";
var searchString = window.showModalDialog(scrPath + dialogHTML, pastArg, feature);
var reg, ign;

function MultiRegExp(wrdArray, opts){
	var len = wrdArray.length;
	for (var i = 0; i < len; i++) wrdArray[i] = new RegExp(wrdArray[i], ign)

	this.test = function (str){
		for (var i=0; i<len; i++) if(!wrdArray[i].test(str)) return false;
		return true;
	}
}

//-------------------------------------------------------

//Cancel時の終了処理
if(!searchString)ExitAndClose();

searchSets = Setting.Parse(searchString);

if(searchSets.Word==null||searchSets.Word=="") Exit();
ign = (searchSets.IsIgnore)? "i":"";
if(searchSets.IsRegExp){
	try{
		reg = new RegExp(searchSets.Word, ign);
	}
	catch(e){
		Exit('搜索字符串不是正则表达式。');
	}
}else{
	sWrd = searchSets.Word.replace(/([\[\]\(\)\{\}\+\*\.\|\/])/g, "\\$1");

	if(searchSets.Options.OR)	reg = new RegExp(sWrd.replace(/[\s　]+/, '|'), ign);
	else if(searchSets.Options.AND)	reg = new MultiRegExp(sWrd.split(/[\s　]+/, 5).reverse(), ign);
				else	reg = new RegExp(sWrd, ign);
}

//--save
luna.WriteProfileString(section, key, searchString);

//======= 検索処理 ================================

var start, lag;

Function.prototype.getHEREdocument = function (name){
    var reg_here_all = new RegExp('\\/\\*start '+ name +'(.|\\n)+end '+ name +'\\*\\/');
    var reg_here_str = new RegExp('\\/\\*start '+ name +'|end '+ name +'\\*\\/', 'g');

    var here = this.toString().match(reg_here_all)[0];
        here = here.replace(reg_here_str, "");
        here = here.replace(/^[\r\n]*|[\r\n]*$/g, "");

    return here;
}

//検索用関数を組み立てる
var _funcstr;
with(searchSets.Targets){
	_funcstr = 'if(';
	if(Title)  _funcstr+= 'wrd.test(luna.ItemTitle(cID))||';
	if(URL)    _funcstr+= 'wrd.test(luna.ItemURL(cID))||';
	if(Comment)_funcstr+= 'wrd.test(luna.ItemComment(cID))';
	_funcstr = _funcstr.replace(/\|\|$/, "") +" )results[results.length] = cID;\n";
}
var SearchFolder = new Function('cID, wrd', FunctionParts.getHEREdocument('SEARCH_HEAD')

+_funcstr+FunctionParts.getHEREdocument('SEARCH_FOOT'));


//-------------------------------------------------------

var strSearchId = luna.GetChildItemID(luna.SelectedItem);
// 子供のいないアイテムを選択している場合はルート以下から検索
if(strSearchId == "")
{
	strSearchId = luna.GetChildItemID(luna.GetRootItemID());
}

start = new Date().getTime();

SearchFolder(strSearchId, reg); //検索

lag = (new Date().getTime() - start)/1000;

if(results.length==0){
	luna.MessageBox("相应的元素没有找到。");
	ExitAndClose();
}
if(!window.confirm(results.length + "结果发现。\n显示详细结果？")) 

ExitAndClose();

//-----表示処理-------
var len = results.length;

document.getElementById('searchWord').innerText = searchSets.Word;
document.getElementById('searchTime').innerText = lag;
document.getElementById('searchHits').innerText = len;

var oTable = document.getElementById('resultTable');
var oTBody = document.createElement('tBody');
var oRow   = document.createElement('TR');
var oTD    = document.createElement('TD');
var oLink  = document.createElement('A');
    oLink.target='_blank';

var oTD_Title, oTD_URL, oURL, oTR;
var crrID, strURL;

for(var i=0; i<len; i++){
	crrID=results[i], strURL=luna.ItemURL(crrID);
	oTD_Title = oTD.cloneNode();
	oTD_URL   = oTD.cloneNode();
	oURL	  = oLink.cloneNode();
	oTR	  = oRow.cloneNode();

	oTBody.appendChild(oTR);
	oTR.appendChild(oTD_Title);
	oTR.appendChild(oTD_URL);
	oTD_URL.appendChild(oURL);

	oTD_Title.innerText = luna.ItemTitle(crrID);
	oURL.innerText = strURL;
	oURL.href = strURL;
	oURL.title= luna.ItemComment(crrID);
}

oTable.replaceChild(oTBody, oTable.tBodies[0]);

function FunctionParts(){
/*start SEARCH_HEAD
	for(; cID!=""; cID=luna.GetNextSiblingItemID(cID)){
		if(luna.ItemType(cID)=="FAVORITE_FOLDER"){
			SearchFolder(luna.GetChildItemID(cID), wrd);
			continue;
		}

end SEARCH_HEAD*/

/*start SEARCH_FOOT

	}
	return;
end SEARCH_FOOT*/
}