/**
 * @require jQuery 1.4.2+
 * @require constants.js
 * @require util.js
 * 
 * @version 1.0.0
 */
jQuery.js = {};

jQuery.js.common = {};

/**
 * 検索結果に遷移
 */
jQuery.js.common.goSearch = function(data) {
	this.xhr = j$.util.cancelRequest(this.xhr);
	this.xhr = j$.ajax( {
		type: 'POST', 
		url: j$.constants.url.urlGenerate, 
		data: data, 
		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();
			}
		}
	});
};

/**
 * 物件詳細遷移
 */
jQuery.js.common.detail = {
	
	check : function(keyword) {
		return keyword && keyword.length > 5 && (keyword.match(/^[0-9]+$/) || keyword.match(/^[0-9]{1,5}\-[0-9]+$/) || keyword.match(/^[0-9]{5}\-[0-9]{1,5}\-[0-9]{3}/));
	},
	go : function(keyword, contract) {
		this.xhr = j$.util.cancelRequest(this.xhr);
		this.xhr = j$.ajax( {
			type: 'POST', 
			url: j$.constants.url.urlDetailGenerate, 
			data: 'keyword=' + keyword + '&contract=' + contract, 
			success: function(response) {
				if (response) {
					parent.location.href = response;
				}
			}
		});
	}
};

/**
 * 画像チェックボックス
 */
jQuery.js.common.checkbox = {
	path : {
		on : j$.constants.img.checkboxOn,
		off : j$.constants.img.checkboxOff
	},
	name : {
		on : j$.constants.img.checkboxOnName,
		off : j$.constants.img.checkboxOffName
	},
	isChecked : function(target) {
		var src = target.attr('src');
		var regex = new RegExp(this.path.on);
		if (src.match(regex)) {
			return true;
		} else {
			return false;
		}
	},
	swap : function(target) {
		if (this.isChecked(target)) {
			target.attr('src', this.path.off).attr('alt', 'off');
			return false;
		} else {
			target.attr('src', this.path.on).attr('alt', 'on');
			return true;
		}
	},
	join : function(target) {
		var checkArray = target.find("img[src*='" + this.name.on + "']");
		var array = new Array(checkArray.length);
		for (i = 0; i < checkArray.length; i++) {
			array[i] = j$(checkArray[i]).attr('name').replace('param_', '');
		}
		return array.join(',');
	},
	isOverLimit : function(target, limit, checkListName) {
		var img = target.find("img[src*='" + jQuery.js.common.checkbox.name.off + "']");
		if (img.length != 0) {
			var checkArray = j$(checkListName).find("img[src*='" + jQuery.js.common.checkbox.name.on + "']");
			return (checkArray.length >= limit) ? true : false;
		} else {
			return false;
		}
	}
};

/**
 * ラジオボタン
 */
jQuery.js.common.radio = {
	path : {
		on : j$.constants.img.radioOn,
		off : j$.constants.img.radioOff
	},
	isChecked : function(target) {
		var src = target.attr('src');
		var regex = new RegExp(this.path.on);
		if (src.match(regex)) {
			return true;
		} else {
			return false;
		}
	},
	check : function(target, array) {
		// onのボタンをoffにする
		for (i = 0; i < array.length; i++) {
			var img = j$(array[i]);
			if (img.hasClass('on')) {
				img.attr('src', this.path.off);
				img.removeClass('on').addClass('off');
				break;
			}
		}
		// offのボタンをonにする
		if (target.hasClass('off')) {
			target.attr('src', this.path.on);
			target.removeClass('off').addClass('on');
		}
	},
	val : function(array) {
		for (i = 0; i < array.length; i++) {
			var img = j$(array[i]);
			if (img.hasClass('on')) {
				return img.attr('name').replace('param_', '');
			}
		}
		return null;
	}
};

/**
 * hidden
 */
jQuery.js.common.hidden = {
	
	join : function(target) {
		var array = new Array(target.length);
		for (i = 0; i < target.length; i++) {
			array[i] = j$(target[i]).val();
		}
		return array.join(',');
	}
};

/**
 * オーバーレイ
 */
jQuery.js.common.overlay = {
	conf: {
		targetIdName : 'TB_overlay'
	},
	show : function() {
		this.hide();
		j$('body').append('<div id="' + this.conf.targetIdName + '"></div>');
		j$.util.overlay.show(j$('#' + this.conf.targetIdName), {color : '#EEE', opacity : '0.75', filter : 'alpha(opacity=75)'});
	},
	hide : function(target) {
		j$.js.common.popup.hide(target);
		j$('#' + this.conf.targetIdName).unbind('click');
		j$.util.overlay.hide(j$('#' + this.conf.targetIdName));
		j$('#' + this.conf.targetIdName).remove();
	},
	is: function() {
		return j$.util.overlay.is(j$('#' + this.conf.targetIdName));
	},
	closeEvent : function(target) {
		j$('#' + this.conf.targetIdName).click(function() {
			j$.js.common.overlay.hide(target);
			return false;
		});
	},
	
	checkError : function(xhr) {
		if (xhr.status != 0) {
			j$.js.common.overlay.show();
			j$.js.common.popup.showMessage('エラーが発生しました。');
			j$.js.common.overlay.closeEvent();
		} else {
			j$.js.common.overlay.hide();
		}
	},
	
	checkException : function(data) {
		if (data == 200) {
			j$.js.common.overlay.show();
			j$.js.common.popup.showMessage('検索に失敗しました。');
			j$.js.common.overlay.closeEvent();
		}
	}
};

/**
 * メッセージポップアップ
 */
jQuery.js.common.popup = {
	conf : {
		targetIdName : 'TB_window'
	},
	show : function(html) {
		this.hide();
		j$('body').append('<div id="' + this.conf.targetIdName + '" style="z-index:1500;"></div>');
		var target = j$('#' + this.conf.targetIdName);
		target.hide().html(html);
		this.popupEvent(target);
		this.closeEvent(target);
	},
	popupEvent : function(target) {
		if (j$.util.browser.isIE6()) {
			j$('select').not('.showSelect').css('visibility', 'hidden');
			target.setCenterPos().show();
			j$.util.popupResize.bind(target);
			j$.util.popupScroll.bind(target);
		} else {
			target.setCenterPosFixed().show();
			j$.util.popupResize.bindFixed(target);
		}
	},
	load : function(url, data, callback) {
		j$('#' + this.conf.targetIdName).load(url, data, callback);
	},
	loading : function() {
		j$.js.common.popup.show('<img src="' + j$.constants.img.loading + '" width="208" height="13" />');
	},
	searchLoading : function() {
		j$.js.common.popup.show('<img src="' + j$.constants.img.searchLoading + '" width="210" height="50" />');
	},
	showMessage : function(message) {
		j$.js.common.popup.show(this.messageHtml(message));
		j$('#' + this.conf.targetIdName).find('img').click(function() {
			j$.js.common.overlay.hide();
			return false;
		});
	},
	showComplexMessage : function(message) {
		j$.js.common.popup.show(this.complexMessageHtml(message));
		j$('#' + this.conf.targetIdName).find('img').click(function() {
			j$.js.common.overlay.hide();
			return false;
		});
	},
	messageHtml : function(message) {
		var html = '<div class="ovlWinara"><div class="ovlWinarabody">' + 
		'<p class="txttop txt">' + message + '</p>' + 
		'<p class="btn"><a href="javascript:void(0);"><img src="' + j$.constants.img.popupClose + 
		'" alt="閉じる" width="50" height="13" class="imgliveover" /></a></p>' + 
		'</div></div>';
		
		return html;
	},
	complexMessageHtml : function(message) {
		var html = '<div class="ovlWinara"><div class="ovlWinarabody">' + 
		message + 
		'<p class="btn"><a href="javascript:void(0);"><img src="' + j$.constants.img.popupClose + 
		'" alt="閉じる" width="50" height="13" class="imgliveover" /></a></p>' + 
		'</div></div>';
		
		return html;
	},
	hide : function(target) {
		j$(window).focus();
		target = target ? target : j$('#' + this.conf.targetIdName);
		j$('#closePopup').unbind('click');
		target.remove();
		if (j$.util.browser.isIE6()) {
			j$('select').not('.showSelect').css('visibility', 'visible');
			j$.util.popupResize.unbind();
			j$.util.popupScroll.unbind();
		} else {
			j$.util.popupResize.unbindFixed();
		}
	},
	closeEvent : function(target) {
		j$('#closePopup').click(function() {
			j$.js.common.overlay.hide(target);
			return false;
		});
	}
};

/**
 * 物件画像の遅延ロード
 */
jQuery.js.common.lazyLoad = {
	scroll : function(selector, namespace, options) {
		namespace = (namespace) ? namespace : 'lazyLoad';
	
		var conf = {
			noImg : j$.constants.img.noImg,
			timeout : 10
		};
		j$.extend(conf, options);

		var images = j$(selector);
		var loadCnt = 0;

		// 各データを取得・設定
		images.each( function() {
			j$.data(this, 'lazyLoad', {
				top : j$.cumulativeOffset(this).top, // offset値（高さのみ）
				isSet : false
			// 設定済みフラグ
			});
		});

		// 初回分を表示
		draw();
		j$(window).bind('scroll.' + namespace, function() {
			draw();
		})

		function draw() {
			var win = j$(window);
			var top = win.scrollTop();
			var range = {
				top : top,
				bottom : top + win.height()
			};

			images.each( function(idx, image) {
				var pos = null;
				if (j$(image).data('lazyLoad')) {
					pos = j$(image).data('lazyLoad').top;
				}

				if (range.top < pos && pos <= range.bottom) {
					var imgContainer = j$(image);
					j$.js.common.lazyLoad.load(imgContainer, conf);

					// ロードイベントを設定した数を保持
					loadCnt++;
					imgContainer.data('lazyLoad', {
						isSet : true
					}); // 設定済みフラグ
				}
			});
			// 全部ロードしたらイベント削除
			if (loadCnt >= images.length) {
				j$(window).unbind('scroll.' + namespace);
			}
		}
	},
	onetime : function(selector, options) {
		var conf = {
			noImg : j$.constants.img.noImg,
			timeout : 10
		};
		j$.extend(conf, options);

		var images = j$(selector);

		// 初回分を表示
		images.each( function(idx, image) {
			var imgContainer = j$(image);
			j$.js.common.lazyLoad.load(imgContainer, conf);
		});
	},
	load : function(imgContainer, conf) {

		var path = (imgContainer.attr('name')) ? imgContainer.attr('name') : conf.noImg;

		var img = new Image();
		img.onload = j$.scope(self, function() {
			j$.js.common.resize.load(img, imgContainer);
			if (imgContainer.data('timer')) {
				clearTimeout(imgContainer.data('timer'));
			}
		});
		img.onerror = j$.scope(self, function() {
			var noImg = new Image();
			noImg.onload = function() {
				j$.js.common.resize.load(noImg, imgContainer);
			};
			noImg.src = conf.noImg;
			if (imgContainer.data('timer')) {
				clearTimeout(imgContainer.data('timer'));
			}
		});

		img.src = path;

		// タイムアウト
		var timer = setTimeout( function() {
			if (img.src != imgContainer.attr('src')) {
				var noImg = new Image();
				noImg.onload = function() {
					j$.js.common.resize.load(noImg, imgContainer);
				};
				noImg.src = conf.noImg;
			}
		}, conf.timeout * 1000);
		imgContainer.data('timer', timer);
	},
	destroy : function(namespace) {
		namespace = (namespace) ? namespace : 'lazyLoad';
		j$(window).unbind('scroll.' + namespace);
	}
};

/**
 * リサイズ
 */
jQuery.js.common.resize = {
	load : function(img, imgContainer) {
		var maxImageSize = Math.max(imgContainer.attr('width'), imgContainer.attr('height'));
	
		// 画像サイズ比率整形
		var imageWidth;
		var imageHeight;
		var imageW = img.width;
		var imageH = img.height;
		var maxSize = Math.max(imageW, imageH);
		if (maxSize) {
			imageWidth = imageW * maxImageSize / maxSize;
			imageHeight = imageH * maxImageSize / maxSize;
		} else {
			imageWidth = maxImageSize;
			imageHeight = maxImageSize;
		}
		var marginTopBottom = (maxImageSize - imageHeight) / 2;
		var marginLeftRight = (maxImageSize - imageWidth) / 2;
		
		imgContainer.attr( {
			'src' : img.src,
			'width' : imageWidth,
			'height' : imageHeight
		}).css( {
			'margin-top' : marginTopBottom, 
			'margin-bottom' : marginTopBottom, 
			'margin-left' : marginLeftRight, 
			'margin-right' : marginLeftRight
		});
	}
};

/**
 * 文字列処理
 */
jQuery.js.common.str = {
	
	trim : function(val) {
		return val ? val.replace(/^\s+|\s+j$/g, '') : null;
	},
	isBlank : function(val) {
		if (val) {
			var value = val.replace(/[\s　]/g, '');
			return value.length > 0 ? false : true;
		} else {
			return true;
		}
	}
		
};

/**
 * 物件のキープ
 */
jQuery.js.common.keep = {
	
	headerCount : function(count) {
		// spanの中の値だけを変えるとIE6でデザインが崩れるためpタグの中身全部を変えてる
		j$('#headerKeep').html('<a href="' + j$.constants.url.compareKeep + '">' + count + '件</a>');
	}
};

/**
 * オススメ物件表示
 */
jQuery.js.common.recommend = function(url, data, callback) {
	this.xhr = j$.ajax( {
		type: 'POST', 
		url: url, 
		data: data, 
		success: function(response) {
			callback(response);
		}
	});
};

/**
 * 閲覧履歴物件表示
 */
jQuery.js.common.history = function(url, data, callback) {
	this.xhr = j$.ajax( {
		type: 'POST', 
		url: url, 
		data: data, 
		success: function(response) {
			callback(response);
		}
	});
};

/**
 * 似たもの物件表示
 */
jQuery.js.common.similar = function(url, data, callback) {
	this.xhr = j$.ajax( {
		type: 'POST', 
		url: url, 
		data: data, 
		success: function(response) {
			callback(response);
		}
	});
};


/**
 * ロードしてポップアップを表示
 */
jQuery.js.common.loadPopup = function() {
	j$('.thickbox').click(function() {
		var url = j$(this).attr('href');
		j$.js.common.overlay.show();
		this.xhr = j$.util.cancelRequest(this.xhr);
		this.xhr = j$.ajax( {
			type : 'GET',
			url : url,
			success : function(response) {
				j$.js.common.popup.show(response);
				j$('#' + j$.js.common.popup.conf.targetIdName).find('img').click(function() {
					j$.js.common.overlay.hide();
					return false;
				});
				j$.js.common.overlay.closeEvent();
			},
			error : function(xhr) {
				if (xhr.status != 0) {
					if (xhr.status == 400) {
						j$.js.common.popup.showMessage(xhr.responseText);
					} else {
						j$.js.common.popup.showMessage('エラーメッセージが発生しました。');
					}
					j$.js.common.overlay.closeEvent();
				}
			}
		});
		return false;
	});
};

/**
 * 親タグだけを取り除く
 */
jQuery.js.common.removeSelf = function(o) {
	return o.each(function(idx) {
		var t = o.eq(idx);
		t.after(t.contents());
		t.remove();
	});
};


/** 初回読み込み処理 */
j$( function() {
	
});
