$(function(){

	var flagEndResourceHash = {
		'artist' : false
	,	'true'   : false
	};

	var jqBody           = $('body:first');
	var jqSearchButton   = jqBody.find('header:first>form:first>p:first>button:first');
	var jqSection        = jqBody.children('section:first');
	var jqMoreButtonList = jqSection.find('article>p.more>button');

	var jqTemplateArtistArticle = jqSection.children('article:first').clone();
	var jqTemplateJacketLi      = jqTemplateArtistArticle.find('ul:first>li:first').clone();

	jqTemplateArtistArticle.children('ul:first').empty();
	jqTemplateArtistArticle.find('p.count:first>span:first').replaceHtml(/[0-9]+/, 0);
	jqTemplateArtistArticle.find('p.more:first>button:first').removeAttr('disabled');

	var jqTemplateLoadingImg = $('<img />').attr({
		'src'    : '/*[HTTP_APP_DIR]*/img/loading.gif'
	,	'width'  : 16
	,	'height' : 16
	,	'alt'    : ''
	});

	jqSearchButton.removeAttr('disabled');
	jqMoreButtonList.removeAttr('disabled');

	var query = $('#query').readData('value');

	var searchInf = {
		'requestUrl'         : $.fn.canonical()
	,	'requestPage'        : 1
	,	'flagCommunicatable' : true
	};

	var artistInfHash = {};

	jqSection.children('article').each(function() {
		setArtistInfHash($(this));
	});

	// ----------------

	function setArtistInfHash(jqArticle) {

		var jqA = jqArticle.find('h1:first>a:first');

		artistInfHash[jqA.text()] = {
			'jqArticle'          : jqArticle
		,	'requestUrl'         : jqA.attr('href')
		,	'requestPage'        : 1
		,	'flagCommunicatable' : true
		,	'flagNoSliding'      : true
		};

	}

	function request(jqTriggerElem, inf, quertValueArtist, quertValueTitle) {

		inf['flagCommunicatable'] = false;

		var jqTriggerElemText = jqTriggerElem.text();

		jqTriggerElem.empty().append(
			jqTemplateLoadingImg.clone()
		);

		var param = {
			'page'   : ++inf['requestPage']
		,	'artist' : flagEndResourceHash['artist'] ? 0 : quertValueArtist
		,	'title'  : flagEndResourceHash['title']  ? 0 : quertValueTitle
		};

		if (quertValueArtist == 1 && quertValueTitle == 1 && artistInfHash[query]) {

			if (artistInfHash[query]['requestPage'] < inf['requestPage']) {
				artistInfHash[query]['requestPage'] = inf['requestPage']
			}

		}

		$.fn.ajax('get', inf['requestUrl'], param, function(json) {

			jqTriggerElem.text(jqTriggerElemText);

			var response = $.parseJSON(json);

			var recordMatrix            = response['recordMatrix'];
			var encodeForModRewriteHash = response['encodeForModRewriteHash'];

			if (response['flagEndResourceHash']['artist']) {
				flagEndResourceHash['artist'] = true;
			}

			if (response['flagEndResourceHash']['title']) {
				flagEndResourceHash['title'] = true;
			}

			var lstArtistName = $.fn.lstKey(recordMatrix);

			for (var tmpArtistName in recordMatrix) {

				if (!artistInfHash[tmpArtistName]) {

					var jqArticle = jqTemplateArtistArticle.clone();

					jqArticle.find('h1:first>a:first').attr('href', '/*[HTTP_APP_DIR]*/search/' + encodeForModRewriteHash[tmpArtistName]).text(tmpArtistName);

					setArtistInfHash(jqArticle);

					jqSection.append(
						jqArticle
					);

				}

				if (quertValueArtist == 1 && quertValueTitle == 1 && flagEndResourceHash['artist'] && flagEndResourceHash['title']) {
					var callback = finish;
				} else if (quertValueArtist == 1 && quertValueTitle == 0 && flagEndResourceHash['artist']) {
					var callback = finish;
				} else if (quertValueArtist == 0 && quertValueTitle == 1 && flagEndResourceHash['title']) {
					var callback = finish;
				} else {
					var callback = null;
				}

				display(tmpArtistName, artistInfHash[tmpArtistName]['jqArticle'].children('ul:first'), recordMatrix[tmpArtistName], tmpArtistName === lstArtistName, callback);

			}

		}, function(response) {

			if (response.status == 404) {
				finish();
			} else {

				$.fn.disabledUserInterface();

				jqTriggerElem.text('エラー！');

				jqBody.append(
					$('<article />').append(
						$('<h1 />').text(response.responseText)
					).append(
						$('<p />').text('問題が発生したため、トップページに戻ります。')
					).append(
						$('<p />').append(
							$('<button />').text('OK').click(function() {
								location.href = '/*[HTTP_APP_DIR]*/';
							})
						)
					).hide().fadeIn()
				);

			}

		});

		function finish() {

			jqTriggerElem.attr('disabled', 'disabled').text('/*[Conf::BUTTON_LABEL_EMPTY]*/');

			jqTriggerElem.parent('p.more:first').parent('article:first').addClass('finish');

			if (quertValueArtist == 1 && quertValueTitle == 1 && artistInfHash[query]) {

				artistInfHash[query]['jqArticle'].find('p.more:first>button').attr('disabled', 'disabled').text('/*[Conf::BUTTON_LABEL_EMPTY]*/');
				artistInfHash[query]['jqArticle'].addClass('finish');

			}

			searchInf['flagCommunicatable'] = inf['flagCommunicatable'] = true;

		}

	}

	function display(artistName, jqArtistUl, recordList, flagLst, callback) {

		var flagOpened = (jqArtistUl.siblings('p.close:first').children('button:first').text() === '/*[Conf::BUTTON_LABEL_CLOSE]*/');

		if (flagOpened) {
			jqArtistUl.height(jqArtistUl.height());
		}

		for (var tmpRecordListIndex in recordList) {

			var tmpRecord = recordList[tmpRecordListIndex];

			if (!jqArtistUl.find('li>ul>li>a[href="' + $.fn.escapeHtml(tmpRecord['affiliateUrl']) + '"]').exists()) {

				var jqJacketLi     = jqTemplateJacketLi.clone();
				var jqDetailLiList = jqJacketLi.find('ul:first>li');

				jqDetailLiList.eq(0).children('a:first').attr('href', $.fn.escapeHtml(tmpRecord['affiliateUrl'])).children('img:first').attr('src', $.fn.escapeHtml(tmpRecord['imageUrl'])).attr('alt', $.fn.escapeHtml(tmpRecord['title']));
				jqDetailLiList.eq(1).text(tmpRecord['title']);
				jqDetailLiList.eq(2).text(tmpRecord['size']);
				jqDetailLiList.eq(3).text(tmpRecord['salesDate']);

				jqArtistUl.append(
					jqJacketLi.writeData('sales-timestamp', tmpRecord['salesTimestamp'])
				);

				if (flagOpened) {

					jqJacketLi.hide().fadeIn(/*[Conf::MORE_FADEIN_COMPLETE_TIME]*/, function() {
						$(this).removeAttr('style');
					});

				}

			}

		}

		jqArtistUl.sortDom(function(jqJacketLi) {
			return jqJacketLi.readIntData('sales-timestamp');
		}, true);

		jqArtistUl.siblings('p.count:first').children('span:first').replaceHtml(/[0-9]+/, jqArtistUl.children('li').size());

		if (flagOpened) {

			jqArtistUl.animate({
				'height' : jqArtistUl.children('li:last').offsetValue('bottom', true) - jqArtistUl.offsetValue('top') + 1
			}, /*[Conf::MORE_SLIDE_COMPLETE_TIME]*/, '/*[Conf::MORE_SLIDE_EASING]*/', function() {

				$(this).removeAttr('style');

				displayBackOrder();

			});

		} else {
			displayBackOrder();
		}

		function displayBackOrder() {

			if (typeof callback === 'function') {
				callback();
			}

			artistInfHash[artistName]['flagCommunicatable'] = true;

			if (flagLst) {
				searchInf['flagCommunicatable'] = true;
			}

		}

	}

	// ----------------

	jqSearchButton.click(function() {

		if (searchInf['flagCommunicatable']) {

			for (var tmpArtistName in artistInfHash) {

				if (!artistInfHash[tmpArtistName]['flagCommunicatable']) {
					return false;
				}

			}

			request($(this), searchInf, 1, 1);

		}

		return false;

	});

	$('body:first>section:first>article>p.more>button').live('click', function() {

		if (searchInf['flagCommunicatable']) {

			var artistInf = artistInfHash[$(this).parent().siblings('h1:first').children('a:first').text()];

			if (artistInf['flagCommunicatable']) {
				request($(this), artistInf, 1, 0);
			}

		}

	});

	$('body:first>section:first>article>p.close>button').live('click', function() {

		var jqCloseButton = $(this);
		var jqCloseP      = jqCloseButton.parent();

		var artistName = jqCloseP.siblings('h1:first').children('a:first').text();

		if (artistInfHash[artistName]['flagNoSliding']) {

			artistInfHash[artistName]['flagNoSliding'] = false;

			if (jqCloseButton.text() === '/*[Conf::BUTTON_LABEL_CLOSE]*/') {

				jqCloseP.siblings('ul:first').slideUp(/*[Conf::VISIBIRITY_SLIDE_COMPLETE_TIME]*/, function() {

					jqCloseButton.text('/*[Conf::BUTTON_LABEL_OPEN]*/');

					artistInfHash[artistName]['flagNoSliding'] = true;

				});

			} else {

				jqCloseP.siblings('ul:first').slideDown(/*[Conf::VISIBIRITY_SLIDE_COMPLETE_TIME]*/, function() {

					jqCloseButton.text('/*[Conf::BUTTON_LABEL_CLOSE]*/');

					artistInfHash[artistName]['flagNoSliding'] = true;

				});

			}

		}

	});

});
