/**
 *	関心空間基本スクリプトライブラリ
 */

var Kanshin = {
	show: function(pane) { if ($(pane)) $(pane).style.display = 'block'; }, 
	
	hide: function(pane) { if ($(pane)) $(pane).style.display = 'none'; },
	
	showHide: function(show) {
		for (var i = 1; i < arguments.length; ++i) {
			Kanshin.hide(arguments[i]);
		}
		Kanshin.show(show);
	}, 
	
	buildUrl: function(url) {
		if (arguments.length > 1) {
			var sep = (url.indexOf('?') < 0 ? '?' : '&');
			
			for (var i = 1; i < arguments.length; ++i) {
				url += sep;
				sep = '&';
				
				url += arguments[i];
			}
		}
		
		return url;
	},
	
	jump: function(url) {
		url = Kanshin.buildUrl.apply(this, arguments);
		window.location.href = url;
	},
	
	openTo: function(target, url) {
		if (target == '_top') {
			top.location.href = url;
		} else {
			window.open(url, target);
		}
	},
	
	confirm: function(msg) {
		return confirm(msg);
	}, 
	
	alert: function(msg) {
		alert(msg);
	},
	
	set: function(req) {
		var url = '/api/set?' + req + '&dt=' + (new Date()).getTime();
		return new Ajax.Request(url, { method: 'get' });
	},
	
	window: {
		pageScroll: function() {
			var x, y;
			
			if (self.pageYOffset) {
				x = self.pageXOffset;
				y = self.pageYOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {
					// Explorer 6 Strict
				x = document.documentElement.scrollLeft;
				y = document.documentElement.scrollTop;
			} else if (document.body) {
					// all other Explorers
				x = document.body.scrollLeft;
				y = document.body.scrollTop;
			}
			
			return { x: x, y: y };
		}, 
		
		// HTMLのコンテンツ領域のサイズ
		contentSize: function() {
			var w, h;
			
			if (window.innerHeight && window.scrollMaxY) {	
				w = document.body.scrollWidth;
				h = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight) {
					// all but Explorer Mac
				w = document.body.scrollWidth;
				h = document.body.scrollHeight;
			} else {
					// Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				w = document.body.offsetWidth;
				h = document.body.offsetHeight;
			}
			
			return { width: w, height: h };
		},
		
		// ウィンドウのサイズ
		frameSize: function() {
			var w, h;
			
			if (self.innerHeight) {
					// all except Explorer
				w = self.innerWidth;
				h = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) {
					// Explorer 6 Strict Mode
				w = document.documentElement.clientWidth;
				h = document.documentElement.clientHeight;
			} else if (document.body) {
					// other Explorers
				w = document.body.clientWidth;
				h = document.body.clientHeight;
			}	
			
			return { width: w, height: h };
		},
		
		// contentsSize()とframeSize()の大きいほう
		pageSize: function() {
			var w, h;
			
			var outer = Kanshin.window.contentSize();
			var inner = Kanshin.window.frameSize();
			
			// for small pages with total height less then height of the viewport
			if (outer.height < inner.height) {
				h = inner.height;
			} else { 
				h = outer.height;
			}
		
			// for small pages with total width less then width of the viewport
			if (outer.width < inner.width) {	
				w = inner.width;
			} else {
				w = outer.width;
			}
		
			return { width: w, height: h };
		}
	},
	
	mouse: {
		inside: function(e, elm) {
			var elm = $(elm);
			return elm && Position.within(elm, Event.pointerX(e), Event.pointerY(e));
		},
		pos: function(e) {
			return { x: Event.pointerX(e), y: Event.pointerY(e) };
		},
		distance: function(e, pos) {
			var curPos = this.pos(e);
			var x = pos.x - curPos.x;
			var y = pos.y - curPos.y;
			return Math.sqrt((x * x) + (y - y) ^ 2);
		}
	},
	
	form: {
		enable: function(elm) { $(elm).disabled = ''; }, 
		disable: function(elm) { $(elm).disabled = 'disabled'; },
		setEnable: function(elm, f) {
			if (f) {
				Kanshin.form.enable(elm);
			} else {
				Kanshin.form.disable(elm);
			}
		},
		select: function(elm, f) { Event.observe( $(elm), 'change', f, false); },
		
		checkEmpty: function(msg) {
			for (var i = 1; i < arguments.length; ++i) {
				if (!Field.present(arguments[i])) {
					Kanshin.alert(msg);
					return false;
				}
			}
			return true;
		},
		
		clear: function(form) {
			var tags = $(form).getElementsByTagName('input');
			
			$A(tags).each(function(elm) {
				switch (elm.type) {
					case 'text':
						elm.value = '';
						break;
						
					case 'checkbox':
					case 'radio':
						elm.checked = false;
						break;
						
					case 'submit':
					case 'reset':
					case 'button':
					case 'hidden':
						break;
						
					default:
						alert(elm.type);
						break;
				}
			});
			
			tags = $(form).getElementsByTagName('select');
			$A(tags).each(function(elm) { elm.selectedIndex = 0 });
		},
		
		dummy: ''
	}, 
	
	remote: {
		open: function() {
			this._resetTimer(true, true);
			
			if (!this.opened) {
				Kanshin.set('remote=open');
				Kanshin.show('remoteOpen');
				Kanshin.showHide('remoteCloseBtn', 'remoteOpenBtn');
				
				this.opened = true;
			}
		},
		openAfterDelay: function() {
			this._resetTimer(false, true);
			
			if (!this.opened && !this.opener) {
				this.opener = setTimeout('Kanshin.remote.open()', this.openDelay);
			}
		},
		close: function() {
			this._resetTimer(true, true);
			
			if (!this.dontClose && this.opened) {
				Kanshin.set('remote=close');
				Kanshin.hide('remoteOpen');
				Kanshin.showHide('remoteOpenBtn', 'remoteCloseBtn');
				
				this.ignoreUntilOut = true;
				this.opened = false;
			}
		},
		closeAfterDelay: function() {
			this._resetTimer(true, false);
			
			if (this.opened && !this.closer) {
				this.closer = setTimeout('Kanshin.remote.close()', this.closeDelay);
			}
		},
		switchTab: function(tab) {
			if (!this.opened) this.open();
			
			if (tab == this.selectedTab) return false;
			
			var tabPane = $('remotePane_' + tab);
			if (!tabPane) {
				this.dontClose = true;
				return true;
			}
			
			Kanshin.showHide('remotePane_' + tab, 'remotePane_' + this.selectedTab);
			Kanshin.set('remote=' + tab);
			this.selectedTab = tab;
			
			this.refreshTab();
			return false;
		},
		refreshTab: function() {
			this.tabList.each(function(tab) {
				var img = $('remoteTabImg_' + tab);
				if (img) {
					img.src = '/images/remote/btn_' + tab + 
							(tab == Kanshin.remote.selectedTab ? '_current' : '') + '.png';
				}
			});
		},
		setup: function(opened, tab, openDelay, closeDelay) {
			Event.observe(document, 'mousemove', function(e) {
				var remote = Kanshin.remote;
				
				if (remote.ignoreMove) {
					if (!remote.opened) {
						if (!remote.initialPos) {
							remote.initialPos = Kanshin.mouse.pos(e);
							remote.ignoreUntilOut = Kanshin.mouse.inside(e, 'remote');
						}
						
						var d = Kanshin.mouse.distance(e, remote.initialPos);
						if (d <= remote.ignoreMovePixels) {
							return;
						}
					}
					
					remote.ignoreMove = false;
				}
				
				if (Kanshin.mouse.inside(e, 'remote')) {
					if (!remote.ignoreUntilOut && remote.openDelay > 0) {
						remote.openAfterDelay();
					}
				} else {
					if (remote.closeDelay > 0) {
						remote.closeAfterDelay();
					}
					
					remote.ignoreUntilOut = false;
				}
			});
			
			Event.observe(window, 'unload', 
						function() { Kanshin.remote.dontClose = true; }, 
						false);
			
			if (opened) {
				Kanshin.show('remoteOpen');
				Kanshin.showHide('remoteCloseBtn', 'remoteOpenBtn');
			} else {
				Kanshin.hide('remoteOpen');
				Kanshin.showHide('remoteOpenBtn', 'remoteCloseBtn');
			}
			
			this.opened = opened;
			this.selectedTab = tab;
			this.openDelay = (openDelay ? openDelay : this.defaultOpenDelay);
			this.closeDelay = (closeDelay ? closeDelay : this.defaultCloseDelay);
			
			this.refreshTab();
		},
		_resetTimer: function(resetOpen, resetClose) {
			if (resetOpen && this.opener) {
				clearTimeout(this.opener);
				this.opener = null;
			}
			
			if (resetClose && this.closer) {
				clearTimeout(this.closer);
				this.closer = null;
			}
		},
		defaultOpenDelay: 300, 
		defaultCloseDelay: 300, 
		ignoreMovePixels: 10, 
		
		opened: false,
		dontClose: false,
		openDelay: 300, 
		closeDelay: 1000, 
		ignoreMove: true,
		initialPos: null,
		ignoreUntilOut: false, 
		selectedTab: null,
		tabList: new Array('notification', 'history', 'comment_history', 
											'kw_bookmark', 'user_bookmark'), 
		opener: null,
		closer: null
	},
	
	overlay: {
		show: function() {
			var elm = Kanshin.overlay.cache;
			if (!elm) {
				var body = document.getElementsByTagName("body").item(0);
				
				elm = document.createElement("div");
				elm.setAttribute('id','overlay');
				elm.onclick = function () { Kanshin.overlay.hide(); return false;}
				elm.style.display = 'none';
				elm.style.position = 'absolute';
				elm.style.top = '0';
				elm.style.left = '0';
				elm.style.zIndex = '1000';
				elm.style.width = '100%';
				elm.style.backgroundImage = "url(/images/overlay.png)";
				body.insertBefore(elm, body.firstChild);
				
				Kanshin.overlay.cache = elm;
			}
			
			selects = document.getElementsByTagName("select");
			for (i = 0; i != selects.length; i++) {
				selects[i].style.visibility = "hidden";
			}
			
			Kanshin.overlay.resize();
			elm.style.display = 'block';
			Kanshin.remote.dontClose = true;
		},
		
		resize: function() {
			var elm = Kanshin.overlay.cache;
			elm.style.height = (Kanshin.window.pageSize().height + 'px');
		},
		
		hide: function() {
			var elm = Kanshin.overlay.cache;
			elm.style.display = 'none';
			
			selects = document.getElementsByTagName("select");
			for (i = 0; i != selects.length; i++) {
				selects[i].style.visibility = "visible";
			}
			Kanshin.remote.dontClose = false;
		},
		
		cache: null
	},
	
	cart: {
		add: function(id) {
			/** 未実装 */
			return true;
		}
	}, 
	
	log: function(elm) {
		/** aタグでなければ */
		var url = window.location.href;
		var arg_begin = 0;
		var redirect_url = '';
		
		if (elm.href) {
			redirect_url = elm.href;
			arg_begin += 1;
		}
		
		var action = 'action=log.click';
		for (var i = arg_begin; i < arguments.length; ++i) {
			action += ';' + arguments[i];
		}
		
		if (redirect_url) {
			action += ';' + redirect_url;
		}
		
		url = Kanshin.buildUrl(url, action);
		
		if (elm.target) {
			Kanshin.openTo(elm.target, url);
		} else {
			Kanshin.jump(url);
		}
		
		return false;
	},
	
	debug: {
		log: function(msg) {
			if (!msg instanceof String) {
				msg = Object.inspect(msg);
			}
			
			Element.show('message'); 
			$('message').innerHTML += '<div>' + msg + '</div>';
		},
		clearLog: function() {
			Element.hide('message'); 
			$('message').innerHTML = '';
		}
	},
	
	createObject: function(type, data, width, height) {
		var object = '<object type="' + type +'" data="' + data + '" width="' + width + '" height="' + height + '" />';
		object += '<param name="movie" value="' + data + '" />';
		object += '<param name="wmode" value="transparent" />';
		object += '</object>';
		document.write(object);
	},
	
	onload: function(e) {
		var anchors = document.getElementsByTagName('a');
		for (var i = 0; i < anchors.length; i++) {
			var anchor = anchors[i];
			
			if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "ext")) {
				anchor.setAttribute('target', '_blank');
				Event.observe(anchor, 'click', function(e) {
				}, false);
			}
		}
	},
	
	dummy: ''
}

// Event.observe(window, 'load', Kanshin.onload, false);

// ===========================

/**
 *	これ以下はリニューアル以前のスクリプト
 *	今後基本的に使う事は無い
 */

var is_win = (navigator.appVersion.indexOf("Win") != -1);
var is_msie = (navigator.appName == "Microsoft Internet Explorer");
var nav_version = parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf('.')-1,navigator.appVersion.length));

function kanshin_open_context_viewer(kid) {
	var baseurl = 'http://xml.kanshin.jp:8080/comcv/';
	var stage = kanshin_open_full_window(baseurl + 'index.php?mode=normal&ID=' + kid, 'fabric');
	
	return false;
}

function kanshin_open_full_window(url, name) {
	var win;
	
	if (nav_version >= 4) {
		if (!(is_win && is_msie)) {
			var x = screen.availWidth;
			var y = screen.availHeight;
			
			win = window.open(url, name, 'scrollbars=yes','width='+x+',height='+y+',top=0,left=0');
			
			win.moveTo(0, 0);
			win.resizeTo(x, y);
		}
		else {
			win = window.open(url, name, "fullscreen=yes");
		}
	}
	else {
		win = window.open(url, name, 'scrollbars=yes');
	}
	
	return win;
}

function reload() {
	location.reload(true);
}

/*
	二つのブロックを、表示、非表示で切り替える
*/
function kanshin_showHidePane(paneId, doOpen) {
	var shownPane = document.getElementById(paneId);
	var hiddenPane = document.getElementById(paneId + 'Closed');
	
	if (shownPane) shownPane.style.display = doOpen ? 'block' : 'none';
	if (hiddenPane) hiddenPane.style.display = doOpen ? 'none' : 'block';
	
	return false;
}

/*
	ウィンドウを開く
*/
function kanshin_openSubWindow(url) {
	width = 600;
	height = 500;
	
	if (arguments.length >= 2) {
		width = arguments[1];
		
		if (arguments.length >= 3) {
			height = arguments[2];
		}
	}
	
	window.open(url, 
				'KanshinSub', 
				'toolbar=no,location=no,menubar=no,' + 
				'directories=no,status=no,scrollbars=auto,resizable=auto,' +
				'width=' + width + ',' + 'height=' + height);
	return false;
}

/*
	単純な表示・非表示切り替え Ajaxに移行
*/
function ShowHide(id) {
	var element = document.getElementById(id);
	element.style.display = (element.style.display == 'block') ? 'none' : 'block';
}

/*
 * thanks to: http://slightlyblue.com/blog/2006/08/javascript_1.html
 */
Kanshin.SmartScroll = {
	targetScrollTop : 0,	// we're gonna make the $(parentid).scrollTop -> targetScrollTop
	dist : 0,
	timer : 0,
	count : 0,
	parentid : 0,
	lastDist : 0,
	//speedStore : [],		// for debug
	options : {},
	defaultOptions : {
		time : 1*1000,		// [ms]
		unit : 50			// [ms]
	},
	scrollTo : function( element, parent, options ){
		this.options.time = this.defaultOptions.time;
		this.options.unit = this.defaultOptions.unit;
		if( options ){
			this.options.time = ( options.time ) ? options.time : this.options.time;
			this.options.unit = ( options.unit ) ? options.unit : this.options.unit;
		}
		clearInterval( this.timer );
		this.parentid = parent;

		this.scrollTopMax = this.$(parent).scrollHeight - this.$(parent).offsetHeight + parseInt(this.$(parent).style.borderTopWidth) + parseInt(this.$(parent).style.borderBottomWidth);

		if( navigator.userAgent.match( "MSIE" ) ){
			this.targetScrollTop = ( element ) ? this.$(element).offsetTop : 0;
		}else{
			var targetOffsetTop = ( element ) ? this.$(element).offsetTop : this.$(parent).offsetTop;
			this.targetScrollTop = targetOffsetTop - this.$(parent).offsetTop;
		}
		this.targetScrollTop = ( this.targetScrollTop > this.scrollTopMax ) ? this.scrollTopMax : this.targetScrollTop;

		this.dist = this.targetScrollTop - this.$(parent).scrollTop;
		this.lastDist = 0;
		this.timer = setInterval('Kanshin.SmartScroll.update()', this.options.unit );
		this.count = 0;
		//this.speedStore = [];
		this.update();
	},
	update : function(){
		var dist = this.targetScrollTop - this.$(this.parentid).scrollTop;
		var speed = 2 * dist * this.options.unit / ( this.options.time - this.options.unit * this.count );
		//this.speedStore.push( speed );
		speed = ( speed > 0 ) ? Math.ceil( speed ) : Math.floor( speed );
		if( Math.abs(dist) <= Math.abs(speed) ){
			// got there
			clearInterval( this.timer );
			this.$(this.parentid).scrollTop = this.targetScrollTop;
			return;
		}else if( this.lastDist == dist ){
			// stuck
			clearInterval( this.timer );
			this.$(this.parentid).scrollTop = this.targetScrollTop;
			return;
		}
		var scrollTop = this.$(this.parentid).scrollTop + speed;
		this.$(this.parentid).scrollTop = scrollTop;
		this.lastDist = dist;
		this.count++;
		if( this.count == this.options.time / this.options.unit ){
			// timeout
			clearInterval( this.timer );
			this.$(this.parentid).scrollTop = this.targetScrollTop;
		}
	},
	$ : function(id) {
		return document.getElementById(id);
	}
}



