
(function($){

	/* for ajax. */
	var SITE_PATH = '/';

	/* for search by foods. */
	var _foodSet;	// JSON objects.
	var _$foodItems;	// jQuery objects.

	$(document).ready(function(){

		/* setup recent recipe list. */
		if ($('#aside div.recipe').length) {
			setupRecentRecipe();
		}

		/* setup footer popup images. */
		$('#fnav div.nav ul img')
			.popimage({
				delay: 300,
				set: $('#fnav div.nav ul')
			})
		;

		/* setup search nav. */
		if ($('#aside div.search').length) {
			setupSearchNav();
		}

		/* setup calendar nav. */
		$('#aside div.calendar div.tab')
			/* store images. */
			.find('img')
				.each(function(){
					var img = new Image();
					img.src = this.src.replace(/^(.+)(\.[a-z]+)$/, '$1_on$2');
					$(this).data('images', {
						defaultSrc: this.src,
						activeSrc: img.src
					});
				})
			.end()

			/* setup tabs */
			.idTabs(function(id, list, set){
				/* switch active tab. */
				$('a', set).each(function(){
					var src;
					if (this.hash === id) {
						$(this).addClass('selected');
						src = $('img', this).data('images').activeSrc;
					}
					else {
						$(this).removeClass('selected');
						src = $('img', this).data('images').defaultSrc;
					}
					$('img', this).attr('src', src);
				});

				/* show & hide tab contents. */
				for (var i in list) {
					$(list[i]).hide();
				}
				$(id).show();
			})

			/* set default tab. */
			.find('a.default')
				.click()
			.end()
		;

	});

	function setupRecentRecipe()
	{
		/* get recipe ids. */
		var cookie = getCookie('recentRecipeIds');
		var recipeIds = cookie ? cookie.split('|') : [];

		/* request recipe xml. */
		$.ajax({
			url: SITE_PATH +'recipe/recent_recipe.php',
			type: 'POST',
			data: 'recipeIds='+ recipeIds.join('|'),
			error: function(xhr, status) {
				alert('error: '+ status);
			},
			success: buildRecentRecipe
		});
	}

	function buildRecentRecipe(xml)
	{
		var listMax = 12;

		var $items = $('recipe', xml);
		var list = [];

		/* append recipes. */
		$items
			.slice(0, listMax)
			.each(function(){
				var url = $('url', this).text();
				var image = $('image', this).text();
				var name = $('name', this).text();
				list.push('<li><a href="'+ url +'"><img src="'+ image +'" alt="'+ name +'" /></a></li>');
			})
		;

		/* fill list. */
		for (var i = 0, len = listMax - $items.length; i < len; i++) {
			list.push('<li>&nbsp;</li>');
		}

		/* build dom contents. */
		$('#aside div.recipe ul')
			.empty()
			.append(list.join(''))

			/* setup aside popup images. */
			.find('img')
				.popimage({
					delay: 300,
					set: $('#aside div.recipe ul'),
					vAlign: 'bottom',
					offset: {
						x: 0,
						y: -11
					}
				})
			.end()
		;

	}

	function setupSearchNav()
	{
		var $nav = $('#aside div.search');

		/* setup all search functions. */
		setupDropDownMenus($nav);
		setupFoodSearch($nav);
		setupKeyWordSearch($nav);
	}

	function setupDropDownMenus($nav)
	{
		/* collect parent menus. */
		var target = $('div.product > a', $nav);
		$.merge(target, $('div.menu > ul > li > a', $nav));
		$.merge(target, $('div.food form > a', $nav));
		$.merge(target, $('div.other > ul > li > a', $nav));

		/* setup parent menus. */
		$(target)
			/* store image data. */
			.find('img')
				.each(function(){
					var hoverImage = new Image();
					hoverImage.src = this.src.replace(/^(.+)(\.[a-z]+)$/, '$1_over$2');
					var activeImage = new Image();
					activeImage.src = this.src.replace(/^(.+)(\.[a-z]+)$/, '$1_on$2');

					$(this)
						.data('images', {
							defaultImage: this.src,
							hoverImage: hoverImage.src,
							activeImage: activeImage.src
						})
					;
				})
			.end()

			/* hover handler. */
			.hover(
				function(){
					if (!$(this).hasClass('active')) {
						var $img = $('img', this);
						$img.attr('src', $img.data('images').hoverImage);
					}
				},
				function(){
					if (!$(this).hasClass('active')) {
						var $img = $('img', this);
						$img.attr('src', $img.data('images').defaultImage);
					}
				}
			)

			/* popup handler. */
			.click(function(){
				/* deactivate other popups. */
				var prevMenuCount = hidePopups(this);

				var $popup = $(this).next();

				/* already activated. */
				if ($(this).hasClass('active')) {
					$popup.stop(false, true).hide('fast');
					$(this).trigger('activate.off');
					$(document.body).unbind('click.overlay');
				}
				/* not activated. */
				else {
					$popup
						.stop(false, true)
						.show(
							prevMenuCount > 0 ? 0 : 'fast',	/* switch from other menus or not. */
							function(){
								/* show contents after. */
								$(this).children().show();
							}
						)
					;
					$(this).trigger('activate.on');

					$(document.body).bind('click.overlay', function(){
						$(document.body).unbind('click.overlay');
						hidePopups();
					});
				}

				return false;
			})

			/* menu activate handler. */
			.bind({
				'activate.on': function() {
					var $img = $('img', this);
					$img.attr('src', $img.data('images').activeImage);
					$(this).addClass('active');
				},
				'activate.off': function() {
					var $img = $('img', this);
					$img.attr('src', $img.data('images').defaultImage);
					$(this).removeClass('active');
				}
			})

			/* prevent popup click event bubbling. */
			.next()
				.bind('click.stopBubbling', function(e){
					e.stopPropagation();
				})
				/* tempolary hide contents. */
				.children()
					.hide()
				.end()
			.end()
		;

		function hidePopups(exclude)
		{
			var duration = 'fast';
			var $activeMenus = $(target).filter(function(){
				return $(this).hasClass('active');
			});
			if (exclude) {
				$activeMenus = $activeMenus.filter(function(){
					return this !== exclude;
				});
				duration = '';
			}

			$activeMenus
				.trigger('activate.off')
				.next()
					.children()
						.hide()
					.end()
					.stop(false, true)
					.hide(duration)
				.end()
			;
			
			return $activeMenus.length;
		}
	}

	function setupFoodSearch($nav)
	{
		/* store form objects. */
		var $form = $('div.food form', $nav);
		_$foodItems = $(':checkbox', $form);

		/* request food set data. */
		$.ajax({
			url: SITE_PATH +'recipe/food_set.php',
			type: 'POST',
			error: function(xhr, status) {
				alert('error: '+ status);
			},
			success: function(data) {
				_foodSet = $.parseJSON(data);
				if (_$foodItems !== undefined) {
					setFoodCheckboxStatus();
				}
			}
		});

		/* setup checkbox handler. */
		_$foodItems.click(setFoodCheckboxStatus);

		/* setup reset handler. */
		$('li.reset a', $form).click(function(){
			$(':checkbox', $form).attr('checked', false);
			setFoodCheckboxStatus();
			return false;
		});
	}

	function setFoodCheckboxStatus()
	{
		/* check JSON data exists. */
		if (_foodSet === undefined) {
			return;
		}

		/* get checked items. */
		var $items = _$foodItems.filter(':checked');

		/* enable all checkbox. */
		_$foodItems.attr('disabled', false);

		/*
		 * food set object structure.
		 * {
		 *   ['array', 'of', 'category', 'set'],
		 *   ...
		 * }
		 */
		if ($items.length > 0) {
			/* find possible combinations set. */
			var set = _foodSet;
			$items.each(function(){
				var i = $(this).val() - 0;	/* string to int. */
				set = $.grep(set, function(n){
					return $.inArray(i, n) !== -1;
				});
			});

			/* create union from set. */
			var union = [];
			$.each(set, function(){
				$.each(this, function(){
					var i = this.toString();
					if ($.inArray(i, union) === -1) {
						union.push(i);
					}
				});
			});

			/* find difference form items. */
			var $target = _$foodItems;
			for (var i = 0, len = union.length; i < len; i++) {
				$target = $target.filter(function(){
					return $(this).val() !== union[i];
				});
			}

			/* disable matched items. */
			$target.attr('disabled', true);
		}
	}

	function setupKeyWordSearch($nav)
	{
		var PLACE_HOLDER_TEXT = '\u30AD\u30FC\u30EF\u30FC\u30C9\u3067\u63A2\u3059';

		$('div.form :text', $nav)
			/* set focus & blur handler. */
			.focus(function(){
				if ($(this).val() === PLACE_HOLDER_TEXT) {
					$(this)
						.val('')
						.removeClass('empty')
					;
				}
			})
			.blur(function(){
				if ($(this).val() === '') {
					$(this)
						.val(PLACE_HOLDER_TEXT)
						.addClass('empty')
					;
				}
			})

			/* initialize value. */
			.blur()
		;
	}

})(jQuery);



/*
 * jQuery popup image plugin.
 *
 * @param {Object} Several options.
 * @return {Object} jQuery object.
 */
(function(a){a.fn.popimage=function(f){function g(){var b=a("div.jq_popimage",this);c.set!==undefined&&a("div.jq_popimage",a(c.set)).filter(function(){return this!==b}).hide();if(b.length)if(b.is(":animated"))b.stop(false,true).show();else{var d=a("img",this).offset(),e=d.top+c.offset.y;if(c.vAlign==="bottom")e+=a("img",this).height();else e-=b.height();b.css({top:e,left:d.left+c.offset.x}).stop(false,true).fadeIn("fast")}}function h(){var b=a("div.jq_popimage",this);setTimeout(function(){b.data("isActive")|| b.stop(false,true).fadeOut()},c.delay)}var c=a.extend({delay:300,set:undefined,vAlign:"top",offset:{x:0,y:0}},f);return a(this).filter("img").each(function(){var b=this,d=new Image;d.onload=function(){a('<div class="jq_popimage"><div></div></div>').insertAfter(b).addClass(c.vAlign==="bottom"?"jq_show_bottom":"jq_show_top").hide().find("div").append(this).append("<p>"+a(b).attr("alt")+"</p>").find("p").css("opacity",0.7).end().end().hover(function(){a(this).data("isActive",true)},function(){a(this).data("isActive", false)})};d.src=this.src;a(this).parent().hover(g,h)})}})(jQuery);



