/* vim: set tabstop=2 shiftwidth=2 foldmethod=marker: */
/**
 *
 * fanscope 公開サイト用 基本スクリプト
 *
 * @author      Shogo Kawase <shogo@arcstyle.jp>
 * @copyright   Arc Style Inc.
 * @version     CVS: $Id: public.js 10698 2010-01-27 01:20:35Z yuk $
 *
 */
/** コンテナ **/
vw.public = {};

/** 初期化 **/
vw.public.init = function(j)
{
	// jQuery UI
	vw.include(j + '/lib/jquery/ui.min.js', 'body');
	
	// onhover 画像切り換え処理
	$('img,:image').filter('.enable_on_hover').each(function(){
		var normal = this.src;
		var img    = new Image();
		img.src    = normal.replace('normal', 'hover')
		$(this).hover(
			function(){ $(this).attr('src', img.src); },
			function(){ $(this).attr('src', normal); }
		);
	});
	
	// ジャケット画像サイズ調整
	$('img.jacket').each(function(){
		if (this.complete) {
			vw.public.jacket.complete(this);
		} else {
			this.onload = vw.public.jacket.onload;
		}
	});
	
	// 2重ポスト対策
	$('form')
		.submit(function(){ $(this).find(':submit,:image').attr('disabled', true); })
		.find(':submit,:image')
		.dblclick(function(){ return $(this).click() && false; })
	;
	
	// フォームの先頭要素に自動フォーカス
	$('form:not(.nofocus):first :text:first').focus();
};

/** 画像先読み **/
vw.public.imgLoad = function()
{
	var i, j = 0, a = arguments, x = [];
	for (i = a.length - 1; i >= 0; --i) {
		(x[j++] = new Image).src = a[i];
	}
};

/** ジャケット画像処理 **/
vw.public.jacket = {
	onload: function()
	{
		var t = $(this), i = new Image(), x = t.width();
		i.onload = function(){ vw.public.jacket.resize(t, i, x); }
		i.src = this.src;
	},
	complete: function(elem)
	{
		var t = $(elem), i = new Image(), x = t.width();
		i.onload = function(){ vw.public.jacket.resize(t, i, x); }
		i.src    = elem.src;
		this.resize(t, i, x);
	},
	resize: function(t, i, x)
	{
		var x = (i.width > i.height) ? (x / i.width) : (x / i.height);
		var w = Math.floor(x * i.width);
		var h = Math.floor(x * i.height);
		if (w > h) t.css({margin:Math.floor((w - h) / 2) + 'px 0'});
		t.attr({width:w, height:h}).show();
	}
};

/** 郵便番号検索 **/
vw.public.postal = function(key, url)
{
	$('<a href="#">[住所検索]</a>')
		.click(function(e){
			var zip = [
				$(key + '-zip-0').val(),
				$(key + '-zip-1').val()
			];
			if (isNaN(zip[0]) || isNaN(zip[1]) || zip[0].length < 3 || zip[1].length < 4) {
				alert('郵便番号は7桁全て正確に入力してください');
			} else {
				$.getJSON(url + '/postal/zipcode=' + zip.join('-') + '/_=' + (new Date).getTime(), function(json){
					if (!json.count) {
						alert('該当する住所が見つかりませんでした。');
					} else {
						var x = [key + '-pref-container', key + '-city-container', key + '-addr-container'].join(',');
						$(key + '-pref').val(json.pref_code);
						$(key + '-city').val(json.city_name);
						$(key + '-addr').val(json.town_name);
						$(x).effect('highlight', {color:'#FFD'}, 1500);
						vw.form.cursorMoveToEnd($(key + '-addr')[0]);
					}
				});
			}
			return false;
		})
		.appendTo(key + '-zip-container')
	;
};
