﻿function AjaxRequestManager(){
	var self = this;
	this.count = 0;
	this.url2RequestIdMap = {};
	this.requestId2CallbackItemMap = {};
	this.url2RequestObjMap = {};
	this.timer = new CountDownTimer(100);
	this.timer.addCountDownCompleteCallback(function(){
		$.each(self.url2RequestObjMap, function(idx, requestObj){
			if(self.requestId2CallbackItemMap[requestObj.requestId]){
				$.ajax(requestObj);
			}
		});
	})

	this.sendRequest = function(url, dataObject, callback){
		var requestId = this.applyRequestId(url);
		this.url2RequestObjMap[url] = {
			requestId:requestId,
			url:url,
			cache:false,
			type:"POST",
			dataType:"json",
			data:$.extend({"requestId" : requestId}, this.optimizeDataObject(dataObject)),
			scriptCharset:"UTF-8",
			success:function(self){return function(result){self.ajaxCallback(result)}}(this),
			error:this.ajaxErrorCallback
		};
		this.requestId2CallbackItemMap[requestId] = {"url" : url, "callback" : callback};
		this.timer.startCountDown(300);
	}
	this.optimizeDataObject = function(dataObject){
		var ret = {};
		for(var prop in dataObject){
			if(typeof(dataObject[prop]) == "undefined" || dataObject[prop] == null){
				continue;
			}
			ret[prop] = dataObject[prop];
		}
		return ret;
	}
	this.applyRequestId = function(url){
		var ret = ++this.count;
		this.url2RequestIdMap[url] = ret;
		return ret;
	}
	this.ajaxCallback = function(result){
		var requestId = result["requestId"];
		var callbackItem = this.requestId2CallbackItemMap[requestId];
		var url = callbackItem.url;
		var ratestRequestId = this.url2RequestIdMap[url];
		if(requestId >= ratestRequestId){
			callbackItem.callback(result);
		}
		// 破棄する。
		delete this.requestId2CallbackItemMap[requestId];
	}
	this.ajaxErrorCallback = function(XMLHttpRequest, textStatus, errorThrown){
		this.requestId2CallbackItemMap = {};
		this.url2RequestIdMap = {};
		this.count = 0;
	}
}

function CountDownTimer(checkFrequency){
	var self = this;
	this.count = 0;
	var countDownCompleteCallbackList = [];
	var timerId = null;

	var isRunning = function(){
		return timerId != null;
	}

	this.addCountDownCompleteCallback = function(listener){
		countDownCompleteCallbackList.push(listener);
	}

	var task = function(){
		self.count -= checkFrequency;
		if(self.count <= 0){
			self.noticeCountDownComplete();
		}
	}

	var runCountDown = function(){
		timerId = setInterval(task, checkFrequency);
	}

	this.noticeCountDownComplete = function(){
		clearInterval(timerId);
		timerId = null;
		$.each(countDownCompleteCallbackList, function(idx, callback){
			callback();
		})
	}

	this.startCountDown = function(msec){
		this.count = msec;
		if(!isRunning()){
			runCountDown();
		}
	}
}

function SeikyuuCart(requestManager, maxSize){
	this.requestManager = requestManager;
	this.maxSize = maxSize;
	this.eventHandler = new Array();

	this.addEventHandler = function(handler){
		this.eventHandler.push(handler);
	}

	this.add = function(customerId, routeType){
		this.requestManager.sendRequest(
			contextPath + "/ajax_seikyuu_cart_add.json",
			{"customerId" : customerId, "routeType" : routeType},
			function(self){return function(response){self.handleResponse(response, "add")}}(this)
		);
	}

	this.remove = function(customerId){
		this.requestManager.sendRequest(
			contextPath + "/ajax_seikyuu_cart_remove.json",
			{"customerId" : customerId},
			function(self){return function(response){self.handleResponse(response, "remove")}}(this)
		);
	}

	this.handleResponse = function(response, type){
		var cartArea = $("#block-reqlist").find("figure").find("ul");
		var self = this;
		cartArea.html("");

		$.each(response["response"], function(idx, val){
			$("<li>").append(idx + 1 + ". " + val.customerName).append($("<a>").attr("href", "javascript:void(0)").click(function(){
				self.remove(val.customerId);
			}).append("削除")).appendTo(cartArea);
		})
		if(!response["error"]){
			$.each(this.eventHandler, function(idx, val){
				val({"type" : type, "customerSummary" : response["customerSummary"]});
			})
		}else{
			alert(response["message"]);
		}
	}
}

function CheckList(requestManager){
	this.requestManager = requestManager;

	this.checkListId = "check-list";

	this.handlerFunc = function(list){
		var addTarget = $("#" + this.checkListId).find("figure").find("ul");
		addTarget.html("");
		if(list && list.length > 0){
			$.each(list, function(idx, val){
				var li = $("<li>").attr("id", "checkList" + val.customerId);
				replaceCheckListElm(li, val.cartFlag, val.customerName, val.customerId, val.accessNumber, val.acceptMethodType, val.docCombinationType);
				li.appendTo(addTarget);
			});
		}
	};

	this.getList = function(){
		this.requestManager.sendRequest(
			contextPath + "/ajax_check_list.json",
			{},
			function(self){return function(response){self.handlerFunc(response["response"])}}(this)
		)
	}
}

// 変数定義と組み立て。
var rm = new AjaxRequestManager();
var seikyuuCart = new SeikyuuCart(rm, 30);
var checkList = new CheckList(rm);
seikyuuCart.addEventHandler(function(event){
	var cs = event.customerSummary;
	if(cs){
		var elm = $("#checkList" + cs.id);
		if(elm.length > 0){
			var cartFlag = event.type == "add";
			replaceCheckListElm(elm, cartFlag, cs.name, cs.id, cs.accessNumber, cs.acceptMethod, cs.docCombinationType);
		}
	}
});


// 以下Util的な関数。
function isRequestable(acceptMethodType, docCombinationType){
	if(acceptMethodType){
		return (acceptMethodType == 1 && docCombinationType) || acceptMethodType == 3;
	}
	return false;
}

function replaceCheckListElm(li, cartFlag, customerName, customerId, accessNumber, acceptMethod, docCombinationType){
	li.html("");
	li.append($("<a>").attr("href", contextPath + "/gakkou/" + accessNumber + "/").append(customerName));
	if(isRequestable(acceptMethod, docCombinationType)){
		if(!cartFlag){
			var hrefValue = "javascript:void(0);";
			var targetValue = "_self";
			var onclickFunc = null;
			if(acceptMethod == 1){
				onclickFunc = function(){
					seikyuuCart.add(customerId, 3);
					return false
				}
			}else if(acceptMethod == 3){
				if(nonDispTermsFlag != null && nonDispTermsFlag == "true"){
					hrefValue = contextPath + "/seikyuu/telemail/" + customerId + "/";
					targetValue = '_blank';
				}else{
					onclickFunc = function(){
						executeWithParam(contextPath + "/seikyuu/telemail/" + customerId + "/", "post", {"seikyuuParamDto.backUrl" : document.URL});
						checkList.getList();
						return false;
					}
//					onclickValue += 'executeWithParam("';
//					onclickValue += contextPath + "/seikyuu/telemail/" + customerId + "/";
//					onclickValue += '", "post", {"seikyuuParamDto.backUrl" : "' + window.location + '"});checkList.getList();return false;';
				}
			}
			var a = $("<a>").attr({
				"href" : hrefValue,
				"target" : targetValue,
				"class" : "btn"
			}).append("資料請求");
			if(onclickFunc){
				a.click(onclickFunc);
			}
			li.append(a);
		}else{
			li.append($("<span>").append("追加済み"));
		}
	}
}

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g, '');
}
