var _system = {
	settings: new Array(),
	url:'',
	focus:null,
	d:null
};

function init()
{
	var start = init1();

	if(!start) {
		/* undisplay cover */
		document.getElementById('gray1').style.display = 'none';
	}
}

function init1() {

	if(!location.search) {
		return 0;
	}

	var q = location.search.slice(1);
	var s = q.split('&');
	var url = '';
	var pathes = new Array();

	for(var i = 0; i < s.length; i++) {
		var r = s[i].split(/=/, 2);
		if( r.length == 2 ) {
			switch( r[0] ) {
			case 'url':
				var url = decodeURIComponent(r[1]);
				url = url.replace(/\s*$/,'');
//				if( ! url.match(/^https?:\/\//) ) url = 'http://' + url;
				break;
			case 'path[]':
				var path = decodeURIComponent(r[1]);
				pathes.push(path);
				break;
			}
		}
	}

	if (url) {
		document.url.url.value = url;
		setup_new(url,pathes);
		return 1;
	} else {
		return 0;
	}
}

function setup_new(url,path)
{
	/* display cover */
	document.getElementById('gray1').style.display = '';

	if (path == undefined) {
		path = new Array();
	}
	_system.settings = path;

	_system.url = url;
//	top.page.location.replace('./redirect/test.html?url=' + encodeURIComponent(_system.url));
	top.page.location.replace('./redirect/?url=' + encodeURIComponent(_system.url));
	/* load() will be called after completion */
}

function load()
{
	/* check frame document is NOT blank.html */
	if( _system && _system.url ) {
		var url = top.page.location.search.split(/[\?\&]/);
		for(var i = 0; i < url.length; i++) {
			if( url[i].match(/^url=(.*)$/) ) {
				/* redirected url */
				_system.url = decodeURIComponent(RegExp.$1);
				/* wait completion of server-side dom */
				load1();
				return;
			}
		}
	}
}

function load1()
{
	/* initialize dom inspector */
	_system.d = new DOMInspector(top.page);
	_system.d.setCallbackIni(callback_ini);
	_system.d.setCallbackDom(callback_dom);
//	_system.d.setTag('a');
	_system.d.setSelMode(1);
	_system.d.initialize();
}

function add(item)
{
	var div = document.getElementById('portions');

	if( div.childNodes.length >= 20 )
	{
		alert('20を超える部分を指定できません．\n既存の指定部分を削除した後，再度操作してください．');
		return null;
	}
	else
	{
		if( div.firstChild && div.firstChild.portion && div.firstChild.portion.form.type.value == 'all' )
		{
			if( confirm('重複があるため既存の指定部分を削除します．\n操作を続けますか？') )
			{
				/* remove existing portions */
				while( div.firstChild ) div.removeChild(div.firstChild);
			}
			else
			{
				return null;
			}
		}
	}

	var portion = new Portion();
	div.insertBefore(portion.container, div.firstChild);
	portion.focus();

	/* default type */
	if(item)
	{

		if (item == '/') {
			//all
			portion.form.type.value = 'all';
			portion.form.type.onchange();
			callback_all();
		} else if (item.substr(0,3) == '//*') {
			//id
			portion.form.type.value = 'id';
			portion.form.type.onchange();
			callback_id(item);
		} else {
			//dom
			portion.form.type.value = 'dom';
			portion.form.type.onchange();
			callback_dom_main(item);
		}
	}
	else
	{
		portion.form.type.value = 'dom';
		portion.form.type.onchange();
	}

	/* cutin */
//	portion.cutin();

	return portion;
}

function ok(status)
{
	var url;
//f.link.value.normalize()

	url = './reg/?url=' + encodeURIComponent(_system.url);
	var portions = document.getElementById('portions').childNodes;
	for(var i = 0; i < portions.length; i++) {
		var o = portions[i].portion;

		url += '&path[]=';
		url += encodeURIComponent(o.form.dom.value);
	}
	window.location.href=url;
	return true;
}

function Portion()
{
	var self = this;

	var container = this.container = document.createElement('div');
	container.className = 'portion';
	container.portion = this;
//	container.onclick = function(){self.focus()};

	var head = this.head = document.createElement('div');
	head.className = 'head';
	head.onclick = function(){self.focus()};
	container.appendChild(head);

	/* close box */
	var close = document.createElement('div');
	close.className = 'close';
	close.innerHTML = 'X';
	close.onclick = function(){
		if(self==_system.focus)_system.focus=null;
		_system.d.deactivate();
		/* hide controller */
		top.document.getElementById('controller').style.display = 'none';
		self.cutout();
	}
	head.appendChild(close);

	var content = document.createElement('div');
	content.className = 'content';
	head.appendChild(content);

	var body = this.body = document.createElement('div');
	body.className = 'body';
	container.appendChild(body);

	/* body content */
	var form = this.form = document.createElement('div');
	form.className = 'content';
	body.appendChild(form);

	/* dom by head content */
	var dom = form.dom = document.createElement('input');
	dom.style.width = '210px';
	dom.style.border = '0 dotted';
	dom.style.backgroundColor = '#cccccc';
	dom.onkeydown = function(e){
		var e = e || window.event;
		var keycode = e.keyCode;
		switch( keycode )
		{
		case 13: // enter
			var dom = self.form.dom && self.form.dom.value || null;
			if (dom) {
				_system.d.setTree(dom);
				_system.d.display_dom(dom);
				top.document.getElementById('controller').style.display = '';
			}
			callback_dom_main(dom);
			break;
		default:
			break;
		}

	}
	content.appendChild(dom);
	var br = document.createElement('br');
	content.appendChild(br);

	/* create select */
	new Select(this);

	/* preview */
	var preview = this.preview = document.createElement('div');
	preview.className = 'preview';
	form.appendChild(preview);

	/* preview utilities */
	this.items = new Array();

	this.insert = function(title, link)
	{
		var item = {title:title, link:link, checked:true};
		this.items.push(item);

//      var o = document.createElement('input');
//      o.type = 'checkbox';
//      o.value = link;
//      preview.appendChild(o);
//      o.checked = true;
//      o.checked = this.exceptions && this.exceptions[link] ? false : true;
//      o.onclick = function(){item.checked=this.checked;};
//      preview.appendChild(document.createTextNode(' '))

		var a = document.createElement('a');
		a.href = link;
		a.innerHTML = item.title.truncate(170).normalize();
		a.target = '_blank';
		preview.appendChild(a);

		preview.appendChild(document.createElement('br'))

		document.getElementById('ok').disabled = false;
	}

	this.resize = function()
	{
		with( this.form.style )
		{
			height = '';
			overflow = '';
		}

		if( this.container.offsetHeight > 200 )
		{
			with( this.form.style )
			{
				height = '160px';
				overflow = 'scroll';
			}
		}
	}

	this.clear = function()
	{
		items = new Array();
		preview.innerHTML = '';
	}

	this.focus = function()
	{
		if( _system.focus ) _system.focus.blur();

		self.container.className = 'portion_focused'
		_system.focus = self;

		if( self.form.type )
		{
			var dom = self.form.dom && self.form.dom.value || null;

			if (dom) {
				_system.d.setTree(dom);
				_system.d.display_dom(dom);
				top.document.getElementById('controller').style.display = '';
			}
			/* activate dom inspector */
			_system.d.activate();
			/* sctivate contol */
		}
	}

	this.blur = function()
	{
		self.container.className = 'portion';
	}

	this.cutout = function()
	{
		var dummy = document.createElement('div');
		dummy.id = 'dummy';
		dummy.style.width = container.offsetWidth + 'px';
		dummy.style.height = container.offsetHeight > 100 ? '100px' : container.offsetHeight + 'px';
		dummy.containerHeight = container.offsetHeight;

		dummy.effect = function()
		{
			var h = dummy.offsetHeight - 50;
			if( h > 50 )
			{
				dummy.style.height = h + 'px';
			}
			else
			{
				dummy.parentNode.removeChild(dummy);

				var portions = document.getElementById('portions').childNodes;
				if( portions.length == 0 ) {
					//portionがすべて削除された場合ボタンをdisable
					document.getElementById('ok').disabled = true;
					add();
				} else if (_system.focus==null) {
					//アクティブななければ一番上をアクティブ
					portions[0].portion.focus();
					_system.d.activate();
				}
				return;
			}
			setTimeout('document.getElementById("dummy").effect()', 200);
		}

		container.parentNode.insertBefore(dummy, container);
		container.parentNode.removeChild(container)

		setTimeout('document.getElementById("dummy").effect()', 200);
	}

	this.cutin = function()
	{
		var dummy = document.createElement('div');
		dummy.id = 'dummy';
		dummy.style.width = container.offsetWidth + 'px';
		dummy.style.height = '5px';
		dummy.containerHeight = container.offsetHeight;

		dummy.effect = function()
		{
			var h = dummy.offsetHeight + 50;

			if( h < dummy.containerHeight - 50 )
			{
				dummy.style.height = h + 'px';
			}
			else
			{
				dummy.parentNode.removeChild(dummy);
				container.style.display = '';
				return;
			}
			setTimeout('document.getElementById("dummy").effect()', 200);
		}

		container.style.display = 'none';
		container.parentNode.insertBefore(dummy, container);

		setTimeout('document.getElementById("dummy").effect()', 200);
	}
}

function Select(portion)
{
	var sel = portion.form.type = document.createElement('select');
	portion.form.appendChild(sel);
	sel.options[0] = new Option('マウスで指定', 'dom', false, false);
	sel.options[1] = new Option('IDで指定', 'id', false, false);
	sel.options[2] = new Option('全体を指定', 'all', false, false);

	var content1 = document.createElement('div');
	portion.form.appendChild(content1);

	sel.onchange = function()
	{
		/* focus */
		portion.focus();

		/* clear */
		portion.clear();
		content1.innerHTML = '';
//		content1.style.display = 'none';
		content1.style.fontSize = '20px';
		content1.style.color = '#999999';
		portion.resize();

		this.options.length = 3;
		_system.focus.form.dom.value = '';

		_system.d.deactivate();
		/* hide controller */
		top.document.getElementById('controller').style.display = 'none';

		switch( sel.value )
		{
		case 'dom':
			break;

		case 'id':
			var f = function(s,a,o){if(o.id&&o.getElementsByTagName('a').length)s.options[s.options.length]=new Option(o.id,'//*[@id="' + o.id + '"]',false,false);};

			var s = portion.form.element = select('選択してください', f);
			content1.style.display = '';
			content1.appendChild(document.createTextNode('└'));
			content1.appendChild(s);
			content1.appendChild(document.createElement('br'));
			s.onchange = function(){portion.focus();if(s.value)callback_id(s.value)};
			break;

		case 'all':
			callback_all();
			break;

		}

		/* activate dom inspector to edit existing portion */
		_system.d.activate();

		function select(note, f)
		{
			var a = [];
			var s = document.createElement('select');
			s.options[0] = new Option(note, '', false, false);
			traverse(top.page.document.body, s, a, f);
			return s;

			function traverse(o, s, a, f)
			{
				f(s, a, o);
				for(var i = 0; i < o.childNodes.length; i++) traverse(o.childNodes[i], s, a, f);
			}
		}
	}
}






function callback_view(dom) {
	_system.focus.form.dom.value = dom;

	/* for prototype */
	var o = _system.d.getElement(dom);

	if(o.snapshotLength) {


		var buf = new Array();
		for(var i = 0; i < o.snapshotLength; i++) {
			buf = buf.concat(links2str(o.snapshotItem(i).tagName == 'A' ? [o.snapshotItem(i)]: o.snapshotItem(i).getElementsByTagName('A')));
		}
/*
		var i = o.snapshotItem(0);
		var buf = buf.concat(links2str(i.tagName == 'A' ? [i]: i.getElementsByTagName('A')));
*/
		create_prototype(_system.focus, buf);

		/* display */
		if( buf.length ) {
			_system.d.display_dom(dom);
			top.document.getElementById('controller').style.display = '';
		}
	} else {
		alert('記事を選択できません．');
	}
}

//function callback_dom(o) {
//	callback_dom_main(_system.d.getAddress(o));
//}
function callback_dom(dom) {
	callback_dom_main(dom);
}

function callback_dom_main(dom) {
	if (_system.focus.form.type.value != 'dom') {
		_system.focus.form.type.value = 'dom';
		_system.focus.form.type.onchange();
	}
	callback_view(dom);
}

function callback_id(dom)
{
	callback_view(dom);
}

function callback_all()
{
	var dom = '/';
	callback_view(dom);
}







function links2str(a)
{
	var buf = new Array();
	for(var i = 0; i < a.length; i++) {
		var img = a[i].getElementsByTagName('IMG');
		var text = getText(a[i]);

		if( ! text && img.length ) {
			text = img[0].getAttribute('alt');
			if( text ) text = '[img]' + text;
		}

		var href = a[i].getAttribute('href');
		if( href ) {
			if( text && href.match(/^http[s]?:\/\//) ) {
				text = text.replace(/<[^>]*>/g, '').normalize(); 
				buf.push(text);
				buf.push(href);
			}
		}
	}
	return buf;

	function getText(node)
	{
		var text = '';
		if ( node.nodeType == 3 ) text += node.nodeValue;
		for (var i = 0; i < node.childNodes.length; i++) text += getText(node.childNodes[i]);
		return text;
	}
}





























function callback_click() {
	if( _system.focus ) {
		if( _system.focus.form.type.value ) add();
	} else {
		add();
	}
}

function callback_ini() {
	/* check frames */
	var f = top.page.document.body.getElementsByTagName('frame');
	if( f.length ) {
		/* messages */
		controller.frames();

		var page = document.getElementById('page');
		var s = _system.d.getRect(window, page);
		for(var i = 0; i < f.length; i++) {
			/* surpress scroll & resize */
			f[i].scrolling = 'no';
			f[i].noResize = true;

			var r = _system.d.getRect(top.page, f[i]);
			r.width = s.left + r.right < s.right ? r.width : s.width - r.left;

			if( r.height > 0 && r.width > 0 ) {
				//var img = new Image();
				var img = document.createElement('img');
				img.style.position = 'absolute';
				img.style.top = s.top + r.top - 1 + 'px';
				img.style.left = s.left + r.left - 1 + 'px';
				img.style.width = r.width + 'px';
				img.style.height = r.height + 'px';
				img.style.border = '1px solid #ffffff';
				img.style.filter = 'alpha(opacity=80)';
				img.style.zIndex = 100;
				img.style.cursor = 'pointer';
				img.src = './img/gray.png';
//				img.title = decodeURIComponent(f[i].src.split('url=')[1]);
				img.title = f[i].src;

				document.body.appendChild(img);

				img.onclick = function()
				{
//上記で作成した画像を全部消す(未対応)
//					var page = document.getElementById('page');
//					while( page.firstChild ) page.removeChild(page.firstChild);

					setup_new(this.title);
//					top.location.href = '/rss/tss2/?url=' + encodeURIComponent(this.title)
				}
			}
		}
	} else {
		/* rewrite form action */
		document.getElementById('ok').value =
								_system.settings.length ? 'フィードを変更' : 'フィードを作成';

		/* set button */
		document.getElementById('ok').onclick = ok;

		/* set title */
//		document.getElementById('channel').innerHTML = '';
		document.getElementById('page_title').innerHTML =
																					top.page.document.title ?
																					top.page.document.title.slice(0,50) :
																					'non title';

		controller.reset();

		/* add portion */
		for(var i = 0, all = false; i < _system.settings.length; i++ ) {
			var item = _system.settings[i];
			add(item);
		}
		if (_system.settings.length == 0) {
			add();
		}

		controller.partial1();

		/* activate button */
		document.getElementById('add').disabled = false;

	}

	/* undisplay cover */
	document.getElementById('gray1').style.display = 'none';

	/* stop unexpected loading on Firefox */
	try {window.stop();} catch(e) {}
}













function create_prototype(o, buf)
{
	if( o )
	{
		o.clear();
		for(var i = 0; i < buf.length; i+=2) o.insert(buf[i], buf[i + 1]);
		o.resize();
	}
}

function getElementById(node, id)
{
	if (node.nodeType == 1 && node.getAttribute('id') == id)
	{
		return node;
	}
	for(var i = 0; i < node.childNodes.length; i++)
	{
		var n = getElementById(node.childNodes[i], id);
		if (n != null)
		{
			return n;
		}
	}
	return null;
}













String.prototype.normalize = function()
{
	return this.replace(/&/g,'&amp;').replace(/&amp;([a-z]+|#[x]?[0-9a-fA-F]+);/g,'&$1;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;');
}

String.prototype.truncate = function(width, className)
{
	/* initialize truncation buffer */
	var buf = String.prototype.truncation_buffer;
	if( ! buf )
	{
		buf = String.prototype.truncation_buffer = document.createElement('nobr');
		if( className ) buf.style.className = className;
		buf.style.visibility = 'hidden';
		document.body.appendChild(buf);
	}

	var length = this.length;
	var result;

	buf.innerHTML = result = this;
	if( buf.offsetWidth > width )
	{
		while( --length )
		{
			buf.innerHTML = result = this.slice(0, length) + '...';
			if( buf.offsetWidth < width ) break;
		}
	}

	return result;
}














var $ = document.getElementById;

var controller = {

	reset:function(){
		var div = document.getElementById('portions');
		if( div.firstChild ) {
			while( div.firstChild ) div.removeChild(div.firstChild);
			_system.d.undisplay();
			_system.d.deactivate();
			/* hide controller */
			top.document.getElementById('controller').style.display = 'none';
		}
	},

	frames:function(){
		controller.show(document.getElementById('frames_top'));
	},

	partial:function(){
		controller.reset()
		controller.partial1();

		var e = document.getElementById('partial');
		if(e) e.disabled = true;
	},

	partial1:function(){
		controller.show(document.getElementById('target_partial'));
		document.getElementById('color').disabled = false;
	},

	show:function(s){
		if(s)s.style.display = '';
	},

	hide:function(s){
		if(s)s.style.display = 'none';
	},

	end_of_object:null
}
