//**********************************************************
//    カートWidget、お問い合わせ候補一覧 に関するJavaScript
//            - require jquery.js
//            - require jquery.cookie.js
//                                    muraki@triax.jp
//**********************************************************

function Cart(cookie_name) {
	// クッキー関連
	this.cookie_name = cookie_name;
	this.cookie_params = {path:'/'}; // 有効期限:セッション終了時
	// データフィールド
	this.prop_code_list = []; // カートに追加されている募集区画コードのリスト
	this.building_dict = {};  // 建物コードと建物名の辞書（カート表示に必要な分のみ）
	// 定数
	this.SEPARATOR = ',';
	
	// コンストラクタ実行
	this._init();
}

Cart.prototype = {
	_init: function() {
		this._load();
		this._make_building_dict(); // htmlから、建物コード対建物名の辞書を構築
	},
	_make_building_dict: function(prop_code_list) {
		var self = this; //無名関数内からの自己参照用
		$(".cart .building_dict_storage li").each(function(){
			code = $(this).find(".code").text();
			name = $(this).find(".name").text();
			self.building_dict[code] = name;
		});
	},
	_check_and_merge_prop_code_list: function(prop_code_list) {
		var self = this; //無名関数内からの自己参照用
		if(prop_code_list.length == 0){
			alert('何も選択されていません。');
			return false; // マージを実行しない
		}
		var prev_count = this.prop_code_list.length;
		if(prev_count + prop_code_list.length >= 100){
			alert('お問合せ候補一覧への登録制限を超えています。件数を減らしてご登録ください。');
			return false; // マージを実行しない
		}
		//### マージ（カートへの追加）実行 ###
		$.each(prop_code_list, function(i, prop_code){
			if($.inArray(prop_code, self.prop_code_list) == -1)
				self.prop_code_list.push(prop_code);
		});
		if(prev_count == this.prop_code_list.length){
			alert('この物件はすでにお問合せ候補一覧に追加されています。');
		}else if(this.prop_code_list.length ==  prev_count + prop_code_list.length){
			alert('お問い合わせ候補に追加いたしました。');
		}else{
			alert('選択した物件の中にすでにお問合せ候補一覧に登録された物件がありましたので、\nその物件を除いて追加いたしました。');
		}
		return true;
	},
	add: function(prop_code_list) {
		prop_code_list = this._validate_prop_code_list(prop_code_list);
		success = this._check_and_merge_prop_code_list(prop_code_list);
		if(!success) return; // 終了
		this._save();
		this._render_widget();
	},
	remove: function(remove_prop_code_list) {
		var ok = confirm('削除いたします。よろしいですか？');
		if(!ok) return; // 終了
		
		this.prop_code_list = $.grep(this.prop_code_list, function(code, i){
			if($.inArray(code, remove_prop_code_list) != -1)
				return false; //削除
			else
				return true; //残す
		});
		this._save();
		this._render_cart_list(remove_prop_code_list);
		
		// 親画面をリロード
		if(window.opener){
			window.opener.location.reload();
		}
	},
	_load: function() {
		var prop_code_str = $.cookie(this.cookie_name); // TODO:クッキーがない場合の挙動を検証
		// console.debug(prop_code_str);
		if(prop_code_str != null)
			this.prop_code_list = prop_code_str.split(this.SEPARATOR);
		this.prop_code_list = this._validate_prop_code_list(this.prop_code_list);
		// console.debug(this.prop_code_list);
	},
	_save: function() {
		prop_code_str = this.prop_code_list.join(this.SEPARATOR);
		// console.debug(prop_code_str);
		$.cookie(this.cookie_name, prop_code_str, this.cookie_params);
		// console.debug(this.cookie_params);
	},
	_render_widget: function(){
		var self = this; //無名関数内からの自己参照用
		$('.cart .display_field').empty(); //消去
		var building_code_list = this._get_building_code_list();
		$.each(building_code_list, function(i, building_code){
			var name = self.building_dict[building_code];
			var property_count = self._get_belong_property(building_code).length;
			if(property_count > 0){
				var li = $('<li>');
				li.text(name + ' ' + property_count + '件');
				$('.cart .display_field').prepend(li);
			}
		});
		self.update_message();
	},
	_render_cart_list: function(prop_code_list){
		$.each(prop_code_list, function(i, prop_code){
			$("a#" + prop_code).closest(".property_row").remove();
		});
		$(".building_row:not(:has(.property_row))").remove();
		this.update_cart_list_message();
	},
	_get_building_code_list: function(){
		var building_code_list = [];
		$.each(this.prop_code_list, function(i, prop_code){
			var bldg_code = String(prop_code).slice(0, 6); // 建物コードを取得
			if($.inArray(bldg_code, building_code_list) == -1)
				building_code_list.push(bldg_code);
		});
		return building_code_list;
	},
	_get_belong_property: function(building_code){
		return $.grep(this.prop_code_list, function(prop_code, i){
			// 募集区画コードの先頭が建物コードと一致＝その建物に属している
			if(String(prop_code).indexOf(building_code) == 0){
				return true;
			}else{
				return false;
			}
		});
	},
	_validate_prop_code_list: function(prop_code_list){
		return $.map(prop_code_list, function(code, i){
			if(isNaN(parseInt(code)))
				return null;
			else
				return code;
		});
	},
	update_message: function(){
		if(this.prop_code_list.length == 0){
			$('.cart .message .zero').show();
			$('.cart .message .not_zero').hide();
		}else{
			$('.cart .all_property_count').text(this.prop_code_list.length);
			$('.cart .message .zero').hide();
			$('.cart .message .not_zero').show();
		}
	},
	update_cart_list_message: function(){
		$('.cart_list .building_count').text($(".building_row").size());
		$('.cart_list .property_count').text($(".property_row").size());
		if(this.prop_code_list.length == 0){
			$('.cart_list .zero_message').show();
			$('.cart_list .not_zero_message').hide();
			$('.contactCol-A1_office').hide(); // フォーム部分を非表示に
		}
	}
}

//--------------------------------------------------
//
// カートに募集区画を追加する。
// [詳細]
//  - クッキーに募集区画のコードを保存
//  - カート領域の表示を更新
//
//--------------------------------------------------
function regist_add_cart_event(cart){
	cart.update_message();
	
	$(".add_cart_button").bind("click", function(event){
		var prop_code_list = $("[name=prop_code]:checked").map(function(){return $(this).val()});
		cart.add(prop_code_list);
		$("[name=prop_code]:checkbox").attr("checked", false); // 物件選択のチェックボックスをクリアする
		return false;
	});
}

//--------------------------------------------------
//
// カートから募集区画を削除する。
// [詳細]
//  - クッキーに募集区画のコードを保存
//  - 領域の表示を更新
//
//--------------------------------------------------
function regist_delete_cart_event(cart){
	$(".delete_cart_button").bind("click", function(){
		var prop_code = $(this).attr('id');
		cart.remove([prop_code]);
		return false;
	});
	$(".delete_building_cart_button").bind("click", function(){
		var prop_code_list = $(this).closest(".building_row")
			.find(".property_row a.delete_cart_button").map(function(){
				return $(this).attr('id');
		});
		cart.remove(prop_code_list);
		return false;
	});
}

//--------------------------------------------------
//
// 詳細画面用の一括カート追加処理
// [詳細]
// 建物詳細画面なら：
//   - 建物に紐づく全ての募集区画をカートに追加
// 募集区画詳細画面なら：
//   - その募集区画自身をカートに追加
//
//--------------------------------------------------
function regist_add_cart_for_detail_event(cart){
	$("a.add_cart_button_bldg_detail").bind("click", function(event){
		var prop_code_list = $("[name=prop_code]:checkbox").map(function(){return $(this).val()});
		// console.debug(prop_code_list);
		cart.add(prop_code_list);
		return false;
	});
	$("a.add_cart_button_prop_detail").bind("click", function(event){
		var prop_code_list = [$("div.function_button [name=prop_code]:hidden").val()];
		// console.debug(prop_code_list);
		cart.add(prop_code_list);
		return false;
	});
}

//--------------------------------------------------
//
// リンクのクリック毎に、チェック／アンチェックを
// 切り替えるイベントを登録
//
//--------------------------------------------------
function get_check_all_func(checked) {
	return function(){
		$(':checkbox').attr('checked', checked);
	};
}
function regist_check_all_event(){
	$('a.all_check').toggle(
		get_check_all_func(true),
		get_check_all_func(false)
	);
}

//--------------------------------------------------
//
// オフィス物件特定お問い合わせへ飛ぶためのフォームの
// ために、サーバで生成した物件情報JSONを
// hiddenにセットする処理
//
//--------------------------------------------------
function regist_contact_button_click_event(cart){
	$("form.contact_button_form :image").click(function(){
		// どのページのボタンであるかによって、物件コードの取得処理を分岐
		var prop_code_list = [];
		if($(this).is(".page_type_cart")){ // お問い合わせ候補一覧
			prop_code_list = cart.prop_code_list;
		}else if($(this).is(".page_type_detail")){ // 建物 or 募集区画詳細
			var property_elem = $("div.function_button [name=prop_code]:hidden");
			if(property_elem.size() == 0){ // 建物
				prop_code_list = $("[name=prop_code]:checkbox").map(function(){return $(this).val()});
			}else{ // 募集区画
				prop_code_list.push(property_elem.val());
			}
		}
		// AJAX通信用のURLを生成
		var url = '/search/cart/_property_list_json?';
		$.each(prop_code_list, function(i, code){
			url += ('code=' + code + '&');
		});
		// サーバで生成したJSONを取得し、hiddenにセットする
		$.ajaxSetup({async: false}); // 同期通信に設定
		$.get(url, function(data){
			// console.debug(data);
			$("form.contact_button_form :hidden[name=property_list_json]").val(data);
		});
		$.ajaxSetup({async: true}); // 非同期通信に戻す
	});
	// kencorp.co.jpのお問い合わせへ飛ぶ際にgoogle analyticsの
	// 情報を引き継ぐための処理
	$("form.contact_button_form :image").click(function(){
		pageTracker._linkByPost(this);
	});
}

// execute function on document ready
$(function(){
	// １．open_window_submitは、regist_contact_button_click_eventの後に
	// bindしなければならない
	$(".contact_button_form :image").unbind('click', open_window_submit);
	
	var cart=new Cart('cart_property_code_list');
	regist_add_cart_event(cart);
	regist_delete_cart_event(cart);
	// サーバで生成したJSONをhiddenにセットする処理
	regist_contact_button_click_event(cart);
	
	// ２．unbindしていたopen_window_submitを再びbind
	$(".contact_button_form :image").bind('click', open_window_submit);
	// ３．ただし「お問い合わせ候補一覧」画面からはお問い合わせへは
	// 同一画面に遷移するという仕様から、同画面のボタンからは
	// open_window_submitをunbindする
	$(".contact_button_form :image.page_type_cart").unbind('click', open_window_submit);
	
	// 詳細画面用、一括カート追加処理
	regist_add_cart_for_detail_event(cart);
	// チェックを「全て選択する」処理
	regist_check_all_event();
});
