//============================================================================
// Copyright (C) 2003,2004,2005    Ikki Ohmukai,      All rights reserved.
//============================================================================


//--------------------------------------------------------------------------
// Utilities
//--------------------------------------------------------------------------

function closeButton(b)
{
	var mark = b.firstChild;
	if(mark.data == "-")
		mark.data = "+";
}
function openButton(b)
{
	var mark = b.firstChild;
	if(mark.data == "+")
		mark.data = "-";
}
function closeButtons(el)
{
	var buttons = el.getElementsByTagName('button');
	for(var i = 0; i < buttons.length; ++i)
		closeButton(buttons.item(i));
}
function openButtons(el)
{
	var buttons = el.getElementsByTagName('button');
	for(var i = 0; i < buttons.length; ++i)
		openButton(buttons.item(i));
}

// navigation
// 	Inspired by たつを's script.
function changeNavigation(target_id, 
	navi_selected, navi_tagname, navi_classname, 
	content_root, content_tagname, content_classname)
{
	if (! document.getElementById) return;

	navi_classname = navi_classname.replace(/-active$/,"");

	var navi_nodes= navi_selected.parentNode.getElementsByTagName(navi_tagname);
	for (var i = 0; i < navi_nodes.length; i++) {
		var navi_node = navi_nodes.item(i);

		if(isNotEmpty(navi_classname) 
			&& navi_node.className != navi_classname 
			&& navi_node.className != navi_classname + "-active" ) 
		{
			continue;
		}

		if(navi_selected == navi_node) {
			navi_node.className = navi_classname + "-active";
		}
		else {
			navi_node.className = navi_classname ;
		}
  }

	// content
	var content_nodes = content_root.getElementsByTagName(content_tagname);
	for (var i = 0; i < content_nodes.length; i++) {
		var content_node = content_nodes.item(i);
		if(isNotEmpty(content_classname) && content_node.className != content_classname ) continue;

		if(content_node.id == target_id || '__ALL__' == target_id) {
			content_node.style.display  = "block";
		}
		else {
			content_node.style.display  = "none";
		}
	}
}


// Incremental search 
//   inspired by satoru's script. 
//   http://namazu.org/~satoru/blog/archives/000019.html
function quotemeta (string) 
{
    return string.replace(/(\W)/, "\\$1");
}
function search_text (pattern, root_element, target_tag, target_class) 
{
	var regex = new RegExp(quotemeta(pattern), "i");
	var targets = root_element.getElementsByTagName(target_tag);

	for (var i = 0; i < targets.length; ++i) {
		var target = targets.item(i);
		if(!isNotEmpty(target_class) || target.className == target_class) {
		// target
			var s = target.innerHTML;
			
			s = s.replace(/\r?\n/g,"");
			s = s.replace(/<\!--.*?-->/g,"");
			s = s.replace(/<[^>]*?>/g,"");

			var divs = target.getElementsByTagName('div');
			var ndiv = divs.length;
			if (s.match(regex)) {
				target.style.display = "block";
				for (var j = 0; j < ndiv; ++j)
					divs.item(j).style.display = "block";
				openButtons(target);
			} else {
				target.style.display = "none";
				for (var j = 0; j < ndiv; ++j)
					divs.item(j).style.display = "none";
				closeButtons(target);
			}
		}
	}
}

// Inspired by Masahide Kanzaki's script.
function showHide(x, tag){
	var marker = x.firstChild;
	var div_array = x.parentNode.getElementsByTagName(tag);
	for (var i = 0; i < div_array.length; i++) {
		var div = div_array.item(i);

		if(marker.data == "-"){
			div.style.display ="none";
		}
		else{ // (marker.data == "+"){
			div.style.display ="block";
 		}
	}

	if(marker.data == "-"){
		marker.data = "+";
	}
	else{
 		marker.data = "-";
	}
}

function showHideAll(x, sw_tag, target_tag){
	var tag_array = x.parentNode.getElementsByTagName(sw_tag);
	for (var i = 0; i < tag_array.length; i++) {
		showHide(tag_array.item(i), target_tag);
	}
}


// 　Inspired by いしだなおと's script
function make_jsfeed(js_cgi, target, encoding, template_uri){
	var source = new String;
	source = 
		'<script type="text/javascript" src="'
		+ js_cgi + '?'
		+ 'encoding=' + encoding 
		+ '&target='   + target
		+ '&template=' + escape(template_uri)
		+ '"><\/script>';

	return source;
}


// var text = getSelectedString(); 
function getSelectedString()
{
	if (window.getSelection) 
		return window.getSelection();
	else if (document.getSelection) 
		return document.getSelection();
	else if (document.selection) 
		return document.selection.createRange().text;

	return '';
}

function isNotEmpty(str) {
	return (str != '' && str != null && str != undefined);
}

// 
function setCookie(name, value, expire_sec, path)
{
	var expire = new Date();
	expire.setTime(expire.getTime() + 1000*expire_sec);
	var cookie_string 
		= escape(name) + "=" + encodeURIComponent(value) + ";";
	if(expire_sec != '' && expire_sec != null && expire_sec != undefined)
		cookie_string += " expires=" + expire.toGMTString() + ";";
	if(isNotEmpty(path))
		cookie_string += " path=" + eacape(path) + ";";

	document.cookie = cookie_string;
}

function getCookie(name)
{
	var ar = new Array();
	var cookie_str = document.cookie.replace(/\s+/g, '');
//alert(cookie_str);
	ar = cookie_str.split(";");
//alert(ar[0] + ' ' + ar[1] + ' ' + ar[2] + ' ' + ar[3]);
	var i = 0;
	for(i = 0; i < ar.length; i++){
		var ar2 = new Array();
		ar2 = ar[i].split("=");
		if (ar2[0] == name){
			return  ar2[1];
			break;
		}
	}

	return null;
}

function deleteCookie(name, path)
{
	setCookie(name, '', -60*60*24, path);
}


// date
function w3cdtf(date)
{
	if(!date) date = new Date();

	var y = date.getUTCFullYear();
	var m = date.getUTCMonth() + 1;
	var d = date.getUTCDate();
	var h = date.getUTCHours();
	var M = date.getUTCMinutes();
	var s = date.getUTCSeconds();

	if(m < 10) m = '0' + m;
	if(d < 10) d = '0' + d;
	if(h < 10) h = '0' + h;
	if(M < 10) M = '0' + M;
	if(s < 10) s = '0' + s;

	return y+'-'+m+'-'+d + 'T' + h+':'+M+':'+s + '+00:00';
}



//--------------------------------------------------------------------------
// onload, onunload
//--------------------------------------------------------------------------

// onload
{
	var global_onload_functions = {};

	window.onload = function() {
		for(var i in global_onload_functions) {
			global_onload_functions[i]();
		}
	};

	function addOnloadFunction(key, func) {
		if(typeof(function(){}) == typeof func) 
			global_onload_functions[key] = func;
		else 
			alert(func.toString() + 'is not function');
	}
	function deleteOnloadFunction(key) {
		delete global_onload_functions[key];
	}
	//addOnloadFunction('aa', function(){alert('終了');});
}


// onunload
{
	var global_onunload_functions = {};

	window.onunload = function() {
		for(var i in global_onunload_functions) {
			global_onunload_functions[i]();
		}
	};

	function addOnunloadFunction(key, func) {
		if(typeof(function(){}) == typeof func) 
			global_onunload_functions[key] = func;
		else 
			alert(func.toString() + 'is not function');
	}
	function deleteOnunloadFunction(key) {
		delete global_onunload_functions[key];
	}
	//addOnunloadFunction('aa', function(){alert('終了');});
}


//--------------------------------------------------------------------------
// XML-RPC
//--------------------------------------------------------------------------
{
	function XMLRPCServerURI(uri) 
	{
		if(uri) XMLRPCServerURI.xmlrpc_server_uri = uri;
		return XMLRPCServerURI.xmlrpc_server_uri;
	}
	XMLRPCServerURI.xmlrpc_server_uri = null;
}

// read-history
{
	var global_accessed_items 
		= {/*'l1':{title:'t',link:'l',date:'d'}, 'l2':{}, ...*/};

	var global_read_history_timer_id = null;
	function startReadHistoryTimer(interval/*[min]*/)
	{
		if(interval != undefined)
			startReadHistoryTimer._interval=interval;
		interval = startReadHistoryTimer._interval
		
		global_read_history_timer_id  
			= setTimeout("postReadHistory();startReadHistoryTimer();", 
			interval*60*1000);
	}
	function stopReadHistoryTimer()
	{
		clearTimeout(global_read_history_timer_id);
		global_read_history_timer_id = null; 
	}
	function startReadHistory() 
	{
		addReadHistory = __addReadHistory;
	}
	function stopReadHistory() 
	{
		addReadHistory = function(){};
	}
	stopReadHistory();

	function __addReadHistory(arg) 
	{
		//alert("test!\n" + arg.link + "\n" + arg.title + "\n" + arg.description);
		global_accessed_items[arg.link] = arg;
	}
	
	function postReadHistory()
	{
		var serverURL = XMLRPCServerURI();
		if(!serverURL) return false;

		var accessed_items = [];
		for(var i in global_accessed_items) {
			accessed_items.push(global_accessed_items[i]);
		}
		if(accessed_items.length < 1) return false;

		var xmlrpc = new XMLRPCTinyClient(serverURL);
		var arg = [{username:'anonymous', passwd:''}, accessed_items];
		var xmlrpc_req = new XMLRPCTinyRequest('rna.postReadHistory', arg, null);
		xmlrpc.call(xmlrpc_req);

		// delete recorded history
		global_accessed_items = {};
	}

	addOnunloadFunction('postReadHistory', postReadHistory);
}

//--------------------------------------------------------------------------
// FoaF Explorer
//--------------------------------------------------------------------------

function FoaFExplorerURI() {return 'http://xml.mfd-consult.dk/foaf/explorer/';}

function openFoaFExplorerView(foaf_uri)
{
	window.open(FoaFExplorerURI()+'?foaf='+ escape(foaf_uri), 'FoaF_Explorer');
}

//--------------------------------------------------------------------------
// Bulkfeeds, Feedback
//--------------------------------------------------------------------------

function bulkfeedsURI() {return 'http://bulkfeeds.net/'; }
function bulkfeedsViewURI() {return bulkfeedsURI()+'app/view';} 
function bulkfeedsItemSearchRSSURI() {return bulkfeedsURI()+'app/search2.rdf';}
function bulkfeedsSimilaritySearchURI() {return bulkfeedsURI()+'app/similar';} 
function feedbackURI() {return 'http://naoya.dyndns.org/feedback/';}
function feedbackItemSearchRSSURI() {return feedbackURI() + 'app/rss';}


// 
function openRSSInfo(rss_uri)
{
	window.open(bulkfeedsViewURI() + '?u=' + escape(rss_uri), 'rss_info');
}

function openSimilaritySearch(uri)
{
	window.open(bulkfeedsSimilaritySearchURI() + '?url=' + escape(uri) + '&sort=date', 'similarity_search');
}


// 
// engine : 'bulkfeeds', 'feedback'
// keyword: string
function make_query_uri_for_search_engine(engine, keyword)
{
	keyword = escape(keyword);
	
	switch(engine.toLowerCase()) {
	case 'bulkfeeds' : 
		return bulkfeedsItemSearchRSSURI() + '?q='+keyword+'&sort=date';
		break;
	case 'feedback'  : 
		return feedbackItemSearchRSSURI() + '?keyword=' + keyword;
		break;
	default : 
		return '';
		break;
	}
	
}

function make_query_uri_window(form, css_uri, js_uri)
{
	var title = 'RNA::Select search engine and Input keyword';
	var form_name = form.name;

	var sub_win = window.open('', 'set_uri_from_search_engine', 'width=500,height=100,titlebar=no,toolbar=no,menubar=no,status=no,resizable=yes');
	sub_win.document.clear();
	sub_win.document.write('<html><head><meta http-equiv="Content-Type" content="text/html\; charset=UTF-8"><meta http-equiv="Content-Script-Type" content="text/javascript"><title>' + title + '</title>'
		+ '<link rel="stylesheet" href="' + css_uri + '" type="text/css">'
		+ '<script type="text/javascript" src="' + js_uri + '"></' + 'script>'
		+ '</head>' + "\n"
		+ '<body>' + "\n"
		+ '<h2>' + title + '</h2>' + "\n"
		+ '<form action="#" onsubmit="var l = opener.document.' + form_name + '.link; var s=l.form.subject; l.value=make_query_uri_for_search_engine(this.engine.value, this.keyword.value); s.value=this.engine.value; window.close(); l.focus(); l.select(); return false;">' + "\n"
		+ '<select name="engine"><option value="bulkfeeds">Bulkfeeds</option><option value="feedback">Feedback</option></select>'  + "\n"
		+ '<input type="text" name="keyword" size="60">'
		+ '<input type="submit" value="Input">'
		+ '</form>' + "\n"
		+ '</body>' + "\n"
		+ '</html>'
	);
	sub_win.document.close();
}

//--------------------------------------------------------------------------
// Authentication
//--------------------------------------------------------------------------

// check if the user is authorized.
function check_auth(is_protected, auth_cgi_uri)
{
	var c = document.cookie;

	if (is_protected) {
	// This page is protected
		if (c.match(/username/)) {
		// Authorized (Loose check)
			return true;
		}
		else{
		// Not authorized. Prompt user to login.
			var ret = confirm("Authentication Required. \nLogin?");
			if(ret){
				location.href
					= auth_cgi_uri + '?transfer=' + escape(location.href);
				return false;
			}
			else{
				return false;
			}
		}
	}
	else {
	// This page is not protected (login is not required) 
		return true;
	}

	return false;
}

//--------------------------------------------------------------------------
// del.icio.us
//--------------------------------------------------------------------------

function deliciousURI() {return 'http://del.icio.us/'; }
function deliciousUsernameLabel() { return "delicious_user";}
function deliciousTempUsernameLabel() { return "temp_delicious_user";}
function deliciousCacheExpireDay() { return 30;}

function cachedDeliciousUsername()
{
	var delicious_username_label = deliciousUsernameLabel();
	var temp_delicious_username_label = deliciousTempUsernameLabel();
	var username = '';

	// get username value from cookie
	var temp_username = getCookie(temp_delicious_username_label);
	if(temp_username == null) {
		username = getCookie(delicious_username_label);
	}
	else {
	// use temporary username
		username = temp_username;
	}

	return username;
}

function cacheDeliciousUsername(username, cookie_path)
{
	var delicious_username_label = deliciousUsernameLabel();
	var temp_delicious_username_label = deliciousTempUsernameLabel();
	var expire_day = deliciousCacheExpireDay();

	// delete cookie
	deleteCookie(delicious_username_label, cookie_path);

	// set cookie
	setCookie(delicious_username_label, username, 60*60*24*expire_day, cookie_path);
	setCookie(temp_delicious_username_label, username, '', cookie_path);

	return true;
}


// post to del.icio.us 
function openPostDelicious(username, url, title, extended, tags, cookie_path)
{
	var v = 2;
	var delicious_username_label = deliciousUsernameLabel();
	var temp_delicious_username_label = deliciousTempUsernameLabel();
	var window_name = "post_to_delicious_window";

	if(extended == '')
		extended = getSelectedString(extended);

	if(username == '') {
		// get username value from cookie
		var temp_username = getCookie(temp_delicious_username_label);
		if(temp_username == null) {
			username = getCookie(delicious_username_label);
			if(username == null || username == undefined)
				username = '';
			username
				=prompt('Please enter your useranme at del.icio.us.',username);
			if(username == null) 
				return false;
		}
		else {
		// use temporary username
			username = temp_username;
		}	
	}

	// set cookie
	cacheDeliciousUsername(username, cookie_path);

	window.open(deliciousURI() + encodeURIComponent(username) 
		+ '?v=' + v 
		+ '&url='      + encodeURIComponent(url) 
		+ '&title='    + encodeURIComponent(title) 
		+ '&tags='     + encodeURIComponent(tags) 
		+ '&extended=' + encodeURIComponent(extended), window_name);
}


// search tag (del.icio.us)
function openSearchTagsDelicious(tags, username)
{
	var window_name = "search_tag_from_delicious_window";

	var delicious_uri = deliciousURI();
	if(username == undefined || username == '' || username == null)	
		delicious_uri += 'tag/';
	else
		delicious_uri += encodeURIComponent(username) + '/';

	delicious_uri += encodeURIComponent(tags.replace(/\s+/g, '+'));
	//alert(delicious_uri);
	window.open(delicious_uri);
}



