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

var Kanshin = {
	uniqueId: function() { return Kanshin._uniqueIdCache++; },
	_uniqueIdCache: 1,
	
	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);
	}, 
	
	addSubPageLoader: function(elm, params) {
		Event.observe(elm, 'click', function(e) {
			Event.stop(e);
			
			var pos = Kanshin.mouse.pos(e);
			params.left = pos.x + (params.offsetX ? params.offsetX : 0) + 'px';
			params.top = pos.y + (params.offsetY ? params.offsetY : 0) + 'px';
			params.mouse = pos;
			
			Kanshin.loadSubPage(params);
		});
	},
	
	loadSubPage: function(userParams) {
		var params = {
			url: '',
			method: 'get', 
			parameters: '', 
			
			id: null,
			left: 0,
			top: 0, 
			width: '',
			height: '',
			offsetX: 0,
			offsetY: 0,
			position: '',
			zindex: 2000,
			contents: ''
		}
		
		if (userParams) Object.extend(params, userParams);
		
		var attribs = {
				id: (params.id || 'subPage' + Kanshin.uniqueId()), 
				className: (params.className || 'subPage'), 
				loaded: false
			};
		var styles = {
				position:'absolute', 
				left: params.left,
				top: params.top, 
				width: params.width,
				zIndex: params.zindex,
				display: 'none'
			};
		
		Kanshin.dom.destroy(attribs.id);
		var p = Kanshin.dom.create('div', attribs, styles);
		Kanshin.dom.body().appendChild(p);
		
		if (params.contents) p.update(params.contents);
		
		if (params.url) {
			new Ajax.Updater(p, params.url, {
					method: params.method,
					parameters: params.parameters,
					onComplete: function() { Kanshin.setupSubPage(p, params) }
				});
		} else {
			p.show();
		}
		
		return p;
	},
	
	setupSubPage: function(elm, params) {
		document.getElementsByClassName('closeBox', elm).each(function(e) {
			Event.observe(e, 'click', function(e) { elm.hide() });
		});
		
		document.getElementsByClassName('draggable', elm).each(function(e) {
			new Draggable(elm, { handle: e });
		});
		
		elm.loaded = true;
		
		if (params.position && params.mouse) {
			var pos = params.position.split(/ +/);
			var size = elm.getDimensions();
			var x = elm.getWidth() * (0 + pos[0]) / 100 + params.mouse.x
			var y = elm.getHeight() * (0 + pos[1]) / 100 + params.mouse.y
			
			console.log(x, y)
		}
		
		if (params.overlay) {
			var ov = new Kanshin.Overlay;
			ov.attach(elm);
			elm.show();
			
			elm = ov;
		}
		
		if (params.effect) {
			var options = {};
			if(params.effectOptions) Object.extend(options, params.effectOptions);
			
			elm.visualEffect(params.effect, options);
		} else {
			elm.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) {
			if (!navigator.userAgent.match(/AppleWebKit\/312/)) {
				// Safari 1.3.2 はこの部分のイベント登録に問題あり。
				// 一時的にオフにしてみる。
			
				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
	},
	
	cart: {
		add: function(id) {
			/** 未実装 */
			return true;
		}
	}, 
	
	log: function(elm) {
		/** aタグでなければ */
		var url = window.location.href.replace(/#.*$/, '');
		
		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 += ';' + encodeURIComponent(redirect_url);
		}
		
		url = Kanshin.buildUrl(url, action);
		
		if (elm.target) {
			Kanshin.openTo(elm.target, url);
		} else {
			Kanshin.jump(url);
		}
		
		return false;
	},
	
	tracker: function(page) {
		Kanshin.dom.accessViaImage('/data/tracker?page=' + encodeURIComponent(page));
		
		if (urchinTracker) urchinTracker(page);
	},
	
	context: function(context) {
		Kanshin.dom.accessViaImage('/data/set_link_context?ctx=' + encodeURIComponent(context));
	},
	
	cookie: {
		get: function(name, default_value) {
			var ck = Kanshin.cookie._parse();
			return (ck[name] != undefined ? ck[name] : default_value);
		},
		
		set: function(name, value) {
			var ck = Kanshin.cookie._parse();
			ck[name] = value;
			document.cookie = name + '=' + encodeURIComponent(value);
			return value;
		},
		
		_parse: function() {
			if (!Kanshin.cookie._cache) {
				Kanshin.cookie._cache = document.cookie.split('; ').inject(
						{}, 
						function(h, s) { var v = s.split('=', 2); h[v[0]] = v[1]; return h }
					)
			}
			
			return Kanshin.cookie._cache
		},
		
		_store: function() {
		},
		
		_cache: null
	},
	
	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: ''
}

Kanshin.dom = {
	head: function() {
		return Kanshin.dom.uniqueTag('head');
	},
	
	body: function() {
		return Kanshin.dom.uniqueTag("body");
	},
	
	uniqueTag: function(tagName) {
		return document.getElementsByTagName(tagName).item(0);
	},
	
	create: function(tagName, attribs, styles) {
		var elm = document.createElement(tagName);
		
		if (attribs) {
			for (var name in attribs) {
				elm[name] = attribs[name];
			}
		}
		
		if (styles) {
			for (var name in styles) {
				if (styles[name] === null) continue;
				
				elm.style[name] = '' + styles[name];
			}
		}
		
		return elm;
	},
	
	destroy: function(elm) {
		if (elm = $(elm)) {
			var p;
			if (p = $(elm.parentNode)) p.removeChild(elm);
		}
	},
	
	accessViaImage: function(url) {
        url += (url.match(/\?/) ? '&' : '?');
		url += 'rnd=' + Math.round(Math.random() * 2147483647);
		
		var i = new Image(1,1);
		i.src = url;
		i.onload = function() { return; }
	},
	
	sibling: function(elm) {
		elm = $(elm);
		while (elm && (elm = elm.nextSibling)) {
			if (elm.nodeType == 1) return elm;
		}
		
		return null;
	},
	
	find: function(userParams) {
		var _params = {
			tagName: '*', 
			parent: null,
			className: null,
			attributes: { },
			checker: null
		}
		
		if (userParams) Object.extend(_params, userParams);
		
		var parent = (_params.parent ? $(_params.parent) : document);
		var elms = parent.getElementsByTagName(_params.tagName ? _params.tagName : '*');
		return $A(elms).findAll(this._finder);
	},
	
	_finder: function(elm) {
		// 変数_paramsは、findの中で定義される_paramsが参照される。
		
		if (_params.className) {
			if (!elm.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) return false;
		}
		
		if (_params.attributes) {
			for (var name in _params.attributes) {
				if (elm[name] != _params.attributes[name]) return false;
			}
		}
		
		if (_params.checker) {
			if (!_params.checker(elm)) return false;
		}
		
		return true;
	}
}

Kanshin.css = {
	load: function(src, media) {
		if (!Kanshin.css.find(src)) {
			var attrs = { href: src, rel: 'stylesheet', type: 'text/css', media: (media ? media : 'all') }
			
			Kanshin.dom.head().appendChild(
				Kanshin.dom.create('link', attrs)
			);
		}
	},
	
	unload: function(src) {
		var link = Kanshin.css.find(src);
		
		if (link) {
			Kanshin.dom.head().removeChild(link);
		}
	},
	
	find: function(src) {
		var re = new RegExp(src);
		
		return $A(document.getElementsByTagName('link')).detect(function(elm) {
							return (elm.rel == 'stylesheet' && elm.href.match(re));
						});
	}
}

Kanshin.js = {
	load: function(src, media) {
		Kanshin.dom.head().appendChild(
			Kanshin.dom.create('script', { src: src, type: 'text/javascript' })
		);
	}
}

Kanshin.Overlay = Class.create();
Kanshin.Overlay.prototype = {
	initialize: function(options) {
		options = options || {}
		
		var attribs = {
			id: options.id || 'overlay' + Kanshin.uniqueId(),
			onclick: function () { this.hide(); return false; }.bind(this)
		}
		
		var styles = {
			display: 'none',
			position: 'absolute',
			top: '0',
			left: '0',
			zIndex: options.zIndex || '1500',
			width: '100%',
			backgroundImage: options.backgroundImage || "url(/images/overlay.png)"
		}
		
		this.elm = new Kanshin.dom.create('div', attribs, styles);
		
		var body = Kanshin.dom.body();
		body.insertBefore(this.elm, body.firstChild);
	},
	
	show: function() {
		if (this.elm.visible()) return;
		
		this._resize();
		this.elm.show();
		
		if (Kanshin.Overlay.openOverlayCount == 0) {
			Kanshin.remote.dontClose = true;
			this._setFormSelectVisibility("hidden");
		}
		
		Kanshin.Overlay.openOverlayCount += 1;
	},
	
	hide: function() {
		if (!this.elm.visible()) return;
		
		this.elm.hide();
	
		Kanshin.Overlay.openOverlayCount -= 1;
		
		if (Kanshin.Overlay.openOverlayCount == 0) {
			Kanshin.remote.dontClose = false;
			this._setFormSelectVisibility("visible");
		}
	},
	
	attach: function(elm) {
		Kanshin.dom.destroy(elm);
		elm.show();
		this.elm.appendChild(elm);
	},
	
	_resize: function() {
		this.elm.style.height = (Kanshin.window.pageSize().height + 'px');
	},
	
	_setFormSelectVisibility: function(visibility) {
		$A(document.getElementsByTagName("select")).each(function(elm) {
			elm.style.visibility = visibility;
		});
	}
}

Object.extend(Kanshin.Overlay, {
	show: function() {
		Kanshin.Overlay.cache = Kanshin.Overlay.cache || new Kanshin.Overlay({id: 'overlay'});
		Kanshin.Overlay.cache.show();
	},
	
	hide: function() {
		if (Kanshin.Overlay.cache) Kanshin.Overlay.cache.hide();
	},
	
	openOverlayCount: 0,
	cache: null
})

// 互換性のために定義
Object.extend(
	Kanshin, 
	{
		sibling: Kanshin.dom.sibling,
		overlay: Kanshin.Overlay
	}
)

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

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

