var grdtItemHash, grdtItemStatusHash;
var myDrags = [];
window.addEvent("domready", function () {
	var oFxSlide = Fx.Slide;
	Fx.Slide = new Class({
		Extends: oFxSlide,
		initialize: function(element, options){
			this.parent(element, options);
			// Fix Margins.
			this.element.setStyle('margin-top', this.wrapper.offsetHeight - this.element.offsetHeight);
			this.element.setStyle('margin-left', this.wrapper.offsetWidth - this.element.offsetWidth);
		}
	});
	grdtItemHash = new Hash(function () {
		var result = {};
		$$('.grdt_item').each(function (item) {
			result[item.id] = item;
		});
		return result;
	}());
	grdtItemStatusHash = new Hash.Cookie('grdt_status', { duration: 91, path: '/', autoSave: false });
	(function () {
		var availableIds = grdtItemHash.getKeys();
		var changed = false;
		grdtItemStatusHash.getKeys().each(function (id) {
			if (!availableIds.contains(id) && id != 'whats-new') {
				changed = true;
				grdtItemStatusHash.erase(id);
			}
		});
		if (changed) grdtItemStatusHash.save();
	})();
	var stateChange = function (item, method) {
		if (item && method) {
			item = $(item);
			var status = grdtItemStatusHash.get(item.id);
			if (!status)	return arguments.callee();
			switch (method) {
				case 'disposed': status[2] = 0; break;
				case 'appeared': status[2] = 1; break;
				case 'closed': status[3] = 0; break;
				case 'open': status[3] = 1; break;
				default: return arguments.callee();
			}
//			if (window.console)	console.log('Item ' + item.id + ' is ' + method + '.');
			item.fireEvent(method);
		} else {
			var obj = {};
			if (item = $(item)) {
				obj[item.id] = item;
			} else {
				obj = grdtItemHash;
			}
			$each(obj, function (item, id) {
				var status = grdtItemStatusHash.get(id);
				if (!status)	status = [ 1, 1, 1, 1];
				status[0] = $$('.grdt_column').indexOf(item.getParent('.grdt_column')) + 1;
				status[1] = item.getAllPrevious('.grdt_item').length + 1;
				status[2] = (item.getStyle('display') == 'none' ? 0 : 1);
				status[3] = (item.getElement('.grdt_item-sliderpane') && item.getElement('.grdt_item-sliderpane').getStyle('height')=='0px' ? 0 : 1);
				grdtItemStatusHash.set(id, status);
			});
		}
		grdtItemStatusHash.save();
	};
	//
	$$('.grdt_item').each(function (item, idx) {
		var placeholder = new Element('div', {
			'id': item.id + '_placeholder',
			'class': 'grdt_item',
			'styles': {
				'position': 'relative',
//				'width': (item.offsetWidth - 4),
//				'height': (item.offsetHeight - 4),
				'background-color': 'transparent',
				'border': '2px dashed #666'
			}
		});
		var myDrag = new Drag.Move(item, {
			'snap': 0,
			'handle': item.getElement('.grdt_item-head'),
//			'container': $('grdt_container'),
			'droppables': $('grdt_container'),
			'onBeforeStart': function (item) {
				placeholder.setStyles({
					'width': (item.offsetWidth - 4),
					'height': (item.offsetHeight - 4)
				}).inject(item.getParent(), 'bottom');
				item.setStyles({
					'position': 'absolute',
					'left': item.offsetLeft,
					'top': item.offsetTop,
					'z-index': 1000,
					opacity: 0.7
				});
				var colid = item.getParent().id;
				this.origin = { colid: colid, tgt: item.getParent(), where: 'bottom' };
				this.tgtid = colid;
				if (item.getNext()) {
					this.origin.tgt = item.getNext();
					this.origin.where = 'before';
					this.tgtid = this.origin.tgt.id;
				}
				var cols = new Hash(function () {
					var result = {};
					$$('.grdt_column').each(function (col) {
						result[col.id] = { x: col.offsetLeft, ys: new Hash({}) };
					});
					return result;
				}());
				grdtItemHash.each(function (otherItem, id) {
					if (otherItem != item && otherItem.getStyle('display') != 'none') {
						cols[otherItem.getParent().id].ys[id] = otherItem.offsetTop;
					}
				});
				cols.each(function (col, id) {
					var y = 0;
					col.ys.each(function (vy, itemid) {	y += $(itemid).offsetHeight + 8;	});
					col.ys[id] = y;
				});
				this.cols = cols;
				placeholder.inject(item, 'before');
			},
			'onCancel': function (item) {
				item.setStyles({
					position: 'relative',
					'left': 0,
					'top': 0,
					'z-index': '',
					opacity: 1
				}).inject(placeholder, 'after');
				placeholder = placeholder.dispose();
//				if (window.console)	console.log(this.tgtid + ': not moved.')
			},
			'onDrag': function (item) {
				var o_tgtid = this.tgtid;
				var cols = this.cols;
				//
				var colid = placeholder.getParent().id;
				var distance = Math.abs(item.offsetLeft - cols[colid].x);
				cols.each(function (col, t_colid) {
					var d = Math.abs(item.offsetLeft - col.x);
					if (d < distance) {
						distance = d;
						colid = t_colid;
					}
				});
				//
				distance = Math.abs(item.offsetTop);
				var pid = o_tgtid;
				var ys = cols[colid].ys;
				ys.each(function (y, id) {
					var d = Math.abs(item.offsetTop - y);
					if (d <= distance) {
						pid = id;
						distance = d;
					}
				});
				if (pid !== o_tgtid) {
					var tgt = grdtItemHash[pid];
					if (tgt) {
						var where = 'before';
						if (item.getParent().hasChild(tgt)) {
							if (ys[pid] > ys[item.id])	where = 'after';
						}
					} else {
						tgt = $(colid);
						var where = 'bottom';
					}
//					if (window.console)	console.log(item.id + ' -> ' + pid + '.' + where);
					placeholder.inject(tgt, where);
					this.tgtid = tgt.id;
				}
			},
			'onDrop': function (item, droppable) {
				item.setStyles({
					position: 'relative',
					'left': 0,
					'top': 0,
					'z-index': '',
					opacity: 1
				}).inject(placeholder, 'after');
				placeholder = placeholder.dispose();
				if (this.tgtid == this.origin.tgt.id) {
//					if (window.console)	console.log(this.tgtid + ': not moved.')
				} else {
//					if (window.console)	console.log(this.origin.tgt.id + ' -> ' + this.tgtid + ': moved.')
				}
				stateChange();
			}
		});
		myDrags.push(myDrag);
		//
		var btnDispose = item.getElement('.grdt_item-head input.fn-dispose');
		var btnClose = item.getElement('.grdt_item-head input.fn-close');
		var btnOpen = item.getElement('.grdt_item-head input.fn-open');
		var btnFn = item.getElement('.grdt_item-head input.fn-fn');
		$$([btnDispose, btnClose, btnOpen, btnFn]).addEvent('mousedown', function (event) {
			new Event(event).stopPropagation();
		});
		if (btnDispose) {
			btnDispose.addEvent('click', function (event) {
				event = new Event(event).stop();
//				alert('[X]');
				item.setStyle('display', 'none');
				stateChange(item, 'disposed');
			});
		}
		if (btnClose && btnOpen) {
			var slideTgt = new Element('div', {
				'class': 'grdt_item-sliderpane-inner',
				'styles': {
					'width': 292,
					'position': 'relative'
				}
			}).inject(item).adopt(item.getElements('.grdt_item-body, .grdt_item-foot'));
			var wrapper = new Element('div', {
				'class': 'grdt_item-sliderpane',
				'styles': {
					'overflow': 'hidden',
					'position': 'relative'
				}
			}).wraps(slideTgt);
			slideTgt.store('wrapper', wrapper);
			//
			btnClose.addEvent('click', function (event) {
				event = new Event(event).stop();
//				alert('[-]');
				slideTgt.get('slide').slideOut().chain(function () {
					btnClose.getParent().setStyle('display', 'none');
					btnOpen.getParent().setStyle('display', 'block');
					if (Browser.Engine.trident) {
						placeholder.setStyles({
							'width': (item.offsetWidth - 4),
							'height': 0
						}).inject(item, 'before');
						item.replaces(placeholder);
					}
					stateChange(item, 'closed');
				});
			});
			btnOpen.addEvent('click', function (event) {
				event = new Event(event).stop();
//				alert('[+]');
				slideTgt.get('slide').slideIn().chain(function () {
					btnOpen.getParent().setStyle('display', 'none');
					btnClose.getParent().setStyle('display', 'block');
					if (Browser.Engine.trident) {
						placeholder.setStyles({
							'width': (item.offsetWidth - 4),
							'height': 0
						}).inject(item, 'before');
						item.replaces(placeholder);
					}
					stateChange(item, 'open');
				});
			});
		}
		if (btnFn) {
			btnFn.getParent('li').setStyle('display', 'block');
			btnFn.addEvent('click', function (event) {
				event = new Event(event).stop();
//				alert('[v]');
				item.fireEvent('function');
			});
			var glassPane = new Element('div', {
				'class': 'grdt_item-glasspane',
				'styles': {
					'right': (item.offsetWidth - btnFn.getCoordinates(item).right),
					'top': (btnFn.getCoordinates(item).top),
//					'z-index': 99,
//					'background-image': 'url(/common/images/blank.gif)',
//					'background-repeat': 'repeat',
					'display': 'none'
				},
				'events': {
					'click': function () {
						glassPane.timer = $clear(glassPane.timer);
						glassPane.setStyle('display', 'none');
						item.setStyle('z-index', '');
					},
					'mouseleave': function () {
						glassPane.timer = (function () {
							glassPane.setStyle('display', 'none');
							item.setStyle('z-index', '');
						}).delay(250);
					},
					'mouseenter': function () {
						glassPane.timer = $clear(glassPane.timer);
					}
				}
			}).inject(item);
		}
	});
	stateChange();

	// === Gadget <-> Switches Combinations ===

	$$('.grdt_chk').each(function (chk) {
		var fnChange = function(flg) {
//			window.console.log(flg + ',' + chk.checked);
			$(chk.value).setStyle('display', !flg ? 'none' : 'block');
			chk.checked = flg;
		};
		chk.addEvent('click', function () {
			fnChange(chk.checked);
			stateChange(chk.value, chk.checked ? 'appeared' : 'disposed');
		});
		var btn = $(chk.value).getElement('input.fn-dispose');
		if (btn) {
			btn.addEvent('click', function () {	fnChange(false); });
		}
	});
});

// === Official Blog Including ===
function getOfficialBlogRSS() {
	var url = encodeURIComponent('http://grampus-eight.blog.so-net.ne.jp/atom.xml');
	$('grdt_item_staffblog-dest').set('text', '取得中...');
	Asset.javascript("http://nagoya-grampus.jp/common/include/rss2json.php?callback=getOfficialBlogRSS_CB&src=" + url);
}
function getOfficialBlogRSS_CB(data) {
	var dest = $('grdt_item_staffblog-dest').setStyles({
		'padding-left': 1,
		'padding-right': 1
	});
	var html = "";
	// Received Error.
	if (data && data.error) {
		if (window.console) {
			console.error("Data Error: \n" + data.error.message + "\n" + data.error.message2);
		}
		html += '<p class="rss-title">Error!</p>';
//		html += '<p>' + data.error.message + '</p>';
//		html += '<p>' + data.error.message2 + '</p>';
		dest.empty().set('html', html);
		return;
	}
	// Received Empty or Invalid Data.
	if (!data || !data.entry || !data.entry.length) {
		if (window.console) {
			if (data && data.entry)	console.warn('Data is Empty.');
			else console.error('Data is Not Valid.');
		}
		new Element('p', {
			'class': 'note',
			'styles': {
				'margin': '0px 0px 0px 0px',
				'padding': '20px 0px 20px 0px',
				'text-align': 'center'
			},
			'html': '\u6700\u65b0\u306e\u60c5\u5831\u306f\u3042\u308a\u307e\u305b\u3093'	// 「最新の情報はありません」
		}).inject(dest.empty());
		return;
	}
	// Received Available Data.
	var entries = data.entry.slice(0, 15);	// limit 15 entries.
	//
	var table = '<table class="information">';
	$each(entries, function (entry, idx) {
		var published = entry.published.substring(0, 10);
		var tr = '<tr class="' + ((idx % 2) ? 'even' : 'odd') + '">';
		tr += '<th class="date">' + published + '</th>';
		tr += '<td><p><a href="' + entry.link + '" title="' + entry.summary + '" target="_blank">' + entry.title + '</a><img src="/common/images/icon-newwin.gif" width="12" height="9" class="post-icon_s" alt="" /></p></td>';
		tr += '</tr>';
		table += tr;
	});
	table += '</table>';
	html = table;
	dest.empty().set('html', html);
}
window.addEvent("domready", function () {
	var item = grdtItemHash.get('grdt_item_staffblog');
	if (!item)	return;
	var status = grdtItemStatusHash.get('grdt_item_staffblog');
	if (status && !status[2]) {
		item.addEvent('appeared', function () {
			item.removeEvent('appeared', arguments.callee);
//			if (window.console)	console.log('Item ' + item.id + ' is initializing contents.');
			getOfficialBlogRSS();
		});
	} else {
		getOfficialBlogRSS();
	}
});

// === PhotoGallery ===
window.addEvent('domready', function () {
	var initializeContent = function () {
		var accordion = new Fx.AccordionG($$('#grdt_item_photogallery ul.recent-photo-list li a'), $$('#grdt_item_photogallery #grdt_photogallery-photo-dest .photo'), {
			duration: 0,
			height: false,
			width: true,
			fixedWidth: 227,
			display: false,
			show: 0,
			opacity: false,
			delay: 250,
			link: 'cancel',
			onActive: function (toggler, element) {
				element.setStyle('display', 'block');
				toggler.addClass('current');
			},
			onBackground: function (toggler, element) {
				element.setStyle('display', 'none');
				toggler.removeClass('current');
			}
		});
	};
	var item = grdtItemHash.get('grdt_item_photogallery');
	if (!item)	return;
	var status = grdtItemStatusHash.get('grdt_item_photogallery');
	if (status && !status[2]) {
		item.addEvent('appeared', function () {
			item.removeEvent('appeared', arguments.callee);
//			if (window.console)	console.log('Item ' + item.id + ' is initializing contents.');
			var request = new Request.HTML({
				'url': '/fan/photogallery/include/top-photogallery-block.php',
				'method': 'get',
				'encoding': 'utf-8',
				'onSuccess': function (responseTree, responseElements, responseHTML, responseJavaScript) {
					$('grdt_photogallery-dest').empty().set('html', responseHTML);
					initializeContent();
				}
			}).send();
		});
	} else {
		// Content is Loaded by PHP-Include.
		initializeContent();
	}
});

// === Schedule ===
window.addEvent('domready', function () {
	var item = grdtItemHash.get('grdt_item_schedule');
	if (!item)	return;
	var status = grdtItemStatusHash.get('grdt_item_schedule');
	if (status && !status[2]) {
		item.addEvent('appeared', function () {
			item.removeEvent('appeared', arguments.callee);
//			if (window.console)	console.log('Item ' + item.id + ' is initializing contents.');
			var request = new Request.HTML({
				'url': '/calendar/include/top-schedule-block.php',
				'method': 'get',
				'encoding': 'utf-8',
				'onRequest': function () {
					if ($defined(this.xhr.overrideMimeType))	this.xhr.overrideMimeType('text/xml;charset=utf8');
				},
				'onSuccess': function (responseTree, responseElements, responseHTML, responseJavaScript) {
					$('grdt_schedule-dest').empty().set('html', responseHTML);
				}
			}).send();
		});
	} else {
		// Content is Loaded by PHP-Include.
	}
});

// === Scoreboard ===
window.addEvent('domready', function () {
	var item = grdtItemHash.get('grdt_item_scoreboard');
	if (!item)	return;
	// vvv- +++ 2009.04.01 +++
	var btnFn = item.getElement('input.fn-fn');
	if (btnFn) {
		var glassPane = item.getElement('div.grdt_item-glasspane');
		var ul = new Element('ul').inject(glassPane);
		var li = new Element('li').inject(ul);
		var loading = new Image();	loading.src = '/images/update.gif';
		var link = new Element('a', {
			'href': 'javascript:void(0)',
			'html': '<img src="/images/icon-innfn-reload.gif" width="11" height="13" alt="" /> \u6700\u65b0\u306e\u60c5\u5831\u306b\u66f4\u65b0',	// 「最新の情報に更新」
			'events': {
				'click': function (evt) {
					// evt = new Event(evt).stop();
					evt = new Event(evt).preventDefault()
					var orgHTML = $('grdt_scoreboard-dest').get('html')
//					$('grdt_scoreboard-dest').empty();
					$('grdt_scoreboard-dest').getChildren().setStyle('visibility', 'hidden');
					$('grdt_scoreboard-dest').grab(new Element('div', {
						'styles': {
							width: $('grdt_scoreboard-dest').getCoordinates().width,
							height: 54,
							position: 'absolute',
							left: 0,
							top: (($('grdt_scoreboard-dest').getCoordinates().height - 54) / 2),
							'text-align': 'center'
						}
					}).grab(new Element('img', {
						'src': loading.src,
						'width': 54,
						'height': 54,
						'alt': ''
					})));
//					(function () {
					var request = new Request.HTML({
						'url': '/game/include/top-scoreboard-block.php',
						'method': 'get',
						'encoding': 'utf-8',
						'onRequest': function () {
							if ($defined(this.xhr.overrideMimeType))	this.xhr.overrideMimeType('text/xml;charset=utf8');
						},
						'onFailure': function () {
							$('grdt_scoreboard-dest').set('html', orgHTML);
						},
						'onSuccess': function (responseTree, responseElements, responseHTML, responseJavaScript) {
							$('grdt_scoreboard-dest').set('html', responseHTML);
						}
					}).send();
//					}).delay(1000);
				}
			}
		}).inject(li);
		item.addEvent('function', function () {
			item.setStyle('z-index', '9');
			glassPane.setStyle('display', 'block');
		});
	}
	// ^^^- +++ 2009.04.01 +++
	var status = grdtItemStatusHash.get('grdt_item_scoreboard');
	if (status && !status[2]) {
		item.addEvent('appeared', function () {
			item.removeEvent('appeared', arguments.callee);
//			if (window.console)	console.log('Item ' + item.id + ' is initializing contents.');
			var request = new Request.HTML({
				'url': '/game/include/top-scoreboard-block.php',
				'method': 'get',
				'encoding': 'utf-8',
				'onRequest': function () {
					if ($defined(this.xhr.overrideMimeType))	this.xhr.overrideMimeType('text/xml;charset=utf8');
				},
				'onSuccess': function (responseTree, responseElements, responseHTML, responseJavaScript) {
					$('grdt_scoreboard-dest').empty().set('html', responseHTML);
				}
			}).send();
		});
	} else {
		// Content is Loaded by PHP-Include.
	}
});

// +++ 2009.03.30 +++
// === What's New ===
window.addEvent('domready', function () {
	var info = $('whats-new');
//	var btnFn = info.getElement('input.fn-fn');
//	if (!btnFn)	return;
	var fnButton = new Element('div', {
		'class': 'fnbutton',
		'html': '<img src="/images/text-fn-config_view.gif" width="54" height="13" alt="\u8868\u793a\u8a2d\u5b9a" />'	// 「表示設定」
	}).inject(info.getElement('.information-header'));
	var btnFn = new Element('input', {
		'type': 'image',
		'src': '/images/button-grdt-fn.gif',
		'class': 'rollover fn-fn',
//		'alt': '[V]',
		'title': '\u30e1\u30cb\u30e5\u30fc',	//「メニュー」
		'alt': '\u30e1\u30cb\u30e5\u30fc',	//「メニュー」
		'events': {
			'mouseenter': function () {
				this.src = '/images/button-grdt-fn-on.gif';
			},
			'mouseleave': function () {
				this.src = '/images/button-grdt-fn.gif';
			}
		}
	}).inject(fnButton);
	//
	grdtItemStatusHash = grdtItemStatusHash || new Hash.Cookie('grdt_status', { duration: 91, path: '/', autoSave: false });
	var options = [ 5, 10, 15, 20 ];
	var currentNum = grdtItemStatusHash.get('whats-new');
	if (!currentNum) {
		currentNum = 15;	// Default.
		grdtItemStatusHash.set('whats-new', [ 99, 99, 99, 99, 15]);
		grdtItemStatusHash.save();
	} else {
		currentNum = currentNum[4] - 0;	// Force to Number.
	}
	//
	var glassPane = new Element('div', {
		'class': 'grdt_item-glasspane',
		'styles': {
			'display': 'none'
		},
		'events': {
			'click': function () {
				glassPane.timer = $clear(glassPane.timer);
				glassPane.setStyle('display', 'none');
			},
			'mouseleave': function () {
				glassPane.timer = (function () {
					glassPane.setStyle('display', 'none');
				}).delay(250);
			},
			'mouseenter': function () {
				glassPane.timer = $clear(glassPane.timer);
			}
		}
	});
	var ul = new Element('ul').inject(glassPane);
	var onclick = function (count) {
		if (count == currentNum)	return;
		currentNum = count;
		GrampusInfoAgent.update(info.getElement('.infobox'), count);
		grdtItemStatusHash.set('whats-new', [ 99, 99, 99, 99, count]);
		grdtItemStatusHash.save();
	};
	options.each(function (count) {
		var li = new Element('li').inject(ul);
		var link = new Element('a', {
			'href': 'javascript:void(0)',
			'html': (count + '\u4ef6\u8868\u793a'),	// XX件表示
			'events': {
				'click': function (evt) {
					// evt = new Event(evt).stop();
					evt = new Event(evt).preventDefault()
					onclick(count);
				}
			}
		}).inject(li);
	});
	glassPane.inject(info);
	btnFn.addEvent('mousedown', function (evt) {
		glassPane.setStyle('display', 'block');
	});
});

// +++ 2009.05.21 +++
// === Ticket Information ===
window.addEvent('domready', function () {
	//Popup Window for TicketGadget
	var win;
	$$('#grdt_item_ticket a.popup').addEvent('click', function (event) {
		event.stop();
		win = window.open(this.href, 'popup', 'width=805,height=640,scrollbars=1,resizable=1'); //横幅805px、縦幅640px、スクロール有、リサイズ有
		win.focus();
	});
});
