//ページネーションセマフォ
var pagerSemaphore = 0;

//javascript拡張
String.prototype.replaceAll = function(org, dest){
	return this.split(org).join(dest);
}
//trim関数
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}

//オブジェクト数カウント
function count(obj)
{
	var count = 0;
	for(temp in obj) count++;
	return count;
}

//location.hrefを絶対にスラッシュ付きで取得
function getLocationHref()
{
	//var currentURL = location.href.replace(/([^:])\/\/+/, '$1');
	//ページ内リンクを除去しURLを取得
	var currentURL = location.href.split('#')[0].replace(/([^:])\/\/+/, '$1');
	if(currentURL.charAt(currentURL.length - 1) != '/')
		currentURL += '/';
	return currentURL;
}

//prまでのURLを取得
function getBaseURL(){
	var baseURL = location.href.match(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?\/search\/pr-[\w+:*]+/)[0];
	if(baseURL.charAt(baseURL.length - 1) != '/')
		baseURL += '/';
	return baseURL;
}

//URLの最終セグメントを取得
function getLastURL()
{
	var splitURL = getLocationHref().split('/');
	var lastURL = splitURL[splitURL.length-2];
	
	return lastURL;
}

//object -> json文字列 -> URI文字列　または　json文字列 -> URI文字列
function encodeCondition(condition)
{
	if(typeof condition != 'object'){
		if(typeof condition == 'string')
			return encodeURIComponent(condition);
		else{
			//alert('condition encode error');
			return false;
		}
	}else
		return encodeURIComponent($.toJSON(condition));
}


function search_encodeCondition(condition)
{
	return encodeCondition(condition);
}

//DOM読み込み完了時
$(document).ready(function(){
	var currentURL = getLocationHref();
	var lastURL = getLastURL();

	//物件
	if(lastURL.match(/obj-[\w+:*]+/)){
		restoreCondition();
	//エリアモーダル
	}else if(lastURL.match(/a1-0/)){
		showAddress1();
	//市町村
	}else if(lastURL.match(/a1-[\w+:*]+/)){
		restoreCondition();
	//沿線モーダル
	}else if(lastURL.match(/li-0/)){
		showAlongLine();
	//路線
	}else if(lastURL.match(/li-[\w+:*]+/)){
		restoreCondition();
	//駅
	}else if(lastURL.match(/st-[\w+:*]+/)){
		restoreCondition();
	//地図モーダル
	}else if(lastURL.match(/ma-0/)){
		showMap();
	//地図描画
	}else if(currentURL.indexOf('/ma-') >= 0 || currentURL.indexOf('/ce-') >= 0){
		drawMap();
	//キャンペーン
	}else if(lastURL.match(/ca-*/)){
		restoreCondition();
	//県のみ
	}else if(lastURL.match(/pr-[\w+:*]+/)){
		restoreCondition();
	//キーワード
	}else if(lastURL.match(/ke-.*/)){
		restoreCondition();
	//ディスプレイオプション
	}else if(lastURL.match(/di-.*/)){
		restoreCondition();
	}
	//マウスホバーアニメーション
	$('tr.serch_bar_contents').live('mouseover', function(){ $(this).addClass('selected'); });
	$('tr.serch_bar_contents').live('mouseout', function(){ $(this).removeClass('selected'); });
	
	//キーワードフィールド制御
	$('input[name="freeword"]').click(function(){
		if($(this).val() == 'キーワード検索'){
			$(this).val('');
		}
	});
	//キーワードエンターサポート
	$('input[name="freeword"]').keydown(function(e){
		if(e.keyCode == 13 && $(this).val() != ''){
			submitKeyword($(this));
		}
	});
});

//検索条件を取得
function getCurrentCondition(partial)
{
	partial = partial || false;
	var condition = {
		pr: {
			cd:[],		//prefecture:県CD
			dis:[]		//表示
		},
		obj:{
			id:[],		//object:物件ID
			dis:[]		//表示
		},
		al: {			//along_line:沿線カテゴリ
			li: [],		//line：線
			st: [],		//station:駅
			dis:{}		//検索表示用
		},
		ar: {			//area:エリアカテゴリ
			a1: [],		//address1:住所1
			dis:[]		//address1表示用
		},
		ma:{
			cina:'',	//市町村名
			adful:'',	//住所フル
			cidis:[],	//市町村表示制度順
			celat:0,	//中心緯度
			celng:0,	//中心経度
			nelat:0,	//北東緯度
			nelng:0,	//北東経度
			swlat:0,	//南西緯度
			swlng:0,	//南西経度
			zo:0		//現在のズームレベル
		},
		ke: '',			//keyword:キーワード
		ca:{
			id:[],		//campaign:キャンペーンID
			cd:[]		//campaign:キャンペーンCD
		},
		la:[],			//layout:間取り配列
		re:{			//rent:賃料カテゴリ
			lo: '',		//low:安
			hi: '',		//high:高
			gs: ''		//general_service:共益費
		},
		tw: '',			//time to walk:（駅から）歩くと掛かる時間
		bu: [],			//building:建物配列
		sp: {			//space:面積カテゴリ
			sm: '',		//small:小
			la: ''		//large:大
		},
		py: '',			//passed year:築年数
		eq: [],			//equipment:設備配列
		di: [],			//display_option:表示オプション配列
		or:{
			by: '',		//デフォルト
			asc: ''
		},
		pp: 10,			//per page
		pn: 1,			//デフォルトpega number
		tab: 1			//1デフォルトでリスト
	};
	
	//----------データ抽出----------
	if(!partial){
		/*--------------------------大項目-------------------------*/
		//物件
		$('input[type="hidden"][name="obj_id[]"]').each(function(i){
			condition['obj']['id'].push($(this).val());
		});
		//沿線
		$('input[type="hidden"][name="al_li[]"]').each(function(i){
			condition['al']['li'].push($(this).val());
		});
		//駅
		$('input[type="hidden"][name="al_st[]"]').each(function(i){
			condition['al']['st'].push($(this).val());
		});
		//エリア、市
		$('input[type="hidden"][name="ar_a1[]"]').each(function(i){
			condition['ar']['a1'].push($(this).val());
		});
		//地図,デフォルト
		condition['ma']['cina'] = $('input[type="hidden"][name="ma_cina"]').val();
		//座標
		condition['ma']['nelat'] = search_getValue('ma_nelat');
		condition['ma']['nelng'] = search_getValue('ma_nelng');
		condition['ma']['celat'] = search_getValue('ma_celat');
		condition['ma']['celng'] = search_getValue('ma_celng');
		condition['ma']['swlat'] = search_getValue('ma_swlat');
		condition['ma']['swlng'] = search_getValue('ma_swlng');
		//現在の位置情報、北東・南西の座標
		if(typeof gmap != 'undefined'){
			condition['ma']['zo'] = map_getZoom();
		}
		//フリーワード
		condition['ke'] = $('input[name="ke"]').val();
		if(condition['ke'] == undefined) condition['ke'] = '';
	}
	/*--------------------------大項目-------------------------*/
	//県名
	$('input[type="hidden"][name="pr_cd[]"]').each(function(i){
		condition['pr']['cd'].push($(this).val());
	});
	$('input[type="hidden"][name="pr_dis[]"]').each(function(i){
		condition['pr']['dis'].push($(this).val());
	});
	/*------------------------小項目-----------------------*/
	if(!partial){
		//キャンペーン、チェックされたもの
		$('input[name="ca_id[]"]:checked').each(function(){
			condition['ca']['id'].push($(this).val());
		});
		//キャンペーン、URLに埋め込まれている値
		$('input[name="ca_id[]"][type="hidden"]').each(function(){
			condition['ca']['id'].push($(this).val());
		});
		//キュンペーンCD
		$('input[name="ca_cd[]"][type="hidden"]').each(function(){
			condition['ca']['cd'].push($(this).val());
		});
		//間取り
		$('input[name="la[]"]:checked').each(function(i){
			condition['la'].push($(this).val());
		});
		//家賃
		condition['re']['lo'] = $('select[name="re_lo"] option:selected').val();
		condition['re']['hi'] = $('select[name="re_hi"] option:selected').val();
		condition['re']['gs'] = $('input[name="re_gs"]:checked').val() != null ? '1': '0';
		//駅から何分
		condition['tw'] = $('select[name="tw"] option:selected').val();
		//建物種別
		$('input[name="bu[]"]:checked').each(function(i){
			condition['bu'].push($(this).val());
		});
		//面積
		condition['sp']['sm'] = $('select[name="sp_sm"] option:selected').val();
		condition['sp']['la'] = $('select[name="sp_la"] option:selected').val();
		//築年数
		condition['py'] =  $('select[name="py"] option:selected').val();
		//設備
		$('input[name="eq[]"]:checked').each(function(i){
			condition['eq'].push($(this).val());
		});
		//表示オプション
		$('input[name="di[]"]:checked').each(function(i){
			condition['di'].push($(this).val());
		});
		//---------------抽出ここまで--------------
	}
	
	return condition;
}

//地図検索ビューからの検索
function search_ajaxSearch(condition)
{
	ajaxSearch(condition);
}
//通信未完了は排除
var semaphore = true;

//ajax検索
function ajaxSearch(condition)
{
	var currentURL = getLocationHref();
	var lastURL = getLastURL();
	var targetURL = getLocationHref() + 'action-ajax_search/';
	var xhr = $.ajax({
		type : 'post',
		url : targetURL,
		data : { 'json': encodeCondition(condition) },
		cache : false,
		beforeSend : function(XMLHttpRequest){
			//前の通信が未完了
			if(!semaphore){
				XMLHttpRequest.abort();
				return false;
			}else
				semaphore = false;
			//地図のサイドボックスを除去
			$('#map_sidebox').remove();
			$('object').hide();
			//地図の時だけ背景透過
			if(lastURL.match(/ma-*/)){
				$.blockUI({
					showOverlay: true,
					message:$('#ajax_loader'),
					css:{
						border:'none', width:'0px', height:'0px', left:($(document).width()-$('#ajax_loader').width()+210)/2+'px',  cursor:'wait'
					},
					overlayCSS: {
						backgroundColor: '#FFFFFF',
						opacity:0
					}
				});
			}else{
				$.blockUI({
					showOverlay: true,
					message:$('#ajax_loader'),
					css:{
						border:'none', width:'0px', height:'0px', left:($(document).width()-$('#ajax_loader').width()+210)/2+'px',  cursor:'wait'
					},
					overlayCSS: {
						backgroundColor: '#000000',
						opacity:0.25
					}
				});
			}
		},
		success : function(html, status){
			//フラッシュを隠す
			$('object').hide();
			//間取り毎の集計
			var xjson = eval(decodeURIComponent(xhr.getResponseHeader('X-JSON')));
			if(xjson != null){
				var layoutCountData = xjson['layout_count'];
				for(var i=0;i<layoutCountData.length;i++){
					var item = layoutCountData[i];
					var checkbox = $('input[name="la[]"][value="' + item['plan_code'] + '"]');
					var layoutbox = $('#layoutbox' + item['plan_code']);
					layoutbox.removeAttr('style');
					checkbox.removeAttr('disabled');
					//間取り毎の件数
					$('#layout' + item['plan_code']).html('&nbsp;(' + item['count'] +')');
					if(item['count'] == 0){
						checkbox.removeAttr('checked');
						checkbox.attr('disabled', 'disabled');
						layoutbox.css('color', '#AAAAAA');
					}
				}
			}
			//地図検索
			//if(lastURL.match(/ma-*/) || lastURL.match(/ce-*/)){
			if(currentURL.indexOf('ma-') >= 0 || currentURL.indexOf('ce-') >= 0){
				//地図検索の時だけhtmlにJSON文字列が代入
				map_redraw(eval(html));
			}else{
				$('#redraw').html(html);
			}
			$.unblockUI({
				fadeOut:250,
				onUnblock:function(){
					//flashを再表示
					$('object').show();
				}
			});
			//ページネーション時トップへ戻る
			if(pagerSemaphore === 1){
				$('html,body').animate({ scrollTop: 0 }, 0);
				//セマフォを初期化
				pagerSemaphore = 0;
			}
		},
		complete: function(){
			semaphore = true;
		}
	});
}

//検索結果制御情報取得
function search_getValue(attrName)
{
	var returnVal = '';
	
	returnVal = $('div#hidden_info_box input[name="' + attrName + '"]').val();
	if(returnVal == undefined){
		returnVal = '';
	}
	return returnVal;
}

//検索用制御情報セット
function search_setValue(attrName, value)
{
	$('div#hidden_info_box input[name="' + attrName + '"]').val(value);
}

//画面遷移からの復帰
function restoreCondition()
{
	var condition = getCurrentCondition();
	var per_page = search_getValue('pp');
	var tab = search_getValue('tab');
	var page_number = search_getValue('pn');
	var order_by = search_getValue('or_by');
	var asc = search_getValue('or_asc');
	
	if(per_page != '')
		condition.pp = per_page;
	if(tab != '')
		condition.tab = tab;
	if(page_number != '')
		condition.pn = page_number;
	if(order_by != '')
		condition.or.by = order_by;
	if(asc != '')
		condition.or.asc = asc;
	
	ajaxSearch(condition);
}

//条件変更時
function changeCondition()
{
	var condition = getCurrentCondition();
	var perPage = search_getValue('pp');
	if(perPage != '') condition.pp = perPage;
	var tab = search_getValue('tab');
	if(tab != '') condition.tab = tab;
	
	ajaxSearch(condition);
}

//タブ
function changeTab(tab)
{
	var condition = getCurrentCondition();
	
	condition.tab = tab;
	
	condition.pn = search_getValue('pn');
	condition.pp = search_getValue('pp');
	condition.or.asc = search_getValue('or_asc');
	condition.or.by = search_getValue('or_by')
	
	
	ajaxSearch(condition);
}
//最大表示数
function changePerPage(event)
{
	var condition = getCurrentCondition();
	
	//セレクトボックスの値をセット
	search_setValue('pp', $('option:selected', event).val());
	condition.pp = search_getValue('pp');
	condition.tab = search_getValue('tab');
	condition.or.asc = search_getValue('or_asc');
	condition.or.by = search_getValue('or_by');

	ajaxSearch(condition);
}
//ページャー
function pager(pageNumber)
{
	pagerSemaphore = 1;
	var condition = getCurrentCondition();
	
	condition.pn = pageNumber;
	
	condition.pp = search_getValue('pp');
	condition.tab = search_getValue('tab');
	condition.or.asc = search_getValue('or_asc');
	condition.or.by = search_getValue('or_by');
	
	ajaxSearch(condition);
}
//順番入れ替え
function changeOrder(orderBy, asc)
{
	var condition = getCurrentCondition();
	
	condition.or.asc = asc;
	condition.or.by = orderBy;
	
	condition.pp = search_getValue('pp');
	condition.tab = search_getValue('tab');

	ajaxSearch(condition);
}

function showObjectList(objURL)
{
	location.href = objURL;
}

//もしも検索
function ifRetrieval(jsonString)
{
	//URI -> String -> JSONオブジェクト
	if(jsonString != '')
		ajaxSearch($.evalJSON(encodeURIComponent(jsonString)));
}

//沿線
function showAlongLine()
{
	var documentWidth = $(document).width();
	$.ajax({
		type : 'post',
		url : getLocationHref() + 'action-ajax_along_line/',
		data : {
			'json': encodeCondition(getCurrentCondition())
		},
		dataType : 'html',
		success : function(data, status){
			var inner_layer = $('#inner_layer');
			inner_layer.empty();
			inner_layer.html(data);
			inner_layer.css({position:'absolute', height:'100%'});
			$.blockUI({
				fadeIn:0,
				fadeOut:300,
				message:inner_layer,
				css:{
					position:'absolute', height:'100%',  overflow:'auto', top:'50px', left:(documentWidth-700)/2+'px', width:'700px', textAlign:'left', cursor:'auto'
				}
			});
		}
	});
}

//エリア
function showAddress1()
{
	var documentWidth = $(document).width();
	$.ajax({
		type : 'post',
		url : getLocationHref() + 'action-ajax_address1/',
		data : { 'json': encodeCondition(getCurrentCondition()) },
		dataType : 'html',
		success : function(data, status){
			var inner_layer = $('#inner_layer');
			
			inner_layer.empty();
			inner_layer.html(data);
			inner_layer.css({position:'absolute', height:'100%'});
			$.blockUI({
				fadeIn:0,
				fadeOut:300,
				message:inner_layer,
				css:{
					position:'absolute', height:'100%',  overflow:'auto', top:'50px', left:(documentWidth-700)/2+'px', width:'700px', textAlign:'left', cursor:'auto'
				}
			});
		}
	});
}

//地図
function showMap()
{
	var documentWidth = $(document).width();
	$.ajax({
		type : 'post',
		url : getLocationHref() + 'action-ajax_map/',
		data : {
			'json': encodeCondition(getCurrentCondition())
		},
		dataType : 'html',
		success : function(data, status){
			var inner_layer = $('#inner_layer');
			
			inner_layer.empty();
			inner_layer.html(data);
			inner_layer.css({position:'absolute', height:'100%'});
			$.blockUI({
				fadeIn:0,
				fadeOut:300,
				message:inner_layer,
				css:{
					position:'absolute', height:'100%',  overflow:'auto', top:'50px', left:(documentWidth-700)/2+'px', width:'700px', textAlign:'left', cursor:'auto'
				}
			});
		}
	});
}

//マップ描画
function drawMap()
{
	var condition = getCurrentCondition();
	
	//地図検索情報
	condition.ma.cina = search_getValue('ma_cina');
	condition.ma.nelat = search_getValue('ma_nelat');
	condition.ma.nelng = search_getValue('ma_nelng');
	condition.ma.celat = search_getValue('ma_celat');
	condition.ma.celng = search_getValue('ma_celng');
	condition.ma.swlat = search_getValue('ma_swlat');
	condition.ma.swlng = search_getValue('ma_swlng');
	condition.ma.zo = search_getValue('ma_zo');
	//最大表示物件数
	condition.ma.pp = 1000;
	
	$.ajax({
		type:'post',
		url:getLocationHref() + 'action-ajax_draw_map/',
		data:{ 'json' : encodeCondition(condition) },
		beforeSend:function(){},
		success:function(html, status){
			$('#redraw').html(html);
		}
	});
}

function submitKeyword(keywordObj){
	var url = getBaseURL();
	//json用データオブジェクト
	var condition = getCurrentCondition(true); //大条件を除いて取得
	var keyword = keywordObj.val();
	
	if(keyword == ''){
		alert('文字を入力してください。');
		return false;
	}
	if(keyword == 'キーワード検索'){
		alert('検索単語を入力してください。');
		return false;
	}
	
	keyword = encodeURIComponent(keyword);
	condition.ke = keyword;
	url += 'ke-' + keyword + '/';
	
	$('input[type="hidden"][name="json"]').val(search_encodeCondition(condition));
	$('#keyword_submit').attr('action', url);
	$('#keyword_submit').submit();
}

//マイリスト
function toggleMyList(roomId, anchorObj)
{
	var ajaxURL;
	if(anchorObj.attr('title') == 'push')
		ajaxURL = '/mylist/ajax_add_my_list/' + roomId + '/';
	else
		ajaxURL = '/mylist/ajax_delete_my_list/' + roomId + '/';
		
	var xhr = $.ajax({
		dataType: 'json',
		url: ajaxURL,
		type: 'post',
		cache: false,
		success : function(json, status){
			$('#my_list_count').html(json.my_list_count);
			if(anchorObj.attr('title') == 'push'){
				anchorObj.attr('title', 'pop');
				anchorObj.parent().removeClass('mylist_btn').addClass('mylist_btn2');
				alert('追加しました。');
			}else{
				anchorObj.attr('title', 'push');
				anchorObj.parent().removeClass('mylist_btn2').addClass('mylist_btn');
				alert('削除しました。');
			}
		}
	});
}

//マイ条件に保存
function saveMyCondition()
{
	var xhr = $.ajax({
		dataType: 'json',
		url: '/mycondition/ajax_add_my_condition/',
		type: 'post',
		cache: false,
		success : function(json){
			if(json.result){
				$('#my_condition_count').html(json.my_condition_count);
				alert('条件を保存しました。');
			}else
				alert('条件を保存できませんでした。');
		}
	});
}

//詳細表示
function detail(roomID, windowOpen)
{
	if(windowOpen == undefined)
		windowOpen = false;
	var targetURL = getLocationHref() + 'action-detail/args-' + roomID + '/';
	if(windowOpen)
		window.open(targetURL);
	else
		location.href = targetURL;
}

