/**
 * @requires jquery.js
 * @requires util.js
 */

lazyScript = (function() {
	var write = document.write;
	return function(src, override) {
		try {
			document.write = override || write;
			$.getScript(src);
		}
		catch(e) {}
	};
})();


Apricot = {};
Apricot.run = function() {
	Apricot.menu();
	Apricot.yunogenerator();

	Apricot.icon();

	$("input.placehold").each(function () {
		var $this = $(this);
		var holder = $this.val();

		$this.attr("style", "color: #666");

		$this.focus(function () {
			if ($this.val() == holder) {
				$this.val("");
				$this.attr("style", "");
			}
		});
		$this.blur(function () {
			if ($this.val() == "") {
				$this.val(holder);
				$this.attr("style", "color: #666");
			}
		});
	});

	if ($('#alert').length) setTimeout(function() {
		$('#alert').slideUp();
	}, 1000 * 5);

	// // ad
	// // since 08/05/21
	// google_ad_client = 'pub-5256446794843681';
	// google_ad_slot   = 7742320582;
	// google_ad_width  = 728;
	// google_ad_height = 90;
	// lazyScript('http://pagead2.googlesyndication.com/pagead/show_ads.js', function(s) {
	// 	$('.ad:eq(0)').append(s);
	// });
	// 
	// // since 09/03/17
	// google_ad_client = 'pub-5256446794843681';
	// google_ad_slot   = 3936706379;
	// google_ad_width  = 728;
	// google_ad_height = 15;
	// lazyScript('http://pagead2.googlesyndication.com/pagead/show_ads.js', function(s) {
	// 	$('.ad:eq(1)').append(s);
	// });
};


Apricot.test = function() {
	var $submit = $('input[type="submit"]');

	$('#test')
		.attr('disabled', 'disabled')
		.after('<img src="/images/loading.gif" id="loading" width="16" height="16" alt="" style="margin-left:3px;"/>');

	$('#result').slideUp('fast', function() {
		$.getJSON(
			'/api/graph/test',
			{
				url  : $('#url').val(),
				xpath: $('#xpath').val()
			},
			function(json) {
				$('#test').attr('disabled', '');
				$('#loading').remove();

				if (json.result) {
					$('#result')
						.removeClass('error').text(json.result)
						.slideDown('fast');

					$submit.removeClass('disable').attr('disabled', '');
				}
				else {
					$('#result')
						.addClass('error').text(json.error || '値が取得できませんでした')
						.slideDown('fast');

					$submit.addClass('disable').attr('disabled', 'disabled');
				}
			}
		);
	});
};


Apricot.icon = function() {
	$('body.domain #body h1').css('background-image', 'url(http://' + $('#domain').text() + '/favicon.ico)');
	$('body.user #body h1')  .css('background-image', 'url(' + $('#icon img').attr('src') + ')');
	$('body.dead #body h1')  .css('background-image', 'url(/images/icon_error.png)');

	if ($('body.graph #domain').length) {
		var icon = 'http://' + $('#domain').text() + '/favicon.ico';

		$('<img/>').attr('src', icon)
			.load(function() {
				$('#domain a').css({
					paddingLeft    : parseInt($('#domain a').css('padding-left')) + 20,
					backgroundImage: 'url(' + icon + ')'
				});
			});
	}
};


Apricot.menu = function() {
	$('#header h1 img').hover(
		function() { this.src = '/images/logo_hover.png'; },
		function() { this.src = '/images/logo.png'; }
	);

	// preload
	var preload_images = [
		'logo_hover.png',
		'bg_menu_hover.png',
		'bg_menu_create_hover.png'
	];
	$.each(preload_images, function() {
		$('<img/>').attr('src', '/images/' + this);
	});
};


Apricot.yunogenerator = function() {
	if ($.browser.msie) return;

	$('<p class="yunogenerator"><span>このページのXPathを探す（おまけ）</span></p>')
		.find('span')
			.one('click', function() {
				$.getScript('http://svn.coderepos.org/share/lang/javascript/bookmarklets/yunogenerator.bookmarklet.js');
			})
			.end()
		.insertBefore('#footer .kayac');
};


Apricot.suggest = function() {
	var f = arguments.callee;
	if (f.run) return;

	f.run = true;

	var link  = $('#url').val();
	var color = {
		odd : 'ffffff',
		even: 'f1f5fa'
	};

	var $graphlist = $([
		'<h2><a href="' + link + '">' + link + '</a>のもしかして</h2>',
		'<p>作成しようとしているグラフは既に存在する可能性があります</p>',
		'<table class="graph-list">',
		'<thead>',
		'<tr>',
		'<th></th>',
		'<th>タイトル</th>',
		'<th>説明</th>',
		'</tr>',
		'</thead>',
		'<tbody><!-- graph --></tbody>',
		'</tbody>',
		'</table>'
	].join(''));

	var $graph = $([
		'<tr><!-- .stripe -->',
		'<td class="graph"><!-- graph --></td>',
		'<th class="title"><!-- title --></th>',
		'<td class="description"><!-- description --></td>',
		'</tr>'
	].join(''));

	$('#graph-suggest').empty();

	$.getJSON('/api/graph/search', { url: link },
		function(json) {
			f.run = false;
			if (json.error || !json.graphs.length) return;

			$.each(json.graphs, function(i) {
				var stripe = i % 2 ? 'even' : 'odd';
				var graph  = this.gchart
					.replace(/(chs=)180x120/, '$1120x50').replace(/f{6}/, color[stripe])
					+ '&chxt=&chg=25,50,1,5';

				$graphlist.find('tbody').append(
					$graph.clone()
						.addClass(stripe)
						.find('td.graph').html('<a href="' + this.link + '"><img src="' + graph + '" width="120" height="50" alt=""/></a>').end()
						.find('th.title').html('<a href="' + this.link + '">' + this.title.truncate(30) + '</a>').end()
						.find('td.description').html(this.description.truncate(35)).end()
				);
			});
			$('#graph-suggest').append($graphlist);
		}
	);
};


Apricot.tool = function() {
	if ($.browser.msie) return; // ＼(^o^)／

	var tools = {
		bookmarklet: $("<li><a href=\"javascript:(function(){var%20x=document.createElement('script');x.src='http://svn.coderepos.org/share/lang/javascript/bookmarklets/yunogenerator.bookmarklet.js';x.type='text/javascript';x.charset='utf-8';document.body.appendChild(x)})();\">Find XPath</a>（ブックマークレット）</li>")
	};

	$.each(tools, function() {
		$('ul.tool').append(this);
	});
};


$(Apricot.run);
