/**
 * @require jQuery 1.4.2+
 * @require constants.js
 * @require util.js
 * @require common.js
 *
 * @version 1.0.0
 */
jQuery.js.header = {};

/**
 * キープ物件数取得
 */
jQuery.js.header.keepCount = function() {
	this.xhr = j$.util.cancelRequest(this.xhr);
	this.xhr = j$.ajax( {
		type: 'POST',
		url: j$.constants.url.keepCount,
		success: function(response) {
			j$.js.common.keep.headerCount(response);
		}
	});
};

/**
 * 物件を探す
 */
jQuery.js.header.searchArticleNavi = function() {
	j$('#headerSearchArticle a').mouseover(function() {
		j$('#headerSearchArticleNavi').show();
		return false;
	}).mouseout(function() {
		j$('#headerSearchArticleNavi').hide();
		return false;
	});
};

/**
 * キーワードイベント
 */
jQuery.js.header.keywordEvent = function() {

	// キーワードテキストボックスにフォーカス
	j$('#headerKeyword').focus(function() {
		init();
		return false;
	});

	// キーワード検索
	j$('#headerKeywordForm').submit(function() {
		init();
		var target = j$('#headerKeyword');
		if (!j$.js.common.str.isBlank(target.val())) {
			if (j$.js.common.detail.check(target.val())) {
				j$.js.common.detail.go(target.val(), '');
			} else if(target.val().length <= 5 && target.val().match(/^[0-9]+$/) ){
				j$.ajax( {
					type: 'POST',
					url: j$.constants.url.keywordApno,
					data: 'keyword=' + target.val(),
					success: function(response) {
						if(response != ''){
							j$.js.common.detail.go(response, '');
						} else {
							j$.js.header.search('#headerKeywordForm');
						}
					}

				});
			} else {
				j$.js.header.search('#headerKeywordForm');
			}
		}
		return false;
	});

	// テキストボックス初期化
	function init() {
		var target = j$('#headerKeyword');
		target.removeClass('initState');
		if(target.val() == j$.constants.str.keywordHeader) {
			target.val('');
		}
	};
};

/**
 * 検索結果画面に遷移
 */
jQuery.js.header.search = function(formSelector) {
	this.xhr = j$.util.cancelRequest(this.xhr);
	this.xhr = j$.ajax( {
		type: 'POST',
		url: j$.constants.url.urlGenerate,
		data: j$(formSelector).serialize(),
		success: function(response) {
			if (response) {
				location.href = response;
			} else {
				j$.js.common.overlay.show();
				j$.js.common.popup.showMessage('検索に失敗しました。');
				j$.js.common.overlay.closeEvent();
			}
		},
		error: function(response) {
			if (response.status != 0) {
				j$.js.common.overlay.show();
				j$.js.common.popup.showMessage('エラーが発生しました。');
				j$.js.common.overlay.closeEvent();
			}
		}
	});
};


/** 初回読み込み処理 */
j$( function() {
	j$.js.header.keepCount();
	j$.js.header.searchArticleNavi();
	j$.js.header.keywordEvent();
});
