/**
 * ERA site - common
 *
 * @author      can i
 * @require     jQuery 1.3.2+
 * @version     1.0.0
 */
jQuery.era = {};

/**
 * IE6撲滅用
 */
jQuery.era.browser = {
	ie6flg: null,
	isIE6: function(){
		if(this.ie6flg!=null){ return this.ie6flg }
		return this.ie6flg = navigator.userAgent.match(/.*MSIE\s*6\.[0-9].*/)? true: false;
	}
}

/**
 * 保存した検索条件で検索
 */
jQuery.era.searchSavedCondition = function(){
	if ($('#sso_parts_searchCondition').val()) {
		window.location.href = $('#sso_parts_searchCondition').val();
		return false;
	} else if (!$('#sso_parts_cookie_searchConditionGet').val()) {
		alert('検索条件が保存されていません。');
		return false;
	}
	this.xhr = $.era.cancelRequest(this.xhr);
	this.xhr = $.ajax({
		type :'GET',
		url :$('#sso_parts_cookie_searchConditionGet').val(),
		success: function(responce){
			if(responce && responce.length > 0){
				window.location.href = responce;
			}else{
				alert('検索条件が保存されていません。');
			}
		},
		error: function(responce, error, con){
			if(responce.status != 0){
				alert('エラーが発生しました。');
			}
		}
	});
	return false;
};

/**
 * フォームをサブミットする
 */
jQuery.era.submitForm = function(formSelector, url, type){
	$(formSelector).attr('method', type || 'post').attr('action', url).submit();
};

/**
 * 物件数カウント処理
 */
jQuery.era.getCount = function(target, param) {
	if(!target || !param){ return; }
	this.xhr = $.era.cancelRequest(this.xhr);
	this.xhr = $.ajax( {
		type :'POST',
		url :$('#sso_parts_searchCount_index').val(),
		data : param,
		success : function(responce) {
			$(target).each(function(){
				$(this).html($(this).find('span.txt')).prepend(responce);
			});
		},
		error : function() {
//			$.era.message.show('confirm', '件数の取得に失敗しました。');
		}
	});
};

/**
 * 物件数カウントクリア（0件にする）
 */
jQuery.era.countClear = function(target){
	$(target).each(function(){
		$(this).html($(this).find('span.txt')).prepend(
			'<input type="hidden" value="false" name="isSearch"/>' + 
			'<span class="num"><img height="26" width="21" alt="0" src="' + $('#sso_era_url').val() + 'images/p2_Panel_number00.gif"/></span>'
		);
	});
};

/**
 * メッセージ出力用
 */
jQuery.era.message = {
	conf : { target :'#p2miniPop', isIE6: null},
	show : function(type, message){
		var pop = $(this.conf.target);
		if (pop.data('visible')){ this.hide(); }
		
		if (type == 'load'){
			pop.find('span.close a, p.btn a').hide().end()
				.find('p.txt').html(message || '<img src="' + $('#sso_era_url').val() + 'images/loading.gif" />検索中');
		}else if (type == 'reading'){
			pop.find('span.close a, p.btn a').hide().end()
			.find('p.txt').html(message || '<img src="' + $('#sso_era_url').val() + 'images/loading.gif" />読み込み中');	
		}else if (type == 'notice'){
			pop.find('span.close a, p.btn a').hide().end()
				.find('p.txt').html(message || '');
		} else if (type == 'confirm'){
			pop.find('span.close a, p.btn a').click(
					$.scope(this, function(){
						this.hide();
						return false;
					})).show().end()
				.find('p.txt').html(message || '');
		}
		if(this.conf.isIE6==null){ this.conf.isIE6 = $.era.browser.isIE6(); }
		if(this.conf.isIE6){ $('select').css('visibility', 'hidden'); }
		pop.setCenterPos().data('visible', true).show();
	},
	hide : function(){
		if(!$.era.overlay.is() && this.conf.isIE6){
			$('select').not('.dummy').css('visibility', 'visible');
		}
		$(this.conf.target).data('visible', false).hide()
			//.find('span.close a, p.btn a').unbind('click');
	},
	write : function(html){
		$(this.conf.target).find('p.txt').html(html);
	},
	is: function(){
		return ($(this.conf.target).data('visible'));
	},
	error: {
		maxnum: function(){
			return arguments[0] +'が'+ arguments[1] +'箇所以上選択されています。';
		},
		required: function(){
			return arguments[0] +'は必須です。';
		},
		noResultList: function(){
			return '申し訳ございません。<br />ご指定の検索条件に該当する物件はありません。';
		}
	}
};

/**
 * オーバーレイ
 */
jQuery.era.overlay = {
	conf: {
		target: '#overlay',
		isIE6: null,
		timer: null
	},
	show: function(){
		var overlay = $(this.conf.target);
		if(this.conf.isIE6==null){ this.conf.isIE6 = $.era.browser.isIE6(); }

		if(!overlay.data('visible')){

			if(this.conf.isIE6){
				// for IE
				var doc = $(document.body);
				$('select').css('visibility', 'hidden');
				overlay
					.css({
						backgroundColor:'#000', position: 'absolute',
						width: doc.width(), height: doc.height(),
						top:'0px', left: '0px',	opacity: '0.5',	filter: 'alpha(opacity=50)'
					})
					.data('visible', true)
					.show();

				this.conf.timer = setInterval(function(){
					overlay.css({width: doc.width(), height: doc.height()});
				}, 100);
			} else {
				// for others
				overlay
					.css({
						backgroundColor:'#000',	position: 'fixed',
						width: '100%', height: '100%',
						top:'0px', left: '0px',	opacity: '0.5',	filter: 'alpha(opacity=50)'
					})
					.data('visible', true)
					.show();
			}
		}
	},
	hide: function(){
		if(this.conf.isIE6){
			$('select').not('.dummy').css('visibility', 'visible');
			if(this.conf.timer){ clearInterval(this.conf.timer); }
		}
		$(this.conf.target)
			.data('visible', false)
			.hide();
	},
	is: function(){
		return ($(this.conf.target).data('visible'));
	}
};

/**
 * 物件画像の遅延ロード
 */
jQuery.era.lazyLoad = {
	load: function(selector, options){
		var conf = {
			noImg: $('#sso_era_url').val() + 'images/p2_no_image01.gif',
			timeout: 30
		};
		$.extend(conf, options);

		conf.images = $(selector);
		conf.loadCnt = 0;

		// 各データを取得・設定
		conf.images.each(function(){
			$.data(this, 'lazyload', {
				top: $.cumulativeOffset(this).top,		// offset値（高さのみ）
				isSet: false							// 設定済みフラグ
			});
		});

		// 初回分を表示
		draw();
		$(window).scroll(draw);

		function draw(){
			var win = $(window);
			var top = win.scrollTop();
			var range = {top: top, bottom: top + win.height()};

			conf.images.each(function(idx, image){
				var pos = null;
				if($(image).data('lazyload')){
					pos = $(image).data('lazyload').top;
				}
				if(range.top < pos && pos <= range.bottom){
					var imgContainer = $(image);
					if(imgContainer.data('lazyload').isSet){ return; }

					var img = new Image();
					var path = (imgContainer.attr('name'))?
							imgContainer.attr('name'): conf.noImg;

					img.onload = $.scope(self, function(){
						imgContainer.attr({'src': path});
						if(imgContainer.data('timer')){
							clearTimeout(imgContainer.data('timer'));
						}
					});
					img.onerror = $.scope(self, function(){
						imgContainer.attr({'src': conf.noImg});
						if(imgContainer.data('timer')){
							clearTimeout(imgContainer.data('timer'));
						}
					});
					img.src = path;

					// タイムアウト
					var timer = setTimeout(function(){
						if(img.src != imgContainer.attr('src')){
							imgContainer.attr({'src': conf.noImg});}
						}, conf.timeout*1000);
					imgContainer.data('timer', timer);

					// ロードイベントを設定した数を保持
					conf.loadCnt ++;
					imgContainer.data('lazyload', {isSet: true});	// 設定済みフラグ
				}
			});
			// 全部ロードしたらイベント削除
			if(conf.loadCnt >= conf.images.length){
				$(window).unbind('scroll');
			}
		};
	},
	destroy: function(){ $(window).unbind('scroll'); }
};

/**
 * cumulativeOffset from prototype.js
 */
jQuery.cumulativeOffset = function(element) {
	var valueT = 0, valueL = 0;
	do {
		valueT += element.offsetTop || 0;
		valueL += element.offsetLeft || 0;
		element = element.offsetParent;
	} while (element);
	return { 'top' :valueT, 'left' :valueL };
};

/**
 * http://16c.jp/2008/0528214632.php
 */
jQuery.scope = function(target, func) {
	return function() {
		return func.apply(target, arguments);
	}
};


/**
 * 共通ヘッダ部分のイベント登録を一括でおこなう
 */
jQuery.era.commmonHeader = function(){
	var conf = { xhr: null };
	// 保存した検索条件を見る
	$('#headerUserBlock')
		.find('#searchBtn').click( function() {
			$.era.searchSavedCondition();
			return false;
		}).end();

};

/**
 * check
 */
jQuery.era.check = {
	/** メールアドレス */
	mailAddress: function(input){
		return (input.match(/^(.+)@(.+)$/));
	},
	/** 電話番号 */
	phoneNum: function(input1, input2, input3){
		return (
			input1.match(/^[0-9]{1,5}$/) &&
			input2.match(/^[0-9]{1,4}$/) &&
			input3.match(/^[0-9]{1,4}$/)
		);
	},
	/** 郵便番号 */
	zipcode: function(input){
		return (input.match(/^[0-9]{3}-[0-9]{4}$/) || input.match(/^[0-9]{7}$/));
	},
	/** 日付 */
	date: {
		/** mmdd */
		mmdd: function(input1, input2){
			return (input1.match(/^[0-9]{1,2}$/) && input2.match(/^[0-9]{1,2}$/));
		}
	}
};

/**
 * リクエストのキャンセル処理
 */
jQuery.era.cancelRequest = function(xhr){
	try{
		if(xhr && xhr.abort){ xhr.abort(); }
	}catch(error){}
	finally{
		return xhr = null;
	}
};

/**
 * checkbox の value を配列でリターン
 */
jQuery.era.checkboxVal = function(selector){
	var elm = $(selector);
	var rtn = [];
	elm.each(function(){
		var val = $(this).val();
		if(val) rtn.push(val);
	});
	return rtn || [];
};

/**
 * era plug-in
 */
jQuery.fn.extend({
	/** ポップアップを画面中央に表示する　*/
	setCenterPos: function(){
		var target = $(this);
		var win = $(window);
		return target.css({
			left :(win.width() - target.width()) / 2 + win.scrollLeft(),
			top :(win.height() - target.height()) / 2 + win.scrollTop()
		})
	}
});
jQuery.era.search = function(formSelector, url, type){
	this.xhr = $.era.cancelRequest(this.xhr);
	this.xhr = $.ajax( {
		type : 'POST',
		url : url,
		data : $(formSelector).serialize(),
		success : function(responce) {
			if(responce && responce.length > 0){
			window.location.href = responce;
			}else{
			$.era.message.show('confirm', '検索に失敗しました。');
			}
		},
		error : function() {
			$.era.message.show('confirm', 'エラーが発生しました。');
		}
	});
};
/* dom ready */
$(function(){
	$.era.commmonHeader();	// 共通ヘッダ
});
