/**
 * Top Image Catalog List Class
 */
var ImgCatalog = Class.create({
	defaultOptions : {
		useWrap:true,
		containerId : 'img-catalog-container',//'topImgCatalog',
		unitId : 'img-catalog-unit',
		noimg : 'common/img/noimage_s.gif',
		descriptionUrls : {
			hotspot: 'hotSpot/hotSpot.php?hotSpotId=',
			event:   'event/event.php?eventId=',
			product: 'product/product.php?productId='
		}
	},
	initialize : function() {
		this.options = Object.extend(this.defaultOptions, {});
		this.container = $(this.options.containerId);
		if(!this.container) {
			return;
		}
		this.unitTpl = Conf.getApplicationParts(this.options.unitId);
		this.units = [];
	},
	createUnit : function(item, searchTarget) {
		// イベント表示の雛形を取得
		var unit = $(this.unitTpl.cloneNode(true));

		// 表示画像を設定
		var imgSrc = item.mainImg.THUMBNAIL02_URL;
		if(!imgSrc) {
//			imgSrc = item.mainImg.LARGE_URL;
		}
		var imgCaption = (item.NOMINAL)?(item.NOMINAL):('');
		unit.select('.catalog-img').each(function(img) {
			img.src   = imgSrc;
			img.alt   = imgCaption;
			img.title = imgCaption;
		});
		// リンクパラメータを設定
		var href = this.options.descriptionUrls[searchTarget] + item.SERIAL;
		unit.select('a').each(function(a) {
			a.href = href;
			a.style.backgroundImage = 'url(' + imgSrc + ')';
			a.title = imgCaption;
			a.name = imgCaption;
			___aTagToolTip___(a);
		});
		return unit;
	},
	reflesh: function(items, searchTarget) {
		if(!this.container) return;

		this.items = items;
		for(var i=0; i<this.units.length; i++) {
			var u = this.units[i];
			u.parentNode.removeChild(u);
		}
		// イベント情報を表示
		this.units = [];

		// タイトル画像を表示
		var titleId = '';
		switch(searchTarget) {
			case 'event': titleId = 'img-catalog-event-title-unit'; break;
			case 'product': titleId = 'img-catalog-product-title-unit'; break;
			case 'hotspot': titleId = 'img-catalog-hotspot-title-unit'; break;
		}
		var titleNode = Conf.getApplicationParts(titleId).cloneNode(true);
		this.container.appendChild($(titleNode));
		this.units.push(titleNode);

		// 各画像を表示
		this.highlighted = null;
		var len = items.length;
		if(len) {
			for(var i = 0; i < len; i++) {
				var item = items[i];
				var unit = this.createUnit(item, searchTarget);
				this.container.appendChild(unit);
				this.units.push(unit);
			}
			$('tbrPhotoNoData').style.display = 'none';
			$('img-catalog-cnt').update(len);
		}
		else {
			$('tbrPhotoNoData').style.display = '';
			titleNode.style.display = 'none';
		}
	},
	showWrap : function(msg) {
		this.container.setOpacity(0.1);

		if(!this.options.useWrap) return;
		if(!this.wrap) {
			this.wrap = new Wrap(this.container.parentNode, {opacity:0.9});
			this.wrap.setImage(Conf._p(Conf.images.loading.url));
		}
		this.wrap.setMessage(msg);
		this.wrap.show();
	},
	hideWrap : function() {
		new Effect.Opacity(this.container, { from: 0.1, to: 1.0, duration: 0.5 });

		if(!this.options.useWrap) return;
		this.wrap.hide();
	}
});

/**
 * Top Image Catalog Class
 */
var TopImgCatalog = Class.create({
	defaultOptions : {
		formId : 'img-catalog-form',
		accordionId : 'fcmPhoto',
		topImgCatalogUri : {
			event  :'EventImgCatalog.php',
			product:'ProductImgCatalog.php',
			hotspot:'HotspotImgCatalog.php'
		}
	},
	initialize : function(options) {
		options = Object.extend(this.defaultOptions, options);
		this.options = options;
		var $this = this;
		var searchTerm = this.getSearchTerms();
		var searchTarget = searchTerm.__searchTarget__;
		//
		// init form
		//
		var form = $(options.formId);
		form.onsubmit = function() {return false};
		$('img-catalog-search-event'  ).observe('click', function() { $this.update(); });
		$('img-catalog-search-product').observe('click', function() { $this.update(); });
		$('img-catalog-search-spot'   ).observe('click', function() { $this.update(); });
		this.recoverForm(searchTerm);
		// 
		// init accordion
		//
		var accordionIndex = 0;
		this.accordion = new Accordion(this.options.accordionId, {
			cookieName : 'TOP_ACCORDION_INDEX',
			listeners : {
				open : function() { $this.update() }
			}
		});
		//
		// init Iikamo Select
		//
		this.iikamoSelect = new IikamoSelect({
			change : function() { $this.update() }
		});
		//
		// show catalog image
		//
		this.imgCatalog = new ImgCatalog();
		this.update();
	},
	update : function() {
		var index = this.accordion.getSelectedIndex();
		switch(index) {
			case 0 : searchTarget='event'; break;
			case 1 : searchTarget='product'; break;
			case 2 : searchTarget='hotspot'; break;
			default: searchTarget='event'; break;
		}

		var params = this.reqParams();
		var uri = this.options.topImgCatalogUri[searchTarget];
		params.__searchTarget__ = searchTarget;

		this.setSearchTerms(params);

		if(!params['tags[]']) {
			// 検索条件にtags[]が無いばあいは
			// 検索結果を0とする
			this.imgCatalog.reflesh([], searchTarget);
			return
		}

		this.imgCatalog.showWrap('読み込み中');

		new Ajax.Request(uri, {
			parameters: params,
			onSuccess: (function(res, itemData) {
				try {
					var items = res.responseJSON;
					if(items) {
						this.imgCatalog.reflesh(items, searchTarget);
					}
					this.imgCatalog.hideWrap();
				}
				catch (e) {
					alert("TopImgCatalog:" + e.message);
				}
			}).bind(this),

			onFailure: function(res)    {
				alert('読み込みに失敗しました');
			},

			onException: function (res) {
				alert('読み込み中にエラーが発生しました');
			}
		});
	},
	activate : function(flg) {
		if(flg) {
			this.iikamoSelect.activate(flg);
			this.accordion.activate(flg);
			this.update();
		}
	},
	reqParams : function() {
		var form = $(this.options.formId);
		var params = {};

		// カテゴリの条件を集める
		var tags = [];
		for(var i=0; i < form.elements.length; i++) {
			var el = form.elements[i];
			if(el.name == 'tags[]' && el.checked) {
				tags.push(el.value);
			}
		}
		if(tags.length > 0) {
			params['tags[]'] = tags;
		}

		// いいかも
		var vote = this.iikamoSelect.getValue();
		if(vote > 0) {
			params.vote = vote;
		}

		return params;
	},
	recoverForm : function(params) {
		var form = $(this.options.formId);
		var tags = params['tags[]'];

		if(tags) {
			tags = tags.join(',');
			for(var i=0; i<form.elements.length; i++) {
				var el = form.elements[i];
				el.checked = ( el.name == 'tags[]' && tags.indexOf(el.value) != -1 );
			}
		}
		else {
			for(var i=0; i<form.elements.length; i++) {
				var el = form.elements[i];
				el.checked = true;
			}
		}
	},
	getSearchTerms : function() {
		var cookie = new CookieManager();
		var jsonStr = cookie.getCookie("TOP_IMG_CATALOG");
		jsonStr = decodeURIComponent(jsonStr);

		var re = (jsonStr)?(jsonStr.evalJSON()):({});
		return (re)?(re):({});
	},
	setSearchTerms : function(searchTerm) {
		var jsonStr = Object.toJSON(searchTerm);
		setCookie("TOP_IMG_CATALOG", jsonStr);
	}
});

/** 装飾のための関数 */
var ___aTagToolTip___ = function(a) {
	jQuery(a).mouseover(function(e) {

		var tooltip = jQuery('#tooltip');
		var tip = jQuery(this).attr('title');

		jQuery(this).attr('title','');
		jQuery('#wrap').append('<div id="tooltip"><div class="tipHeader"></div><div class="tipBody">' + tip + '</div><div class="tipFooter"></div></div>');

		jQuery('#tooltip').fadeIn('500');
		jQuery('#tooltip').fadeTo('10',0.9);
		jQuery('#tooltip').css('top', e.pageY + 10 );
		jQuery('#tooltip').css('left', e.pageX + 20 );


	}).mousemove(function(e) {

		jQuery('#tooltip').css('top', e.pageY + 10 );
		jQuery('#tooltip').css('left', e.pageX + 20 );

	}).mouseout(function() {

		jQuery(this).attr('title',jQuery('.tipBody').html());
		jQuery('#wrap').children('div#tooltip').remove();

	});
}



