
//TODO テスト用の記述
if(!console){
	var console = {
		debug : function(str){	
			$("#footerBox").after("<b>" + str + "</b>");
		}
	}
}

/*
 * http://d.hatena.ne.jp/amachang/20061019/1161201903
 */
var clone = function(p) {
	p = (function(){return this}).apply(p); // objectify if atomic
	switch (typeof p) {
	case 'function':  return function() { return p.apply(this, arguments) };
	case 'undefined': return p;
	case 'object':
		if (p == null) return p;
		else {
			var f = function() {};
			f.prototype = p;
			var o = new f;
			switch (p.constructor) {
			case String: case Number: case Boolean:
				if (o.toSource) o.toSource = function() { return "clone(" + p.toSource.apply(p, arguments) + ")/*require clone function*/" };
				o.toString = function() { return p.toString.apply(p, arguments) };
				o.valueOf = function() { return p.valueOf.apply(p, arguments) };
			}
			return o;
		}
	}
}

Array.prototype.index = function(value, compare){;
	for(var i=0; i<this.length; i++){
		if(this[i] === value || (compare && compare(this[i], value))){
			return i;
		}
	}
	return -1;
};

Array.prototype.remove = function(index) {
	if(i>this.length){
		return ;
	}
	for(var i = 0, j = 0; i < this.length; i++) {
		if( i != index ) {
			this[j++] = this[i];
		}
	}
	this.length -= 1;
};

Array.prototype.removeItem = function(item) {
	for ( var i = 0 ; i < this.length ; i++ ) {
		if ( this[i] == item ) {
			this.remove(i);
		}
	}
};

/**
 * チェックされているオブジェクトのすべてのvalue要素を取得します。
 */
jQuery.fn.getAllCheckedValue = function() {
	var values = new Array();
	$(this).each(function(){
		if( this.checked ){
			values.push($(this).val());
		}
	});
	return values;
}

var Century21 = {
	//TODO versionとか入れる？
};

/** 
 * モダンブラウザかどうかを判定します
 * モダンブラウザの場合はtrue / モダンブラウザではない場合はfalse
 */
 Century21.isModernBrowser = function() {
 	return typeof document.documentElement.style.maxHeight != "undefined";
 }

/**
 * パラメータークラス
 */
Century21.Parameter = function(f, v) {
	this.field = f;
	this.value = v;
}

/**
 * 検索条件クラス
 * 
 */
Century21.Condition = function() {
	this.conds = new Array();
}

Century21.Condition.prototype = {

	//検索条件を設定します。
	put : function(key, value){
		if(this.containsKey(key)){
			var index = this.index(key);
			this.conds[index] = new Century21.Parameter(key, value);
		}else{
			this.conds.push(new Century21.Parameter(key, value));	
		}
	},
	//指定したフィールド名の検索条件が設定されているかどうかを取得します。
	containsKey : function(key){
		return this.index(key) >= 0;
	},
	//指定したフィールド名の検索条件の設定されているindexを取得します。
	index : function(key){
		return this.conds.index(key, function(a, b){return a.field === b});
	},
	//指定したフィールド名の検索条件を取得します。
	getByKey : function(key){
		var idx = this.index(key);
		return (idx >= 0) ? this.conds[this.index(key)] : undefined;
	},
	//指定したフィールド名の検索条件の値を取得します。
	getValueByKey : function(key){
		var obj = this.getByKey(key);
		return obj? obj.value : "";
	},
	//指定したフィールド名の検索条件を反転します。
	reverse : function(key){
		key = key.replace(/^disp_/, "");
		this.put(key, (this.getValueByKey(key) == "1") ? "0" : "1");
	},
	//URLに含まれるパラメーター部分を検索条件に追加します。
	setFromUrlParameter : function(u){
		var params = new Century21.UrlTokenizer(u).params();
		for(var i=0; i<params.length; i++){
			this.put(params[i].field, params[i].value);
		}
	},
	//URLパラメーターに変換するときの順序を設定します。
	setUrlOrder : function(order){
		this.order = order;
	},
	//検索条件のソートをおこないます。
	sort : function(){
		if(this.order != undefined) {
			var order = this.order;
			this.conds.sort(function(a, b) {
				return order.index(a.field) > order.index(b.field) ? 1 : -1;
			});
		} else {
			this.conds.sort();
		}
		return this.conds;
	}
};

/* 
 * 基本条件クラス
 */
Century21.BasicCondition = function(){
	Century21.Condition.apply(this, arguments);
}

Century21.BasicCondition.prototype = new Century21.Condition();

//検索条件をすべて初期化します。空文字をセットする
Century21.BasicCondition.prototype.clear = function(){
	var condition = this;
	jQuery.each(this.conds, function(){
	//kindは消す
		if (this.field == 'kind') {
			this.field = "";
			this.value = "";
		} else {
			this.value = "";
		}
	});
}

/* 
 * こだわり条件クラス
 */
Century21.ParticularCondition = function(){
	this.contradicts = [
		{floorNum1:"floorNum2"},
		{floorNum1:"floorNum5"},
		{floorNum1:"floorNum10"},
		{floorNum1:"floorNum20"},
		{floorNum2:"floorNum5"},
		{floorNum2:"floorNum10"},
		{floorNum2:"floorNum20"},
		{floorNum5:"floorNum10"},
		{floorNum5:"floorNum20"},
		{floorNum10:"floorNum20"},
		{pjMvCnd1:"pjUd2"},
		{pjMvCnd2:"pjUd3"},
		{pjMvCnd3:"pjUd4"}
	];
	Century21.Condition.apply(this, arguments);
}

Century21.ParticularCondition.prototype = new Century21.Condition();

//検索条件をすべて初期化します。空にする
Century21.ParticularCondition.prototype.clear = function(){
		this.conds = new Array();
}

Century21.ParticularCondition.prototype.pop = function(){
		this.conds.pop();
}

//相反する項目の名称を取得します。
Century21.ParticularCondition.prototype.getContradict = function(key){
	var rets = new Array();
	for (var i=0; i<this.contradicts.length; i++) {
		var obj = this.contradicts[i];
		for(var c in obj){
			if(key == c) {
				rets.push(obj[c]);
			}
			if(key == obj[c]) {
				rets.push(c);
			}
		}
	}
	return rets;
}

//指定したフィールド名の検索条件を反転します。
//相反する項目がセットされている場合は、その項目を検索条件から除外します。
Century21.ParticularCondition.prototype.reverse = function(key){
	
	Century21.Condition.prototype.reverse.call(this, key);
	
	if(this.getValueByKey(key) == 1){
		var contradicts = this.getContradict(key);
		for (var i=0; i < contradicts.length; i++) {
			var con = contradicts[i];
			if(this.getValueByKey(con) == 1){
				Century21.Condition.prototype.reverse.call(this, con);
			}
		}
	}
}

/**
 * 検索クラス
 */
Century21.SearchManager = function() {
	this.initialize.apply(this, arguments);
}

Century21.SearchManager.prototype = {
	
	//コンストラクタ
	initialize: function(url) {
		this.url = url;
		this.condRoute = new Century21.ParticularCondition();
		this.condMain = new Century21.ParticularCondition();
		this.condWord = new Century21.ParticularCondition();
		this.condBasic = new Century21.BasicCondition();
		this.condPart = new Century21.ParticularCondition();
		this.condDisp = new Century21.Condition();
		
		var load = function(className, cond){
			$("input[type='hidden'][class='" + className + "']").each(function(){
				if($(this).val()){
					cond.put(this.id, $(this).val());
				}
			});
		};
		
		//hidden項目の値を読み込む
		load("condRoute", this.condRoute);
		load("condMain", this.condMain);
		load("condWord", this.condWord);
		load("condBasic", this.condBasic);
		load("condPart", this.condPart);
		load("condDisp", this.condDisp);
	},
	
	//メイン検索条件以外の条件をクリアします。
	clear2ndConditions: function(){
		this.condBasic.clear();
		this.condPart.clear();
		//kindは個別に消去する
		if(this.condBasic.index("kind") >= 0){
			this.condBasic.conds.remove(this.condBasic.index("kind"));		
		}
	
	},
	
	//URLパラメーター用のmapを取得します。
	map4url: function(){
		var ret = {};
		jQuery.each([this.condRoute], function(){
			this.sort();
			for(var i=0; i<this.conds.length; i++) {
				var p = this.conds[i];
				if(p.field != '' && (p.value != '' && p.value != 0)){
					ret[p.field] = p.value;
				}
				
			}	
		});
		jQuery.each([this.condMain, this.condWord, this.condBasic, this.condPart, this.condDisp], function(){
			this.sort();
			for(var i=0; i<this.conds.length; i++) {
				var p = this.conds[i];
				if(p.field != '' && (p.value != '' && p.value != 0)){
					ret["p."+p.field] = p.value;
				}
				
			}	
		});
		
		return ret;
	},

	//条件画像の切り替え
	switchLeftConditions: function(){
	
		//基本条件を画像を切り替える
		jQuery.each(this.condBasic.conds, function(){
			var cond = this;
			$("#disp_" + cond.field + " img").each(function(){
				if (cond.value == '1') {
						if (! this.src.match(/_on\.gif/) ) {
							this.src = this.src.replace(/_off\.gif/, "_on\.gif");
						}
				} else {
						if (this.src.match(/_on\.gif/)) {
							this.src = this.src.replace(/_on\.gif/, "_off\.gif");
						}
					}
				});
			//プルダウン
			$("#select_" + cond.field).each(function(){
				$(this).val(cond.value);
			});
		});
	
		//こだわり画像の切り替え
		//いったんすべてOFF画像に
		$(".kodawari img").each(function(){
			if( this.src.match(/_on\.gif/) ){
					this.src = this.src.replace(/_on\.gif/, "\.gif");
				}
		});
		
		//周辺施設の距離
		var dist = function(part){
			var d = jQuery.grep(part,function(a){
				return a.field == 'facilityDist';
			});
			return (d.length == 1) ? d[0].value : 0;
		}(this.condPart.conds);
		
		//周辺施設 該当の距離以外のパネルはすべて非表示にする
		$("dl.kodawari li").each(function(){
			if(/disp_facility/.test(this.id)){
				$(this).css("display", "none");
			}
		});
		
		//条件が設定されているものをONにする
		jQuery.each(this.condPart.conds, function(){
			if(this.value > 0){
				//周辺施設以外のこだわり条件
				$("#disp_" + this.field + " img").each(function(){
					if(! this.src.match(/_on\.gif/) ){
						this.src = this.src.replace(/\.gif/, "_on\.gif");
						$(this).parents("li").css("display", "block");
					}
				});
				//周辺施設
				$("#disp_" + this.field + "_" + dist + " img").each(function() {
					if(! this.src.match(/_on\.gif/) ){
						this.src = this.src.replace(/\.gif/, "_on\.gif");
						$(this).parents("li").css("display", "block");
					}
				});
			} else {
				//周辺施設以外のこだわり条件
				$("#disp_" + this.field + " img").each(function(){
					this.src = this.src.replace(/_on\.gif/, "\.gif");
					$(this).parents("li").css("display", "block");
				});
				//周辺施設
				$("#disp_" + this.field + "_" + dist + " img").each(function() {
					this.src = this.src.replace(/_on\.gif/, "\.gif");
					$(this).parents("li").css("display", "block");
				});
			}
		});
	},
	
	//検索を実行する
	executeSearch: function(url){
		this.condDisp.put("currentPage", 1);
		this.showSearchResult(url);
	},
	
	//
	showSearchResult : function(url){
		url = (url == undefined) ? this.url : url;
		this.switchLeftConditions();
		
		$("body").append("<div id='rightBox_load'><img src='/images/loading2.gif'/></div>");	
		$("#rightBox").append("<div id='rightBox_overlay'></div>");

		$("#rightBox_overlay").width($("#rightBox").width());
		$("#rightBox_overlay").height($("#rightBox").height());
		$("#rightBox_overlay").css('top',  $("#rightBox").position().top);
		$("#rightBox_overlay").css('left', $("#rightBox").position().left);
		
		if(tb_detectMacXFF()){
			$("#rightBox_overlay").addClass("TB_overlayMacFFBGHack");
		}else{
			$("#rightBox_overlay").addClass("TB_overlayBG2");
		}
	
		$('#rightBox_load').show();
				
		$("#rightBox").load(url, this.map4url(), function(){$('#rightBox_load').remove();$("#rightBox_overlay").remove();});
	},
	
	//ページを移動する
	movePage: function(p){
		this.condDisp.put("currentPage", p);
		location.href = this.getUrl();
	},	
	
	//賃貸用RSSフィード
	toRssForRent: function(){
		location.href = "/rent/rss/feed?" + $.param(this.map4url());
	},
	
	//売買用RSSフィード
	toRssForBuy: function() {
		location.href = "/buy/rss/feed?" + $.param(this.map4url());
	}
};

/**
 * URL解析クラス
 * 
 */
Century21.UrlTokenizer = function(url) {
	this.url = url;
};
Century21.UrlTokenizer.prototype = {

	bareUrl:function(){
		return this.url.replace(/\?.+$/, "");
	},
	
	params : function(){
		var ret = new Array();
		var paramStr = this.url.split("?")[1];
		var paramArr = paramStr.split("&");
		for(var i=0; i<paramArr.length; i++){
			var p = paramArr[i].split("=");
			ret.push({field:p[0], value:p[1]});
		}
		return ret;
	}
};

/**
 * 画像読み込みクラス
 * 
 */
Century21.ImageLoader = function(url) {
	this.url = url;
}

Century21.ImageLoader.prototype.setImageSize = function(max, oldImage) {
	var image = new Image();
	image['class'] = oldImage['class'];
	
	//画像の読み込み後処理
	image.onload = function(){
		var w = image.naturalWidth != undefined ? image.naturalWidth : image.width;
		var h = image.naturalHeight != undefined ? image.naturalHeight : image.height;
		
		if (max <= Math.max(w, h)) {
			if(w > h){
				var rate = 1.0 * w / max;
				w = max;
				h = Math.round(h / rate);
			} else {
				var rate = 1.0 * h / max;
				w = Math.round(w / rate);
				h = max;
			}
		}
		image.width = w;
		image.height = h;
		$(oldImage).replaceWith(image);
		$(image).addClass("loaded");
	}

	//画像が存在しない場合の処理	
	image.onerror = function(){
		$(oldImage).remove();
	}
	
	image.src = this.url;
};

