/* Interaction Initiative WebSiteBrowser 
 * Copyright (c) 2008 Interaction Initiative Inc.
 * All rights reserved.
 */
var INTERACTION_ENABLED = false;	
var GOOGLEMAP_ENABLED = false;
var THUMBNAIL_ENABLED = true;
var USE_ALT_OBJECT = true;

var FOCUS_WIDGET = 'work'; 
var WIDGET_FRAME = {//[top, left, width, height, hidden]
	news:			[ '0%', '10%'],
	businessOutline:[ '8%', '18%', '', '', true],
	service:		['13%', '27%', '200px', '259px', true],
	work:			[ '8%', '42%', '400px', '450px'],
	accessMap:		['42%', '78%', '200px', '259px', true],
	companyProfile:	['19%', '15%', '', '', true],
	inquiry:		['60%',  '2%', '400px', '500px', true],
	aboutThisSite:	['63%', '24%', '', '', true],
	backgroundUploader: ['25%', '25%', '290px', '310px', true]
}
var DEFAULT_FRAME = ['20%', '20%', '400px', '300px'];

if (Prototype) {
	var ua = new UserAgent();
	INTERACTION_ENABLED = (ua.IE >= 6 && !ua.Opera) || ua.Firefox >= 2 || ua.Opera >= 8
						|| (ua.Safari > 500 && !ua.iPhone) || ua.Netscape >= 7;
	USE_ALT_OBJECT = ua.IE >= 6;
	Prototype.Browser.IE6 = Prototype.Browser.IE && ua.IE < 7;

	window.onload = function() {
		if (INTERACTION_ENABLED) {
			if (Prototype.Browser.IE6) {
				AlternateStyleSheet.add('./images/css/widget_ie6.css', ContentsBrowser.DEFAULT_STYLE);
			}
			AlternateStyleSheet.init();
			ContentsBrowser.init();
		}
		loading(true);
		document.body.focus();
	}
	if (INTERACTION_ENABLED && GOOGLEMAP_ENABLED) {
		var key = 'ABQIAAAAUJKc7xeQfFi9XKM0espBNRRnCKlPq4FXM0dhFDBkYoU4Df93uxR84AlhtqTmCQwYnjCxlfRDWY6M3A';
		document.writeln('<script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=' + key + '"></script>');
	}
}

function loading(done) {
	if (INTERACTION_ENABLED || done)
		document.body.style.visibility = done ? '' : 'hidden';
}

function reset() {
	iiPersistence.clear();
}

function debug(message) {
//	if (window.console) console.log(message);
//	window.status = message;
}
function dump(obj) {
	var s = obj + '\n';
	try { for (var i in obj) s += i + ': ' + obj[i] + '\n'; } catch (e) { s += e; }
	return s;
}

var ContentsBrowser = {
	DEFAULT_FONT_SIZE: '80%',
	DEFAULT_STYLE: 'Default',
	menu: null,
	widgets: [],
	contents: [],
	tabIndex: -1,
	ancIndex: -1,
	language: ['en', 'ja'],
	style: ['Default', 'HighContrast', 'Aural'],

	init: function() {
		iiPersistence.path = '/';
		if (this.setLanguage()) return; // redirect

		this.menu = this.init_menu();
		this.init_contents();
		this._display = this.display;
/*TODO
		var contentsMenu = this.menu.topMenuList[0].childMenu;
		for (var i = 0; i < this.contents.length; i++) {
			var a = this.contents[i].firstChild.getElementsByTagName('A')[0];
			if (contentsMenu[i + 1] && a)
				contentsMenu[i + 1].menuItem.href = '#' + a.name;
		}
*/
		if (this.menu) iiKey.addListener(this.menu);
		iiKey.addListener(this);

		this.setStyleSheet(this.getParameter('s'));
		if (iiPersistence.get('customBg')) {
			updateBackground(iiPersistence.get('customBg'));
		}
		this.setFontSize();

		AlternateStyleSheet.onchange = function(title) {
			ContentsBrowser.setStyleSheet(title);
		}
		Event.observe(document, 'click', AlternateStyleSheet.check)

		var contentsId = this.getParameter('c');
		if (contentsId != null) this.show(contentsId);
	},

	init_menu: function() {
//TODO
		if (!$('ii-menuList')) return null;
		if (location.href.lastIndexOf('/index_') == -1)
			menuStyle.imagePath = '.' + menuStyle.imagePath; 

		var menu = new iiMenu('ii-menuList', menuStyle);
		var group = 1;

		//コンテンツメニュー
		menu.setMenuAction(group++, function(event) {
			menu.hide();
//			return ContentsBrowser.show(this.parentNode.menuIndex - 1, event);
			return ContentsBrowser.show(this.parentNode.menuIndex - 1, this.parentNode);
		});

		//スタイルメニュー
		menu.setMenuAction(group++, function(e) {
			if (this.menuIndex == 3) {
				if (iiWidget.enabled) iiWidget.layout();
				return false;
			}
			ContentsBrowser.setStyleSheet(ContentsBrowser.style[this.menuIndex]);
			return false;
		});
//		menu.topMenuList[1].firstChild.ondblclick = function() {
//			if (AlternateStyleSheet.getActive() == ContentsBrowser.DEFAULT_STYLE) {
//				reset(); location.reload();
//			}
//   	}

/*		//プリントメニュー
		menu.setMenuAction(group++, function() {
			switch(this.menuIndex) {
			case 0:
				ContentsBrowser.preview();
				break;
			case 1:
				window.print();
				break;
			}
			return false;
		});
*/
		//フォントサイズ
		menu.setMenuAction(group++, function(e) {
			var size = parseInt(document.body.style.fontSize);
			var i = this.parentNode.menuIndex;
			if (i == 0)  {				
				size = size + 10 + '%';
			} else if (i == 1) {
				size = (size > 10 ? size - 10 : size) + '%';
			} else {
				size = ContentsBrowser.DEFAULT_FONT_SIZE;
			}
			ContentsBrowser.setFontSize(size);
			return (i < 2) ? stopEventPropagation(e) : false;
		});

		// 背景
		menu.setMenuAction(group++, function(e) {
			iiPersistence.set('customBg', '');
			if(iiWidget.enabled && iiWidget.backgroundUploader) {
				iiWidget.backgroundUploader.close();
				iiWidget.activateTop();
			}
			ContentsBrowser.setBackground(this.parentNode.menuIndex + 1);
			return false;
		});

		// 言語
		menu.setMenuAction(group++, function(e) {
			var lang = ContentsBrowser.language[this.parentNode.menuIndex];
			ContentsBrowser.setLanguage(lang);
			return false;
		});

		// 使い方
		if (menu.length >= group) {
			menu.topMenuList[group - 1].menuItem.onclick = function() {
				var guide = $('operation-guide');
//TODO			if (!guide) return false;
				if (!guide) return true;

				//var top = guide.offsetTop;
				//var prev = guide.previousSibling;
				//var top = prev.offsetTop + prev.clientHeight;
				var IE = Prototype.Browser.IE;
				var top = 0, delay = 0;
				var target = window;
				if (iiWidget.enabled) {
					if (!iiWidget.maximized || iiWidget.maximized.id != 'aboutThisSite') {
						ContentsBrowser.show(5);//TODO
						delay = 500;
					}
					target = $('aboutThisSite-detail').parentNode;

					if (!IE) top = -target.parentNode.firstChild.clientHeight;
				} else {
					ContentsBrowser.show(-1);

					if (IE && AlternateStyleSheet.getActive() == 'HighContrast')
						top += guide.parentNode.parentNode.offsetTop;
				}
				setTimeout(function() {
					if (IE && iiWidget.enabled) top += guide.parentNode.offsetTop;
			
					new iiEffect.scroll(target, 0, top + guide.offsetTop);
				}, delay);
				return false;
			}
		}
		return menu;
	},

	init_contents: function() {
		if (!$('contents')) return;
		var contents = select_element($('contents').childNodes);
		for (var i = 0; i < contents.length; i++) {
			if (contents[i].className == 'prWidget') {
				this.widgets.push($(contents[i]));
				continue;
			}
			if (contents[i].className != 'widget') continue;

			var content = $(contents[i]);
			this.contents.push(content);
			this.widgets.push(content);
			this.widgets[content.id] = content;

//			var gotoMenu = content.lastChild.getElementsByTagName('a')[3];
			var a = content.lastChild.getElementsByTagName('a');
			var gotoMenu = a[a.length - 1];

			gotoMenu.onclick = function() {
				ContentsBrowser.show(-1);
//				window.scrollTo(0, 0);
//				return false;
			}
			content.label = content.firstChild.firstChild; 
			content.anchors = $A(content.childNodes[1].getElementsByTagName('a'));
			content.anchors.push(gotoMenu);
		}
		return contents;
	},

	show: function(index, menu) {
		this._content = index;
		return this._display(index, menu);
	},
	_content: -1, // for preview

	display: function(index, menu) {
//TODO
		if (location.href.lastIndexOf('/index_') == -1 || menu && menu.hierarchy > 2) return true;

		for (var i = 0; i < this.contents.length; i++) {
			this.contents[i].style.display = (i == index || index == -1) ? '' : 'none';
		}
		iiKey.setActiveListener(index >= 0 ? this : this.menu);
		this.tabIndex = index;
//		return index == -1 ? false : true;
		return false;
	},

	onkeydown: function(e, code, shift, ctrl, alt) {
		if (shift && code != Event.KEY_TAB || ctrl || alt) return true;
		switch (code) {
		case Event.KEY_TAB:
			var index = this.tabIndex;
			var content = index >= 0 ? this.contents[index] : null;

			if (content && this.ancIndex >= 0 && this.ancIndex < content.anchors.length) {
				content.anchors[this.ancIndex].blur();
			}
			if (shift) {
				if (this.tabIndex < 0) {
					this.tabIndex = this.contents.length - 1;
					if (this.tabIndex < 0) return true; 

					content = this.contents[this.tabIndex];
					this.ancIndex = content.style.display == 'none' ? -1 : content.anchors.length;
				}
				while (this.ancIndex < 0) {
					if (--this.tabIndex < 0) return true;
					content = this.contents[this.tabIndex];
					if (content.style.display == 'none') continue;

					this.ancIndex = content.anchors.length;
					location.hash = content.label.name;
				}
				if (--this.ancIndex >= 0) {
					content.anchors[this.ancIndex].focus();
					return false;
				}
				location.hash = content.label.name;
				return false;
			}

			if (content && ++this.ancIndex < content.anchors.length) {
				content.anchors[this.ancIndex].focus();
				return false;
			}
			this.ancIndex = -1;
			while (++this.tabIndex < this.contents.length) {
				content = this.contents[this.tabIndex];
				if (content.style.display == 'none') continue;

				location.hash = content.label.name;
				return false;
			}
			this.tabIndex = -1;
		}
		return true;
	},

	getStyleSheet: function() {
		return iiPersistence.get('style') || this.DEFAULT_STYLE;
	},
	setStyleSheet: function(title) {
		title = title || this.getStyleSheet();
		if (!AlternateStyleSheet.setActive(title)) {
			title = this.DEFAULT_STYLE;
			AlternateStyleSheet.setActive(title);
		}
		if (title != 'print')
			iiPersistence.set('style', title);

		if (this._content != -1) this.show(-1); // for IE!

		var widgetEnabled = (title == this.DEFAULT_STYLE);
		if (widgetEnabled && !iiWidget.enabled) {
//TODO
			if (location.href.indexOf('/business/') != -1) {
				location.replace('../index_' + this.getLanguage() + '.html');
				return;
			}

			AccessMap.init();
///			iiWidget.init(this.contents);
			iiWidget.init(this.widgets);
			iiKey.replaceListener(ContentsBrowser, iiWidget);
			this._display = iiWidget.display;
			this._content = -1;

			this.setBackground();
		}
		if (!widgetEnabled && iiWidget.enabled) {
			AccessMap.dispose();
			iiWidget.dispose();
			iiKey.replaceListener(iiWidget, ContentsBrowser);
			this._display = this.display;
			this._content = -1;

			this.setBackground(0);
//			if (Prototype.Browser.IE6) location.reload();
		}

		if (!widgetEnabled) {
			var backgroundMenu = this.menu.topMenuList[3];
			backgroundMenu.menuDisabled = true;
			backgroundMenu.menuItem.style.color = '#AAAAAA';
		}
	},

	setBackground: function(index) {
		if (index == undefined) index = iiPersistence.get('bg') || 2;
		if (index < 0 && index > 3) return;
		if (index > 0)  iiPersistence.set('bg', index);

		var textColor = ['', '#000000', '#000000', '#FFFFFF', '#FFFFFF'][index];
		var bodyColor = ['', '#FFFFFF', '#B3DA41', '#454545', '#134585'][index];

//		if (Prototype.Browser.IE) {
//			this._addStyle(index, textColor, bodyColor);
//		} else {
			this._setStyle(index, textColor, bodyColor);
//		}
		var backgroundMenu = this.menu.topMenuList[3];
		if (index > 0) {
			backgroundMenu.menuDisabled = false;
			backgroundMenu.menuItem.style.color = textColor;

			if (THUMBNAIL_ENABLED) {
				var thumbnails = $('thumbnails').childNodes;
				for (var i = 0; i < thumbnails.length; i++) {
					thumbnails[i].firstChild.style.color = textColor;
				}
			}
		}
	},

	_setStyle: function(index, textColor, bodyColor) { // for Firefox,Safari,Opera
		var menu = this.menu.topMenuList;
		for (var i = 0; i < menu.length; i++) {
			menu[i].firstChild.style.color = textColor;
		}
		$('copyright').getElementsByTagName('P')[0].style.color = textColor;
		document.body.style.background = (index == 0) ? ''
				: bodyColor + ' url(./images/bitmap/bg_body_0' + index + '.jpg) right top no-repeat';
	},
/*	_rules: [],
	_addStyle: function(index, textColor, bodyColor) { // for IE,Firefox,Opera
		if (index < 1) return;
		var sheetIndex = AlternateStyleSheet.getIndex();
		for (var i = this._rules.length - 1; i >= 0; i--)
			AlternateStyleSheet.removeRule(this._rules[i], sheetIndex);

		this._rules[0] = AlternateStyleSheet.addRule('#home #header a', 'color:' + textColor, sheetIndex);
		this._rules[1] = AlternateStyleSheet.addRule('#footer p', 'color:' + textColor, sheetIndex);
		this._rules[2] = AlternateStyleSheet.addRule('body', 'background:'
				+ bodyColor + ' url(../bitmap/bg_body_0' + index + '.jpg) right top no-repeat', sheetIndex);
	},
*/
	setFontSize: function(size) {
		size = size || iiPersistence.get('fontSize') || this.DEFAULT_FONT_SIZE;
		document.body.style.fontSize = size;
		iiPersistence.set('fontSize', size);
	},

	setLanguage: function(lang) {
		lang = lang || this.getLanguage();
		if (lang) {
			lang = lang.substring(0, 2) == 'ja' ? 'ja' : 'en';
			iiPersistence.set('language', lang);

			var href = location.href;
			if (this.getStyleSheet() != this.DEFAULT_STYLE && href.indexOf('.html') != -1) {
				href = href.substring(0, href.lastIndexOf('_') + 1) + lang + '.html' + location.hash;
				if (href != location.href) {
					location.replace(href);
				}
				return true;
			}
//TODO
			var html = 'index_' + lang + '.html';
//			if (href.lastIndexOf(html) == -1) {
			if (href.lastIndexOf(html) == -1 || href.lastIndexOf('/xaml/') != -1) {
				var index = href.lastIndexOf('/business/');
				if (index != -1) html = href.substring(0, index + 1) + html;
				var id = iiWidget.idFromUri(href);
				if (id) iiPersistence.set('focus', id);
				location.replace(html);
				return true;
			}
		}
		return false;
	},

	getLanguage: function() {
		var lang = iiPersistence.get('language') || navigator.language || navigator.browserLanguage;
		return lang ? lang.substring(0, 2) : 'en'; 
	},

	getParameter: function(name) {
		var query = location.search;
		var index = query.indexOf(name)
		if (index == -1) return null;
		return query.substring(index + name.length + 1).split('&')[0];
	},

	preview: function() {
		if (window.ActiveXObject) {
			var object = create_element('object', {classid:'CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'});
			document.body.appendChild(object);
			object.ExecWB(7, 1);
		    document.body.removeChild(object);
		} else {
			var contentId = iiWidget.maximized ? iiWidget.maximized.widgetIndex : this._content; 
			window.open('?s=print&c=' + contentId);
		}
	}
}

var menuStyle = {
	imagePath: './images/bitmap/', 

	hideMenu: function(ul) {
		ul.style.top = '-9999px';
	},

	showMenu: function(ul) {
		ul.style.top = (ul.parentNode.hierarchy == 1) ? '1em' : '0em';

		if (ul.parentNode.hierarchy == 1)
			new iiEffect.Alpha(ul, 0, 100, 300);
	},

	focus: function(li, menu) {
		if (li.menuItem && li.hierarchy > 1) {
			li.menuItem.style.backgroundColor 	= '#CCCCCC';
			li.menuItem.style.color				= '#444';
		}
	},

	blur: function(li, menu) {
/*		if (li.hierarchy > 2) {
			li.menuItem.style.backgroundColor	= '#444';
			li.menuItem.style.color				= '#CCC';
		} else 
*/		if (li.hierarchy > 1) {
			var a = li.menuItem;
			if (a.effect) a.effect.cancel();

			a.effect = new iiEffect.Gray(a, 0x40, 0xC0, 400, 20);
			a.effect.onStop = function() {
				if (menu.currentItem) // && currentMenuItem.menuItem && currentMenuItem.parentMenu) 
					menuStyle.focus(menu.currentItem);
			}
		}
	},

	setMenuItemStyle: function(li) {
		if (li.hierarchy == 1) {
			li.style.cssFloat		= 'left';
			li.style.styleFloat		= 'left';
			li.style.marginRight	= '15px';
			li.style.position		= 'relative';
		} else {
			li.style.position		= 'relative';
			//li.style.marginBottom	= '1px';
			/*li.style.borderBottom	= 'solid 1px #555';
			li.style.borderLeft		= 'solid 1px #555';
			li.style.borderRight	= 'solid 1px #555';*/
			li.style.borderBottom	= 'solid 1px #000000';
			li.style.borderLeft		= 'solid 1px #000000';
			li.style.borderRight	= 'solid 1px #000000';

			if (li.menuItem && (!Prototype.Browser.IE || ua.IE==8)) {
				li.menuItem.style.display = 'block';
			}
			if (li.subMenu && li.menuItem) {
				li.style.zIndex		= '1';
				li.menuItem.style.backgroundImage		= 'url('+ this.imagePath +'bg_hasChildsSubMenu.gif)';
				li.menuItem.style.backgroundPosition	= 'right center';
				li.menuItem.style.backgroundRepeat		= 'no-repeat';
			}
			if (Prototype.Browser.IE6) li.style.width	= '10em';

///			if (li.hierarchy == 4) li.menuItem.style.width	= '16em'; //TODO
		}
		if (li.subMenu) {
			li.subMenu.style.position	= 'absolute';
			li.subMenu.style.top 		= '-9999px';
///			li.subMenu.style.left 		= (li.hierarchy == 1) ? '0em' : '10.1em';
			//li.subMenu.style.borderTop	= 'solid 1px #555';
			li.subMenu.style.borderTop = 'solid 1px #000000';
		}
	}
}

var AccessMap = {
	element: null,

	init: function() {
		var widget = $('accessMap');
		var map = $('accessMapP');
		if (!map) return;
		this.element = map;

		map.originalHTML = map.innerHTML;
		// 2009/09/25 - Disable google maps
		/*
		if (!Prototype.Browser.IE6) {
			map.innerHTML = '<iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.jp/maps?f=q&amp;source=s_q&amp;hl=ja&amp;geocode=&amp;q=%E6%9D%B1%E4%BA%AC%E9%83%BD%E5%8D%83%E4%BB%A3%E7%94%B0%E5%8C%BA%E4%B8%89%E5%B4%8E%E7%94%BA%EF%BC%92%E4%B8%81%E7%9B%AE%EF%BC%92%EF%BC%92%E2%88%92%EF%BC%91%EF%BC%98&amp;sll=-0.21955,151.257866&amp;sspn=76.820854,111.621094&amp;ie=UTF8&amp;ll=35.703102,139.751673&amp;spn=0.02091,0.025749&amp;z=14&amp;output=embed">'
				+ map.originalHTML + '</iframe>';

//			if (!Prototype.Browser.WebKit) {
				widget.onresize = function() {
					map.firstChild.height = map.parentNode.clientHeight + 'px';
				}
//			}
			return;
		}
		*/
		map.innerHTML = '';
		map.style.padding = 0;
		map.style.marginLeft = '0.4em';
		map.style.marginRight = '0.4em';
		map.style.marginTop = '0.9em';
		map.style.width = map.style.height = '100%';
		map.style.background = 'url(./images/bitmap/fig_access.gif) 50% 0% no-repeat';
		map.parentNode.style.overflowX = "hidden";

		var w = 720, h = 720;
		map.onmousedown = function(e) {
			if (iiWidget.activated != widget) {
				widget.activate();
				return false;
			}
			if (map.clientWidth >= w && map.clientHeight >= h) {
				return false;
			}
			var pos = map.getStyle('backgroundPosition').split('%');
			map._x = Math.floor(pos[0]*w/100);
			map._y = Math.floor(pos[1]*h/100);

			iiDrag.init(e, function(x, y) {
				x = (map.clientWidth < w) ? map._x - x : map._x;
				y = (map.clientHeight < h) ? map._y - y : map._y;
				x = x < 0 ? 0 : x > w ? 100 : Math.floor(x/w*100);
				y = y < 0 ? 0 : y > h ? 100 : Math.floor(y/h*100);
				map.style.backgroundPosition = x + '% ' + y + '%';
				return stopEventPropagation();
			});
			return false;
		}
		widget.onactivate = function(e) {
			map.parentNode.style.overflowX = "hidden";
		}
		widget.onresize = function() {
			var p = map.style.backgroundPosition.split(' ');
			if (widget.clientWidth >= w) {
				p[0] = '50%';
			}
			if (widget.clientHeight >= h) {
				p[1] = '0%';
				map.style.height = h + 'px';
			} else {
				map.style.height = '100%';
			}
			map.style.backgroundPosition = p[0] + ' ' + p[1];
		}
	},

	dispose: function() {
		var map = $('accessMapP');
		if (map && map.originalHTML) {
			map.innerHTML = map.originalHTML;

			// 2009/09/25 - Disable google maps
			//if (Prototype.Browser.IE6) {
				map.onmousedown = null;
				map.style.padding = '1em';
				map.style.background = '#000';
				map.style.width = map.style.height = '';
				map.parentNode.style.width = '';
			//}
		}
	},

	show: function(widget) {
		var map = this.element;
		// 2009/09/25 - Disable google maps
		/*
		if (map && widget.id == 'accessMap' && !Prototype.Browser.IE6) {
			map.style.display = '';
			map.firstChild.height = map.parentNode.clientHeight + 'px';
		}*/
	},

	hide: function(widget) {
		var map = this.element;
		// 2009/09/25 - Disable google maps
		/*
		if (map && widget.id == 'accessMap' && !Prototype.Browser.IE6) {
			map.style.display = 'none';
		}*/
	},

	cover: function(enabled) {
		var widget = $('accessMap');
		if (enabled && widget && !widget.hidden) {
			var div = document.createElement('DIV');
			div.id = 'accessMapCover';
			div.style.position = 'absolute';
			div.style.zIndex = ContentsBrowser.widgets.length + 1;
			iiWidget.setRect(div, widget.getRect());
			widget.parentNode.appendChild(div);
		}
		if (!enabled) {
			var div = $('accessMapCover');
			if (div) div.remove();
		}
	}
}

var iiWidget = function(widget) {
	Object.extend($(widget), this);

	widget.onclick = this.activate.bind(widget, true);
	//widget.style.display = ''; IE crash!!

	var parts = select_element(widget.childNodes);
	parts[0].onmouseover = function() { this.style.cursor = 'move'; }
	parts[0].onmousedown = this._move.bind(widget);
	parts[0].ondblclick = this.maximize.bind(widget);
	parts[0].onselectstart = function() { return false; }

	parts[1].style.overflow = 'hidden';

	var icons = parts[2].firstChild.childNodes; 
	icons[0].onclick = this.maximize.bind(widget);
	icons[1].onmousedown = this._resize.bind(widget);
	icons[2].onclick = this.close.bind(widget);
	icons[2].firstChild.href = "";

	widget.parts = parts;
	widget.icons = icons;
	widget.margin = parts[0].clientHeight + parts[2].clientHeight;
	var a = $A(parts[1].getElementsByTagName('a'));
	widget.nodes = (a.length > 1) ? a : [parts[1]];
	widget.nodes.unshift(icons[0].firstChild);
	widget.activeNode = 0;
	widget.activeIcon = 0;

	widget.widgetIndex = iiWidget.widgets.length;
	iiWidget.widgets.push(widget);

	widget.setOpacity(iiWidget.translucent);

//TODO	
	widget.links = $(parts[1]).select('ul.dir a','ul.subDir a');
	for (var i = 0; i < widget.links.length; i++) {
		a = widget.links[i];
		iiWidget.link(a, true);
		
		a.parentWidget = widget;
		a.onclick = function(e) {
			iiWidget.load(this.widgetId, this.widgetUrl, this);
			return stopEventPropagation(e);
		}
	}
	return widget;
}

iiWidget.idFromUri = function(uri) {
	if (!uri) return null;
	var map = {
		about:'aboutThisSite', access:'accessMap',
		business:'businessOutline'/*'mission'?*/, company:'companyProfile'
	}  
	var from = uri.lastIndexOf('/') + 1;
	var to = uri.lastIndexOf('_');
	if (from < to) {
		var id = uri.substring(from, to);
		return map[id] ? map[id] : id;
	}
	return null;
}

iiWidget.link = function(a, icon) {
	var href = a.href; // a.getAttribute('href'); 

	var id = iiWidget.idFromUri(href);
	if (id) {
		a.widgetId = id;
		var url = iiWidget.linkMap[id];
		if (url) {
			a.widgetUrl = url;
		} else {
			url = href.substring(0, href.lastIndexOf('_'));
			a.widgetUrl = url
			iiWidget.linkMap[id] = url;
		}
		if (icon) iiWidget.iconMap[id] = a;
	}
}

iiWidget.enabled = false;
iiWidget.widgets = [];
iiWidget.activated = null;
iiWidget.maximized = null;
iiWidget.minimumWidth = 200;
iiWidget.minimumHeight = 142; //200;
iiWidget.opaque = 1.01;
iiWidget.translucent = 0.5;
iiWidget.transparent = 0.4;

iiWidget.linkMap = {}; // id: url
iiWidget.loadMap = {}; // id: iiWidget
iiWidget.iconMap = {}; // id: a

iiWidget.prototype = {
//	_private:
	_move: function(e) {
		if (this.busy) return false;
		if (this.isMaximized) return false;

		this.activate();

		this.top = iiWidget.top2px(this.style.top);
		this.left = iiWidget.left2px(this.style.left);
		iiDrag.init(e, this._drag.bind(this), this.saveRect.bind(this));
		return false;
	},

	_drag: function(x, y, e) {
		x += this.left;
		y += this.top;
		var w = screenWidth - this.clientWidth - contentsMargin;
		var h = contentsHeight ;//- this.clientHeight; if (h < 0) h = contentsHeight;

		x = (x < contentsMargin) ? contentsMargin : (x > w) ? w : x;
		y = (y < 0) ? 0 : (y > h) ? h : y;

		this.style.top = iiWidget.px2top(y);
		this.style.left = iiWidget.px2left(x);
		
		return false;
	},

	_resize: function(event) {
		if (this.busy) return false;
		AccessMap.cover(true);
		if (!iiWidget.effect.busy && !this.isMaximized) {
			new iiWidget.effect(this, function() {
				this.saveRect();
				if (this.onresize) this.onresize();
				AccessMap.cover(false);
			}.bind(this)).resize(event);
		}
		return false;
	},

	_focus: function() {
		this.style.display = '';
		this.activeNode = 0;
		this.activeIcon = 0;
		try {
			this.icons[0].firstChild.focus();
		} catch (e) {debug(e.message);}
	},

//	public:

	maximize: function(e) {
		if (this.busy) return false;
		debug('maximize: ' + this.id);
		if (!iiWidget.effect.busy) {
			new iiWidget.effect(this, function() {
				this.busy = false;
				if (this.onresize) this.onresize();
			}.bind(this)).maximize();
		}
		iiKey.setActiveListener(iiWidget);
		
		SWFVisibleOnOff($('iPhoneDemoSWF'),this,true);

		if (this.thumbnail) {
			this.thumbnail.style.backgroundImage = this.thumbnailDisable;
		}
		return stopEventPropagation(e || window.event); // for IE
	},

	activate: function(e) {
		if (this.busy) return false;
		if (iiWidget.activated == this) return true;
		debug('activate: ' + this.id);
//TODO
		if (iiWidget.activated) {
			iiWidget.activated.inactivate();
//		} else {
//			iiWidget.inactivate();
		}
		iiWidget.activated = this;

		this.hidden = false;
		this.style.display = '';
		this.parts[1].style.overflow = 'auto';
		this.setOpacity(iiWidget.opaque);
		iiWidget.activate(this);

		if (!e) this._focus();
		if (this.onactivate) this.onactivate();
		iiKey.setActiveListener(iiWidget);
//		iiPersistence.set('focus', this.widgetIndex);
		
		SWFVisibleOnOff($('iPhoneDemoSWF'),this,true);
		/*-081217nomura-*/
		if(this == iiWidget.backgroundUploader) {
			$('backgroundUploaderObject').style.display = '';
		}
		return false;
	},

	inactivate: function() {
		if(this == iiWidget.backgroundUploader) {
			$('backgroundUploaderObject').style.display = 'none';
		}
		this.parts[1].style.overflow = 'hidden';
		this.setOpacity(iiWidget.translucent);
		if (iiWidget.activated == this) iiWidget.activated = null;
		
		SWFVisibleOnOff($('iPhoneDemoSWF'),this,false);
		
	},

	open: function() {
		if (this.busy) return;
		if (iiWidget.maximized) iiWidget.maximized.maximize(); 
		if (!this.hidden) {
			this.activate();
			return;
		}
		debug('open: ' + this.id);

		this.activate();
		this.setOpacity(0);
		this.busy = true;

		AccessMap.hide(this);

		var callback = function() {
			this.busy = false;
			this.activate();
			this.saveRect();
			AccessMap.show(this);
		}.bind(this);

		if (this.thumbnail || this.thumbnailIcon) {
			if (this.thumbnailDisable) this.thumbnail.style.backgroundImage = this.thumbnailDisable; 

			var r = this.savedRect;
			new iiWidget.effect(this, callback).move(r.top, r.left, r.width, r.height, 1);
		} else {
			var alpha = new iiEffect.Alpha(this, 0, iiWidget.opaque*100, 700);
			alpha.onStop = callback;
		}
		
		SWFVisibleOnOff($('iPhoneDemoSWF'),this,true);
		
	},

	close: function(e) {
		if (this.hidden || this.busy) return false;
		this.busy = true;
		debug('close: ' + this.id);

		if (this.isMaximized) {
			this.isMaximized = false;
			iiWidget.maximized = null;
			iiWidget.toggle();
			//this.restore();
		}
		if (iiWidget.activated == this) iiWidget.activated = null;

		this.hidden = true;
		this.saveRect(this.savedRect);
		AccessMap.hide(this);

		var callback = function() {
			this.busy = false;
			this.style.display = 'none';
			AccessMap.show(this);

			if (this.thumbnail) {
				this.thumbnail.style.backgroundImage = this.thumbnailEnable;
			}
			iiWidget.activateTop();
//TODO
			if (iiWidget.loadMap[this.id]) {
				iiWidget.remove(this, true);
			}
		}.bind(this);
//TODO
		if (!this.thumbnailIcon) this.thumbnailIcon = iiWidget.iconMap[this.id];

		var r = null;
		if (this.thumbnail || this.thumbnailIcon) {
			r = iiWidget.getThumbnailRect(this);
			if (r) new iiWidget.effect(this, callback).move(r.top, r.left, r.width, r.height, 0);
		}
		if (!r) {
			var alpha = new iiEffect.Alpha(this, 100, 0, 700);
			alpha.onStop = callback;
		}
		return stopEventPropagation(e || window.event);
	},

	toggle: function() {
		if (this.busy) return;
		this.hidden ? this.open() : this.close();
	},

	getRect: function() {
		return iiWidget.getRect(this);
	},

	setRect: function(rect) {
//TODO	if (!rect) return;
		iiWidget.setRect(this, rect);
		var height = parseInt(rect.height) - this.margin;
		this.parts[1].style.height = (height < 0 ? 0 : height) + 'px'; 
		this.parts[1].style.width = rect.width;
		this.parts[2].style.width = rect.width;
	},

	saveRect: function(rect) {
		var r = (rect && rect.top) ? rect : this.getRect();
//TODO
		if (parseFloat(r.top) - parseInt(r.top) != 0) r.top = Math.round(parseFloat(r.top)) + '%';
		if (parseFloat(r.left) - parseInt(r.left) != 0) r.left = Math.round(parseFloat(r.left)) + '%';

		iiPersistence.set(this.id, [r.top, r.left, r.width, r.height, this.hidden ? '0' : '1'].join(','));
		debug('saveRect: ' + this.id + ' ' + r.top + ' ' + r.left + ' ' + r.width + ' ' + r.height + ' ' + this.hidden);
		return this.savedRect = r;
	},

	restore: function() {
		if (this.savedRect)
			this.setRect(this.savedRect);
	},

	moveTo: function(top, left, w, h, hidden) {
		if (top instanceof Array) { left = top[1]; w = top[2]; h = top[3]; hidden = top[4]; top = top[0]; }
		if (w && parseInt(w) < iiWidget.minimumWidth) w = iiWidget.minimumWidth + 'px';
		if (h && parseInt(h) < iiWidget.minimumHeight) h = iiWidget.minimumHeight + 'px';
		
		left = iiWidget.adjustLeft(this, left);
		if (w && h) {
			this.setRect({top:top, left:left, width:w, height:h});
		} else {
			this.style.top = top;
			this.style.left = left;
		}
		this.hidden = hidden;
		this.saveRect();
		if (hidden) {
			this.style.display = 'none';
			this.setOpacity(0);
			if (THUMBNAIL_ENABLED && this.thumbnail)
				this.setRect(iiWidget.getRect(this.thumbnail));
		}
		if (this.onresize) this.onresize();
	},

	dispose: function() {
		this.onclick = null;
		this.parts[0].onmouseover = null;
		this.parts[0].onmousedown = null;
		this.parts[0].ondblclick = null;

		this.style.width = '';
		this.style.height = '';
		this.style.display = '';
		this.setOpacity(1);

		this.parts[1].style.overflow = '';
		this.parts[1].style.height = '';
		this.parts[1].style.width = '';
		this.parts[2].style.width = '';

		for (var i = 0; i < this.links.length; i++) {
			this.links[i].onclick = null;
		}
	}
}

iiWidget.dispose = function() {
	var widgets = ContentsBrowser.widgets;
	for (var i = 0; i < widgets.length; i++) {
		widgets[i].dispose();
	}
	iiWidget.widgets.length = 0;
	window.onresize = null;

	iiWidget.maximized = null;
	iiWidget.activated = null;

	var contents = $('contents');
	contents.style.position = 'static';
	contents.style.height = '';
	var footer = $('footer'); 
	footer.style.position = 'static';
	footer.style.top = '';

//TODO
	var load = iiPersistence.get('load');
	if (load) {
		load.split('.').each(function(id) {
			iiWidget.remove(iiWidget.loadMap[id]);
		});
	}

	Element.remove($('contents').lastChild); // thumbnails

	iiWidget.enabled = false;
}

iiWidget.init = function(contents) {
	iiWidget.adjust();

	if (THUMBNAIL_ENABLED) {
		var thumbnails = $('menu-contents').lastChild.cloneNode(1);
		thumbnails.id = 'thumbnails';
		thumbnails.removeChild(thumbnails.firstChild);

		$('contents').appendChild(thumbnails);
		thumbnails = thumbnails.childNodes;
	}
	var index = 0;
	for (var i = 0; i < contents.length; i++) {
		contents[i].style.zIndex = i + 1;
		if (contents[i].className == 'prWidget') {
			new prWidget(contents[i], index++);
			continue;
		}
		var widget = new iiWidget(contents[i], index++);

		var frame = iiPersistence.get(widget.id);
		if (frame) {
			frame = frame.split(',');
//			if (frame[4] == undefined) {
//				frame = null;
//			} else {
				frame[4] = frame[4] == 0;
//			}
		}
		if (!frame) {
			frame = WIDGET_FRAME[widget.id];
		}
		if (THUMBNAIL_ENABLED && thumbnails[i] && frame) {
			widget.thumbnail = thumbnails[i];
			widget.thumbnailEnable = 'url(./images/bitmap/icon/icon_widget_' + (i + 1) + '.gif)';
			widget.thumbnailDisable = 'url(./images/bitmap/icon/icon_widget_' + (i + 1) + '_disable.gif)';
			var title =  thumbnails[i].firstChild.innerHTML.split(' ')[0];
			thumbnails[i].title = title;
			thumbnails[i].style.background = 'transparent ' + (frame[4] ? widget.thumbnailEnable : widget.thumbnailDisable) + ' top center no-repeat';
			thumbnails[i].widget = widget;
			thumbnails[i].onclick = function() { this.widget.open(this); return false; } //{ this.widget.toggle(this); }

			thumbnails[i].firstChild.innerHTML = title;
			thumbnails[i].firstChild.style.background = '';
			while (thumbnails[i].childNodes.length > 1) {
				thumbnails[i].removeChild(thumbnails[i].lastChild);
			}
		}
		if (frame) widget.moveTo(frame);
	}

//TODO
//	var menu = ContentsBrowser.menu.topMenuList[0].childMenu[3].subMenu;
	var menu = $('menu-contents').childNodes[1].childNodes[3].childNodes[1];
	if (menu) {
		$A(menu.getElementsByTagName('a')).each(function(a) { iiWidget.link(a); });
	}

//TODO
	var focus = iiPersistence.get('focus') || FOCUS_WIDGET;

	var load = iiPersistence.get('load');
	if (load) {
		load.split('.').each(function(id) {
			if (id != focus)
				iiWidget.load(id, iiWidget.linkMap[id]);
		});
	}
//TODO
setTimeout(function() {
	var widget = ContentsBrowser.widgets[focus];
	if (!widget) {
		iiWidget.load(focus, iiWidget.linkMap[focus], iiWidget.iconMap[focus]);
	} else if (widget.hidden) {
		widget.open();
	} else {
		widget.activate();
	}
}, 1000);
	iiWidget.enabled = true;
}


iiWidget.load = function(id, url, a) {

	if (!url) return;
	url += '_' + ContentsBrowser.getLanguage() + '.html';

	//TODO
	var loaded = iiWidget.loadMap[id];// || document.getElementById(id);

	if (iiWidget.maximized && loaded != iiWidget.maximized) {
		iiWidget.minimize();
	}
	if (loaded) {
		loaded.activate();
		return;
	}
	debug('load: ' + id + ' url=' + url);

	new Ajax.Request(url, {
		"method": "get",
		"parameters": new Date().getTime().toString(),
		onComplete: function(request) {
//			alert('Complete');
	
			var content = null;

			var dom = document.createElement('div');
			dom.innerHTML = request.responseText;;

			var div = dom.getElementsByTagName('div');
			for (var i = 0; i < div.length; i++) {
				if (div[i].id == id/* && div[i].className == 'widget'*/) {
					iiWidget.add(div[i], a);
					return;
				}
				if (div[i].id == 'contents') {
					content = div[i];
				}
			}
			if (content) {
				var title = dom.getElementsByTagName('title')[0] || '';
				if (title) title = title.firstChild.nodeValue.split(' @')[0];
				iiWidget.create(id, title, content.innerHTML, a);
			} else {
				iiWidget.create(id, 'Error', '<font color="darkgrey">' + dom.innerHTML +  '</font>', a);
			}
		},
//TODO
		onSuccess: function(request) {
//			alert('Success');
		},
		onFailure: function(response) {
//			alert('Failure\nURL: ' + url + '\nstatus: ' + response.status);
		},
		onException: function (request, e) {
//			alert('Exception\nURL: ' + url + '\n' + dump(e));
		}
	});
	iiWidget.alphaEnabled = iiWidget.enabled;
}

iiWidget.create = function(id, title, content, a) {
	debug('create: ' + id);
	var resource = {
		en: ['Details', 'Resize', 'Close', 'Back to Menu'],
		ja: ['詳細', 'リサイズ', '閉じる', 'メニューに戻る']
	};
	var text = resource[ContentsBrowser.getLanguage()];

	var widget = document.createElement('div');
	widget.id = id;
	widget.className = 'widget';

	widget.innerHTML = //'<div id="' + id + " class="widget">' + 
			'<h2 class="widgetLabel"><a name="' + id + 'A" id="' + id + 'A">' + title + '</a></h2>'
		+	'<div class="widgetContents">' + content + '</div>'
		+	'<div class="widgetFooter">'
		+		'<ul>'
		+			'<li class="fullScreen"><a href="index.html">' + text[0] + '</a></li>'
		+			'<li class="resize"><a>' + text[1] + '</a></li>'
		+			'<li class="close"><a>' + text[2] + '</a></li>'
		+			'<li class="goToMenu"><a href="#menu-contentsA">' + text[3] + '</a></li>'
		+		'</ul>'
		+	'</div>'

	return iiWidget.add(widget, a);
}

iiWidget.createIFrame = function(id, title, url) {
	return iiWidget.create(id, title, '<iframe src="' + url + '" style="width:100%; height="100%;"></iframe>');
}

//TODO
iiWidget.px2top  = function(px) { return Math.round(px/contentsHeight*100) + '%'; }
iiWidget.px2left = function(px) { return Math.round(px/screenWidth*100) + '%'; }
iiWidget.top2px  = function(top) { return Math.round(parseFloat(top)*contentsHeight/100); }
iiWidget.left2px = function(left) { return Math.round(parseFloat(left)*screenWidth/100); }

iiWidget.getThumbnailRect = function(widget) {
//TODO

	if (widget.thumbnail) {
		var r = iiWidget.getRect(widget.thumbnail);
//		alert(dump(r));
		return r;
	}
	var icon = widget.thumbnailIcon;
	var parent = widget.parentWidget || icon.parentWidget;
	while (parent && parent.hidden) {
		if (parent.thumbnail) {
			return iiWidget.getRect(parent.thumbnail);
		}
		if (parent.thumbnailIcon) {
			icon = parent.thumbnailIcon;
		}
		parent = parent.parentWidget;
	}
//TODO
//alert('parent=' + parent + ' hidden=' + (parent ? parent.hidden : 'null') + '\na=' + a);
	if (!parent) return null;
		
	var offset = icon.cumulativeOffset();
	offset.top -= icon.parentWidget.parts[1].scrollTop + headerHeight;
	offset.left -= icon.parentWidget.parts[1].scrollLeft;

	return {top: iiWidget.px2top(offset.top), left: iiWidget.px2left(offset.left), width: '33px', height: '33px'};
}

iiWidget.add = function(div, a) {
	debug('add: ' + div.id);

	$('contents').appendChild(div);

	widget = new iiWidget(div);
//	widget.setOpacity(0);
//TODO
//	if (!a) a = iiWidget.iconMap[widget.id];
//	widget.thumbnailIcon = a ? a : null;
//	a = iiWidget.iconMap[widget.id];
	widget.thumbnailIcon = a || iiWidget.iconMap[widget.id];

	ContentsBrowser.widgets.push(widget);
	widget.style.zIndex = ContentsBrowser.widgets.length;

	var r = iiPersistence.get(widget.id);
	r = r ? r.split(',') : (WIDGET_FRAME[widget.id] || DEFAULT_FRAME);
	widget.moveTo(r);
//TODO
	var opened = false;
	if (a && a.parentWidget) {
		widget.parentWidget = a.parentWidget;
		widget.hidden = true;
		var r = iiWidget.getThumbnailRect(widget);
		if (r) {
			widget.setRect(r);
			widget.open();
			opened = true;
		}
	}
	if (!opened) {
		widget.hidden = false;
		if (iiPersistence.get('focus') == widget.id) {
			widget.activate();
		} else {
			widget.inactivate();
			widget.style.display = '';
		}
	}

//TODO
	if (widget.id == 'work4') SWFRunContent();

	iiWidget.loadMap[widget.id] = widget;
	iiPersistence.set('load', $H(iiWidget.loadMap).keys().join('.')); 
	return widget;
}

iiWidget.remove = function(widget, save) {
	debug('remove: ' + widget.id);

	var i = iiWidget.widgets.indexOf(widget);
	if (i != -1) iiWidget.widgets.splice(i, 1);

	i = ContentsBrowser.widgets.indexOf(widget);
	if (i != -1) ContentsBrowser.widgets.splice(i, 1);

//TODO
	delete iiWidget.loadMap[widget.id];

	if (save) {
		iiPersistence.set('load', $H(iiWidget.loadMap).keys().join('.'));
		iiWidget.activateTop();
	}
	widget.remove();
}



iiWidget.adjust = function() {
	if (!$('header')) return;
	var ie = Prototype.Browser.IE;
	screenHeight = ie ? document.body.parentNode.clientHeight : window.innerHeight;
	screenWidth = ie ? document.body.parentNode.clientWidth : window.innerWidth;
	headerHeight = $('header').clientHeight;
	footerHeight = $('footer').clientHeight;
	contentsHeight = screenHeight - headerHeight;
	if (contentsHeight < 0) contentsHeight = 0;
	$('contents').style.position = 'relative';
	$('contents').style.height = contentsHeight + 'px';
	$('footer').style.position = 'absolute';
	$('footer').style.top = screenHeight - footerHeight + 'px';
	contentsMargin = $('footer').firstChild.offsetLeft;
	contentsWidth = screenWidth - contentsMargin*2;

	var x = contentsMargin/screenWidth*100;
	var w = contentsWidth;
	var h = contentsHeight - footerHeight;

	if (x < 1) x = 1;
	if (w < iiWidget.minimumWidth) w = iiWidget.minimumWidth; 
	if (h < iiWidget.minimumHeight) h = iiWidget.minimumHeight;
	iiWidget.contentRect = {
		top: '0%',
		left: x + '%', 
		width: w + 'px',
		height: h + 'px'
	}
//TODO
//	var overflow = false;
	for (var i = 0; i < iiWidget.widgets.length; i++) {
		var widget = iiWidget.widgets[i];
		widget.style.left = iiWidget.adjustLeft(widget, widget.style.left);

//		if (!widget.hidden && widget.offsetLeft + widget.clientWidth > screenWidth) overflow = true;
	}
//	document.body.style.overflowX = overflow ? 'scroll' : '';
	if (iiWidget.maximized) {
		if (Prototype.Browser.Gecko || Prototype.Browser.Opera) {
			iiWidget.maximized.isMaximized = false;
			iiWidget.maximized.maximize();
		} else {
			//Prototype.Browser.IE || Prototype.Browser.WebKit
			iiWidget.maximized.setRect(iiWidget.contentRect);
		}
	}
	window.onresize = iiWidget.adjust;
}

iiWidget.adjustLeft = function(widget, left) {
	if (screenWidth <= 0) return '1%';
	if (left) {
		var min = contentsMargin;
		var max = screenWidth - widget.clientWidth;
//TODO
//		var max = screenWidth - contentsMargin - widget.clientWidth;
		var x = parseInt(left)*screenWidth/100;
		if (x < min)
			//return Math.floor(min/screenWidth*100) + '%';
			return iiWidget.px2left(min);
		if (x > max && max >= 0) {
			//return Math.floor(max/screenWidth*100) + '%';
			return iiWidget.px2left(max);
		}
	}
	return left;
}

iiWidget.getRect = function(element) {
	var display = element.style.display;
	element.style.display = '';
	var r = {
//TODO
//		top: element.style.top || element.offsetTop/contentsHeight*100 + '%',
//		left: element.style.left || element.offsetLeft/screenWidth*100 + '%',
		top: element.style.top || iiWidget.px2top(element.offsetTop),
		left: element.style.left || iiWidget.px2left(element.offsetLeft),
		width: element.clientWidth + 'px',
		height: element.clientHeight + 'px'
	};
	element.style.display = display;
	return r;
},

iiWidget.setRect = function(element, rect) {
//TODO
if (!rect) return;
	var style = element.style;
	style.top = rect.top;
	style.left = rect.left;
	style.width = rect.width;
	style.height = rect.height;
}

iiWidget.maximize = function(i) {
	var widget = iiWidget.widgets[i];
	if (widget) {
		widget.activate();
		widget.maximize();
	}
}

iiWidget.minimize = function() {
	if (iiWidget.maximized) {
		iiWidget.maximized.maximize(false);
	}
}

iiWidget.display = function(index, menu) {
	debug('display: ' + i);
	if (menu && menu.hierarchy > 2) {
		var a = menu.menuItem;
//TODO
		iiPersistence.set('focus', a.widgetId);
		var icon = iiWidget.iconMap[a.widgetId];
		iiWidget.load(a.widgetId, a.widgetUrl, icon);
		return false;
	}
	if (index == -1) {
		iiWidget.minimize();
	} else {
		var widget = iiWidget.widgets[index];
		if (widget) {
			THUMBNAIL_ENABLED ? widget.maximize() : widget.toggle();
		}
	}
	return stopEventPropagation(iiKey.event);
}

iiWidget.activateTop = function() {
	if (iiWidget.activated) return;
	var widgets = ContentsBrowser.widgets;
	var z = 0;
	var index;
	for (var i = 0; i < widgets.length; i++) {
		if (widgets[i].hidden/* || widgets[i].className != 'widget'*/) continue;
		if (z < parseInt(widgets[i].style.zIndex)) {
			z = parseInt(widgets[i].style.zIndex);
			index = i;
		}
	}
	if (z > 0) widgets[index].activate();
}

iiWidget.activate = function(widget) {
//TODO
	var widgets = ContentsBrowser.widgets;
	var z, zIndex = parseInt(widget.style.zIndex);
	for (var i = 0; i < widgets.length; i++) {
		if ((z = parseInt(widgets[i].style.zIndex)) >= zIndex) {
			widgets[i].style.zIndex = --z < widgets.length ? z : widgets.length - 1;
		}
		if (Prototype.Browser.IE) widgets[i].style.visibility = 'visible';
	}
	widget.style.zIndex = widgets.length;
	iiPersistence.set('focus', widget.id);
}

iiWidget.inactivate = function() {
//	var widgets = iiWidget.widgets;
	var widgets = ContentsBrowser.widgets;
	for (var i = 0; i < widgets.length; i++) {
		var widget = widgets[i];
		if (!widget.hidden) { // && widget != iiWidget.activated) {
			widget.inactivate();
		}
	}
	iiWidget.activated = null;
}

iiWidget.toggle = function() {
	iiWidget.widgets.each(function(widget, index) {
		widget.style.display = (iiWidget.maximized && iiWidget.maximized != widget || widget.hidden) ? 'none' : '';
	});
}

iiWidget.activateNext = function(index, reverse, rotate) {
	var len = iiWidget.widgets.length;
	for (var i = 0; i < len; i++) {
		index += reverse ? -1 : 1;
		if (!rotate && (index < 0 || index >= len)) return false;
		index = (index + len) % len;
		if (!iiWidget.widgets[index].hidden) {
			iiWidget.widgets[index].activate();
			return true;
		}
	}
	return false;
}


//TODO
iiWidget.onkeydown = function(e, code, shift, ctrl, alt) {
	if (shift && code == 36) {
		iiEventAction.WIDGETS.enableBackgroundUploader();
		return false;
	} else if (shift && code != Event.KEY_TAB || ctrl || alt) return true;

	var widget = iiWidget.activated;
	var index = widget ? widget.widgetIndex : -1;
	var len = iiWidget.widgets.length;
	switch (code) {

	/*case 36: // HOME
		iiWidget.widgets[6].open();
		return false;
		break;*/
	case 32: // SPACE
		if (widget && widget.nodes.length == 2) {
			widget.activeNode = 1 - widget.activeNode;
			widget.nodes[widget.activeNode].focus();
			return false;
		}
		break;
	case Event.KEY_UP:
	case Event.KEY_DOWN:
//		var active = document.activeElement || window.getSelection().focusNode;
		if (!widget) break;
		if (widget.activeNode == 1 && widget.nodes.length == 2) break;

		var i = widget.activeNode + (code == Event.KEY_UP ? -1 : 1);
		widget.activeNode = (i + widget.nodes.length) % widget.nodes.length;  
		widget.nodes[widget.activeNode].focus();
		
		return false;

	case Event.KEY_LEFT:
	case Event.KEY_RIGHT:
		if (widget && widget.activeNode == 0) {
			var icon = widget.activeIcon;
			if (icon == 0 && code == Event.KEY_RIGHT) icon = 2;
			else if (icon == 2 && code == Event.KEY_LEFT) icon = 0;

			if (icon != widget.activeIcon) {
				widget.activeIcon = icon;
				widget.icons[icon].firstChild.focus();
				return false;
			}
		}
		if (index != -1 && !iiWidget.maximized) {
			return !iiWidget.activateNext(index, code == Event.KEY_LEFT, true);
		}
		break;
	case Event.KEY_TAB:
		if (len == 0) return true;
		if (iiWidget.maximized) {
			iiWidget.maximized._focus();
			return true;
		}
		if (index == -1) {
			return !iiWidget.activateNext(shift ? iiWidget.widgets.length : -1, shift, false);
		} else if (iiKey.getActiveListener() != iiWidget) {
			iiWidget.widgets[index]._focus();
			return false;
		}
		if (iiWidget.activateNext(index, shift, false)) {
			return false;
		} else {
			iiWidget.activated.inactivate();
		}
	}
	return true;
}

//TODO
iiWidget.layout = function() {
	if (iiWidget.maximized) return;

	var H = contentsHeight - footerHeight;
	var cols = 3;
	var n = iiWidget.widgets.length;
	var w = Math.floor(screenWidth/cols);
	var h = Math.floor(H/(n + 1)*cols);
	for (var i = 0; i < n; i++) {
		var widget = iiWidget.widgets[i];
		var x = Math.floor((i % cols)*w/screenWidth*100) + 1 + '%'; 
		var y = Math.floor(Math.floor(i / cols)*h/H*100) + '%';
//		widget.setOpacity(iiWidget.opaque);
//		iiWidget.widgets[i].moveTo(y, x, w - 10 + 'px', h - 10 + 'px');

		new iiWidget.effect(widget, function() {
//			new iiEffect.Alpha(this, 101, 80, 400);
			if (this.onresize) this.onresize();
		}.bind(widget)).move(x, y, w, h);
		return;
	}
}

iiWidget.effect = function(widget, callback) {
	this.widget = widget;
	this.callback = callback;
	this.resizeV = Prototype.Browser.IE6 ? 2 : 3;
}

iiWidget.effect.style = {
//	border		: 'solid 1px #666',
	background	: '#eee',
	zIndex		: 1000,
	opacity		: iiWidget.transparent,
	filter		: 'alpha(opacity=40)'
}

iiWidget.effect.queue = [];

iiWidget.effect.prototype = {
	resize: function(e) {
		this.widget.activate();
		this.targetRect = this.widget.getRect();
		this.targetArea = this._createTargetArea(this.targetRect);

		if (Prototype.Browser.IE6) {
			this.targetArea.style.border = 'solid 1px #666'; 
			this.targetArea.style.zIndex = 1000;
		} else
		Object.extend(this.targetArea.style, iiWidget.effect.style);

		iiDrag.init(e, this._resize.bind(this), this._effect.bind(this), 'nw-resize');
	},

	maximize: function() {
		this.widget.activate();
		var adjust = false;
		if (this.widget.isMaximized = !this.widget.isMaximized) {
			this.targetRect = iiWidget.contentRect;

			if (this.widget != iiWidget.maximized) {
///				this.widget.saveRect();
				if (iiWidget.maximized) {
					iiWidget.maximized.restore();
					iiWidget.maximized.isMaximized = false;
				}
//TODO
			} else adjust = true;
			iiWidget.maximized = this.widget;
		} else {
			this.targetRect = this.widget.savedRect;
			iiWidget.maximized = null;
		}
		if (!adjust) iiWidget.toggle();
		this._effect();
	},

	move: function(top, left, w, h, alpha) {
		this.targetRect = this.widget.getRect();
		this.targetRect.top = top;
		this.targetRect.left = left;
		if (w) this.targetRect.width = w;
		if (h) this.targetRect.height = h;
		this.targetAlpha = alpha;
		this.resizeV = 4;
		this._effect();
	},

//	_private;
	_createTargetArea: function(rect) {
		var area = document.createElement('DIV');
		area.style.position = 'absolute';
		iiWidget.setRect(area, rect);
		this.widget.parentNode.appendChild(area);
		return area;
	},

	_resize: function(x, y) {
		var w = this.widget.clientWidth + x;
		var h = this.widget.clientHeight + y;
		var maximumWidth = screenWidth - contentsMargin - this.widget.offsetLeft;
		if (w > maximumWidth) w = maximumWidth;
		if (w < iiWidget.minimumWidth) w = iiWidget.minimumWidth;
		if (h < iiWidget.minimumHeight) h = iiWidget.minimumHeight;
		this.targetArea.style.width = w + 'px';
		this.targetArea.style.height = h + 'px';
		return stopEventPropagation();
	},

	_effect: function() {
		iiWidget.effect.busy = true;
//TODO
//		this.targetTop = parseInt(this.targetRect.top)*contentsHeight/100; 
//		this.targetLeft = parseInt(this.targetRect.left)*screenWidth/100;
		this.targetTop = iiWidget.top2px(this.targetRect.top);
		this.targetLeft = iiWidget.left2px(this.targetRect.left);
		this.targetWidth = parseInt(this.targetArea ? this.targetArea.style.width : this.targetRect.width); 
		this.targetHeight = parseInt(this.targetArea ? this.targetArea.style.height : this.targetRect.height);

		this.opacity = iiWidget.transparent; // Element.getOpacity(this.clone);
		var interval = 50;
		this.timeout = 1000/interval;
		this.timer = setInterval(this._animate.bind(this), interval);
		return false;
	},

	_ease: function(from, to, scale) {
		return (from + (to - from)/this.resizeV)/scale*100 + '%';
	},

	_animate: function() {
		if (!this.isDeleting) {
			var widget = this.widget;
			var target = this.targetRect;
			var dw = this.targetWidth - widget.clientWidth;
			var dh = this.targetHeight - widget.clientHeight;

			var r = widget.getRect();
			if ((dw*dw + dh*dh > 10 || r.top != target.top || r.left != target.left) && --this.timeout > 0) {
				r.width = widget.clientWidth + dw/this.resizeV + 'px';
				r.height = widget.clientHeight + dh/this.resizeV + 'px';
				if (r.top != target.top) r.top = this._ease(widget.offsetTop, this.targetTop, contentsHeight);
				if (r.left != target.left) r.left = this._ease(widget.offsetLeft, this.targetLeft, screenWidth);

				widget.setRect(r);
				if (this.targetAlpha != undefined) {
					var alpha = widget.getOpacity();
					widget.setOpacity(alpha + (this.targetAlpha - alpha)/this.resizeV);
				}
			} else {
//				widget.setRect(target);
				this.isDeleting = true;
			}
		} else {
			this.opacity -= 0.1;
			if (this.targetArea) Element.setOpacity(this.targetArea, this.opacity);
			if (this.opacity <= 0) {
				clearInterval(this.timer);
				if (this.targetArea) Element.remove(this.targetArea);
				if (this.callback) this.callback();
				iiWidget.effect.busy = false;
			}
		}
	}
}

var prWidget = function(widget, index) {
	this.img = widget.getElementsByTagName('img')[0];
	this.widgetIndex = index;
	this.activated = false;

	var p = iiPersistence.get(widget.id);
	if (p) {
		p = p.split(',');
		widget.style.top = p[0];
		widget.style.left = p[1];
	}
	return Object.extend(widget, this);
}

prWidget.prototype = {
	dispose: function() {
		this.onmouseover = null;
		this.onmousedown = null;
		this.onclick = null;
		this.img.style.cursor = 'pointer';
	},

	activate: function() {
		iiWidget.inactivate();
		iiWidget.activate(this);
		this.activated = true;
	},

	inactivate: function() {
		this.activated = false;
	},

	isActive: function() {
//		return this.style.zIndex == ContentsBrowser.widgets.length;
		return this.activated;
	},
	
	onmouseover: function(e) {
		this.img.style.cursor = this.isActive() ? 'pointer' : 'move';
	},

	onmousedown: function(e) {
		this.dragged = false;
		this.active = this.isActive();

		this.activate();

		this.top = this.offsetTop;
		this.left = this.offsetLeft;
		iiDrag.init(e, this.onDrag.bind(this), this.onDrop.bind(this));
		return false;
	},

	onclick: function(e) {
		this.img.style.cursor = 'pointer';
		//pr2
//		if(this.widgetIndex == 9 && this.active && !this.dragged){
//			iiWidget.widgets[6].open();
		if(this.widgetIndex == 7 && this.active && !this.dragged){
			iiWidget.widgets[4].open();
			return false;
		}
//		return !this.dragged;
		return this.active && !this.dragged;

	},
	
	onDrag: function(x, y) {
		if (x != 0 || y != 0) {
			this.dragged = true;
			iiWidget.prototype._drag.apply(this, arguments);
		}
		return false;
	},

	onDrop: function() {
		if (this.dragged) {
			var pos = this.style.top + ',' + this.style.left;
			iiPersistence.set(this.id, pos);
		}
	}
}

var iiEventAction = {
	WIDGETS: {
		enableBackgroundUploader: function() {
			if(!document.getElementById('backgroundUploader')) {
				var resource = {
					en: ['Background', 'Drag&amp;Drop an image here.'],
					ja: ['背景', '背景にしたい画像をここにドラッグ&amp;ドロップしてください。']
				};
				var text = resource[ContentsBrowser.getLanguage()];
				var currentBackgroundUrl = document.body.style.backgroundImage.substr(4, document.body.style.backgroundImage.length-5);
				// for Opera
				if(currentBackgroundUrl.indexOf('"') >= 0) {
					currentBackgroundUrl = currentBackgroundUrl.substr(1, currentBackgroundUrl.length-2);
				}
				var objectCode = '<object id="backgroundUploaderObject" classid="java:jp/co/ii/utilities/BackgroundUploader.class" type="application/x-java-applet" archive="./images/jar/commons-codec-1.4.jar,./images/jar/commons-httpclient-3.1.jar,./images/jar/commons-logging-1.1.1.jar,./images/jar/BackgroundUploader.jar" width="220" height="165">'
						+ '<param name="code" value="jp/co/ii/utilities/BackgroundUploader.class" />'
						+ '<param name="bgImage" value="' + currentBackgroundUrl + '" />'
						+ '</object>';
				if(USE_ALT_OBJECT) {
					objectCode = '<object id="backgroundUploaderObject" classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" codebase="http://java.sun.com/update/1.6.0/jinstall-6u13-windows-i586.cab" width="220" height="165">'
						+ '<param name="code" value="jp/co/ii/utilities/BackgroundUploader.class" />'
						+ '<param name="archive" value="./images/jar/commons-codec-1.4.jar,./images/jar/commons-httpclient-3.1.jar,./images/jar/commons-logging-1.1.1.jar,./images/jar/BackgroundUploader.jar" />'
						+ '<param name="bgImage" value="' + currentBackgroundUrl + '" />'
						+ '</object>';
				}
				var content = '<p>' + text[1] + '</p>'
					+	'<p>' + objectCode + '</p>';
				iiWidget.backgroundUploader = iiWidget.create('backgroundUploader', text[0], content, document.createElement('a'));
			}
			iiWidget.backgroundUploader.open();
			iiWidget.activateTop();
		}
	}
};

function SWFVisibleOnOff(swfObj,widgetObj,visibility){
	var displayState = (visibility) ? "block" : "none";
	if(widgetObj.id=="work4" && swfObj) swfObj.style.display = displayState;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

//  document.write(str);
  var flash = $('iPhoneDemoSWF');
  if (flash) {
	  flash.innerHTML = str;
	  flash.generated = true;
  }
}

function SWFRunContent(swf) {
	if ($('iPhoneDemoSWF').generated) return;
	AC_FL_RunContent(
		'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
		'width', '300',
		'height', '225',
		'src', 'images/swf/movie_intro',
		'quality', 'high',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'showall',
		'wmode', 'window',
		'devicefont', 'false',
		'id', 'movie_intro',
		'bgcolor', '#ffffff',
		'name', 'movie_intro',
		'menu', 'true',
		'allowFullScreen', 'false',
		'allowScriptAccess','sameDomain',
		'movie', 'images/swf/movie_intro',
		'salign', ''
	);
}

function updateBackground(imgLocation) {
	var backgroundColor = "#3d3c3c";
	var textColor = "#ddd";
	iiPersistence.set('customBg', imgLocation);
	//ContentsBrowser.setBackground(1);
	document.body.style.backgroundColor = backgroundColor;
	document.body.style.backgroundImage = 'url(' + imgLocation + ')';
	document.body.style.backgroundPosition = 'center top';
	$('copyright').getElementsByTagName('P')[0].style.color = textColor;
	for(var i = 0; i < ContentsBrowser.menu.topMenuList.length; i++) {
		ContentsBrowser.menu.topMenuList[i].menuDisabled = false;
		ContentsBrowser.menu.topMenuList[i].menuItem.style.color = textColor;
	}
	if (THUMBNAIL_ENABLED) {
		var thumbnails = $('thumbnails').childNodes;
		for (var j = 0; j < thumbnails.length; j++) {
			thumbnails[j].firstChild.style.color = textColor;
		}
	}
}

