// photoagent.js
var GrampusPhotoAgent = new Class ({
	initialize: function (dest) {
		this.dest = $(dest);
		if (!this.dest) {
			if (window.console)	console.error('$("' + dest + '") is Not Found.');
			return;
		}
		//
		var base = this.dest;
		base.addClass('photoslide');
		var fullw = base.offsetWidth || base.getParent().getStyle('width').toInt();
		var cellw = 124;
		var dermo = base.getElement('.photoslide-dermo') || new Element('div', {
			'class': 'photoslide-dermo',
			'styles': {
				'width': fullw
			}
		}).inject(base, 'top');
		var core = dermo.getElement('.photoslide-core') || new Element('div', {
			'class': 'photoslide-core',
			'styles': function () {
				var w = Math.floor((fullw - 10) / cellw) * cellw + 10;
				var rm = Math.floor((fullw - w) / 2);
				var lm = fullw - w - rm;
				return {
					'margin': '0 ' + rm + 'px 0 ' + lm + 'px',
					'width': w
				};
			}()
		}).inject(dermo);
		var btnLD = dermo.getElement('.photoslide-leftbutton') || new Element('div', {
			'class': 'photoslide-leftbutton'
		}).inject(dermo);
		var btnL = btnLD.getElement('img') || new Asset.image('/common/images/button-photoslide-left.gif', {
			'alt': '\u2190',	// 「←」
			'styles': {
				'display': 'none'
			},
			'onload': function () {
				btnL.inject(btnLD);
			}
		});
		var btnRD = dermo.getElement('.photoslide-rightbutton') || new Element('div', {
			'class': 'photoslide-rightbutton'
		}).inject(dermo);
		var btnR = btnRD.getElement('img') || new Asset.image('/common/images/button-photoslide-right.gif', {
			'alt': '\u2192',	// 「→」
			'styles': {
				'display': 'none'
			},
			'onload': function () {
				btnR.inject(btnRD);
			}
		});
		var rollover = function (img) {
			img.normal = new Image;
			img.rover  = new Image;
			img.normal.src = img.src;
			img.rover.src  = img.src.replace(
				/^(.+)(?:-on)?(\.(gif|jpg|jpeg|xbm|png)(\?.*)?)$/,
				"$1-on$2");
			img.addEvent('mouseenter', function () {
				img.src = img.rover.src;
			}).addEvent('mouseleave', function () {
				img.src = img.normal.src;
			});
		};
		([btnL, btnR]).each(rollover);
		this.core = core;
		this.btnL = btnL;
		this.btnR = btnR;
		//
		var noteBlock = base.getElement('.photoslide-noteblock') || new Element('div', {
			'class': 'photoslide-noteblock'
		}).inject(base);
		var note = noteBlock.getElement('p.note') || new Element('p', {
			'class': 'note',
			'styles': {
				'visibility': 'hidden'
			},
			'html': '\u753b\u50cf\u3092\u30af\u30ea\u30c3\u30af\u3059\u308b\u3068\u62e1\u5927\u8868\u793a\u3057\u307e\u3059'	// 「画像をクリックすると拡大表示します」
		}).inject(noteBlock);
		var moreLink = base.getElement('p.more');
		if (moreLink) {
			moreLink.inject(noteBlock);
		}
		this.noteBlock = noteBlock;
		this.note = note;
	},
	set: function (data) {
		if (!this.dest) {
			if (window.console)	console.error('Not Initialized.');
			return;
		}
		var core = this.core;
		var btnL = this.btnL.removeEvents('click');
		var btnR = this.btnR.removeEvents('click');
		//
		if (!data || !data.entry) {
			if (window.console)	console.error('Data is Not Valid.');
			new Element('p', {
				'class': 'note',
				'styles': {
					'padding-top': 55,
					'text-align': 'center'
				},
				'html': '\u8868\u793a\u3067\u304d\u308b\u5199\u771f\u304c\u3042\u308a\u307e\u305b\u3093'	// 「表示できる写真がありません」
			}).inject(core.empty());
			btnL.setStyle('display', 'none');
			btnR.setStyle('display', 'none');
			if (this.note)	this.note.setStyle('visibility', 'hidden');
			return;
		}
		//
		var entries = data.entry;
		if (!entries.length) {
			if (window.console)	console.warn('Data is Empty.');
			new Element('p', {
				'class': 'note',
				'styles': {
					'padding-top': 55,
					'text-align': 'center'
				},
				'html': '\u8868\u793a\u3067\u304d\u308b\u5199\u771f\u304c\u3042\u308a\u307e\u305b\u3093'	// 「表示できる写真がありません」
			}).inject(core.empty());
			btnL.setStyle('display', 'none');
			btnR.setStyle('display', 'none');
			if (this.note)	this.note.setStyle('visibility', 'hidden');
			return;
		} else {
			// Limit=30
//			entries = entries.slice(0, 30);
			entries = Array.slice(entries, 0, 30);
		}
		//
		if (this.note)	this.note.setStyle('visibility', 'visible');
		var fullw = this.dest.offsetWidth || this.dest.getParent().getStyle('width').toInt();
		var cellw = 124;
		var listw = cellw * entries.length + 10;
		var dermo = this.dest.getElement('.photoslide-dermo');
		//
		var ul = core.getElement('ul.photoslide-list') || new Element('ul', {
			'class': 'photoslide-list'
		}).inject(core.empty());
		ul.setStyle('width', listw).empty();
		entries.each(function (entry) {
			var html = '<img src="' + entry.summary + '" alt="" />';
			html = '<a href="' + entry.link + '" rel="LightBoxA" title="' + entry.title + '" target="_blank">' + html + '</a>';
			var li = new Element('li', {
				'html': html
			}).inject(ul);
		});
		if (window.Slimbox) {
			ul.getElements('li a').slimbox();
		}
		//
		var numThumbs = entries.length;
		var corew = core.getStyle('width').toInt();
		var numView = Math.floor(corew / cellw);
		if (numView < numThumbs) {
			var tween = ul.get('tween', {duration: 'short', transition: 'expo:out'});
			var currentItem = 0;
			var maxItem = numThumbs - numView;
			var skipItem = Math.min(Math.max(3, Math.floor(numView / 2)), numView);
			var nextItem = 0;
			var btnVChange = function () {
				btnL.setStyle('display', (nextItem == 0) ? 'none' : 'block');
				btnR.setStyle('display', (nextItem == maxItem) ? 'none' : 'block');
			};
			btnVChange();
			btnL.addEvent('click', function () {
				nextItem -= skipItem;
				if (nextItem < 0)	nextItem = 0;
				if (nextItem != currentItem) {
					tween.start('left', -currentItem * cellw, -nextItem * cellw);
					currentItem = nextItem;
					btnVChange();
				}
			});
			btnR.addEvent('click', function () {
				nextItem += skipItem;
				if (nextItem > maxItem)	nextItem = maxItem;
				if (nextItem != currentItem) {
					tween.start('left', -currentItem * cellw, -nextItem * cellw);
					currentItem = nextItem;
					btnVChange();
				}
			})/*.addEvent('mouseup', btnVChange)*/;
		}
	}
});
GrampusPhotoAgent.JSONMAP = new Hash({
	'__all__': '/fan/photogallery/photolist.json'
});
GrampusPhotoAgent.deploy = function (key, target) {
	var fKey = GrampusPhotoAgent._idify(key);
	var url = GrampusPhotoAgent.JSONMAP.get(key);
	var retryCount = 10;
	window.addEvent('domready', function () {
		url = url || GrampusPhotoAgent.JSONMAP.get(key);	// for Webkit
		if (!url) {
			if (retryCount--)	arguments.callee.delay(13);
//			if (window.console)	console.log(10 - retryCount)
			return;
		}
		target = $(target) || $(fKey + '-photoslide') || $('photoslide') || document.getElement('.photoslide');
		if (!target)	return;
		var agent = new GrampusPhotoAgent(target);
		new Request.JSON({
			url: url,
			onSuccess: function (data, text) {
				agent.set(data);
			},
			onFailure: function (xhr) {
				agent.set({ entry: [] });
			}
		}).get();
	});
};
GrampusPhotoAgent.deployHere = function (key) {
	var fKey = GrampusPhotoAgent._idify(key);
	document.write('<div id="' + fKey + '-photoslide-dermo" class="photoslide-dermo"></' + 'div>');
	window.addEvent('domready', function () {
		var target = $(fKey + '-photoslide-dermo');
		var parent = target.getParent();
		if (target.getPrevious('p')) {
			parent = new Element('div').wraps(target);
			if (parent.getNext('p.more'))	parent.getNext('p.more').inject(parent);
		}
		GrampusPhotoAgent.deploy(key, parent);
	});
}
GrampusPhotoAgent._idify = function (src) {
	if (!src)	return '';
	var result = escape(src);
	result = result.replace(/%u/g, 'u').replace(/%/g, 'x').replace(/[!-,.\/:-@~]+/g, '__');
	if (/^[^a-zA-Z]/.test(result))	result = 'e' + result;
	return result;
}

// Asset JS&CSS
if (!window.Slimbox) {
	Asset.css('/common/css/slimbox.css', {'media':'all'});
	Asset.javascript('/common/js/slimbox.js');
}
Asset.css('/common/css/photoagent.css', {'media':'all'});
if (Browser.Engine.trident && !document.documentMode) {	// When IE 6or7 (<8)
	Asset.css('/common/css/photoagent-ie.css', {'media':'all'});
}
// Override JSONMAP
Asset.javascript('/fan/photogallery/js/photojsonlist.js');
