/* managerFaqCate component, write logic of managerFaqCate module in this class */
var managerFaqCate = new adminComponent("admin/managerFaqCate");
//when this js have been loaded ,put this object in app cache.
app.registerComponent(managerFaqCate);

managerFaqCate.languageMapping = {
		"en" : "faqCategory-en",
		"zh_CN" : "faqCategory-zh_CN",
		"zh_TW" : "faqCategory-zh_TW"
};

managerFaqCate.on("load",function(){
	var self = this,
		dtdList = [];
	self.editMode = false;
	//$("#rhs").hide();
//	if (getCookie("language_lang") == null) {
//		setCookie("language_lang", "en", 10000);
//	}
//	var language = getCookie("language_lang")||"en";
	this.showLoading("mainContent");
	$("#mainContent").append("<div id='faqCategory-en' style='display:none'></div><div id='faqCategory-zh_CN' style='display:none'></div><div id='faqCategory-zh_TW' style='display:none'></div>");
	
	var currentLanguage = this.currentLanguage || "en";
	for ( var languageKey in this.languageMapping) {
		dtdList.push(this.render(
				"template/admin/managerFaqCate.html",
				this.languageMapping[languageKey],
				this[languageKey + "Data"]?
				this[languageKey + "Data"]:
				"faqCategory/list/" + languageKey
		));
	}
	
	return $.when.apply(null, dtdList).done(function(){
	    $("#loadingDiv").empty().remove();
		$("#faqCategory-" + currentLanguage).show();
		self.currentLanguage = currentLanguage;
		//cache data
		self["enData"] =  arguments[0][1];
		self["zh_CNData"] =  arguments[1][1];
		self["zh_TWData"] =  arguments[2][1];
		
		$("a[name='faqCateSave']").attr("customizedDisabled", true);
		self.initSelectLanaguage(currentLanguage);
		self.initAddEvent();
		self.initUpdateEvent();
		self.initDeleteEvent();
		self.initUpDownEvent();
		
		self.initSaveEvent();
		
		self.initManageQuestionEvent();
		self.buttonColorDisable();
	});
//	return this.render(
//			"template/admin/managerFaqCate.html",
//			"mainContent",
//			this.data?
//			this.data :
//			"faqCategory/language/"+language
//	).done(function(template,data){
//				//cache data
//				self.data = data;
//				
//				//init page
//				$("button[name='faqCateSave']").attr("disabled",true);
//				self.initSelectLanaguage();
//				self.initAddEvent();
//				self.initUpdateEvent();
//				self.initDeleteEvent();
//				self.initUpDownEvent();
//				self.initManageQuestionEvent();
//				self.initSaveEvent();
//				
//				$("#faqCategoryForm").validate({
//					submitHandler : function(){
//						return false;
//					}
//				});
//				
//			});
});

managerFaqCate.on("changeLang", function(language){
	$("button[name='faqCateEng']").attr("style","background:#737173");
	$("button[name='faqCateZh-CN']").attr("style","background:#737173");
	$("button[name='faqCateZh-HK']").attr("style","background:#737173");
	this.currentLanguage = language || "en";
	
	for ( var languageKey in this.languageMapping) {
		$("#" + this.languageMapping[languageKey]).hide();
	}
	
	$("#" + this.languageMapping[language]).show();
	this.initSelectLanaguage(language);
	
});


//
//managerFaqCate.enterChangToUpdateOrAddOrRemove = function() {
//	$("button[name='faqCateUp']").attr("disabled", true);
//	$("button[name='faqCateDown']").attr("disabled", true);
//	
//	$("button[name='faqCateEng']").attr("disabled", true);
//	$("button[name='faqCateZh-CN']").attr("disabled", true);
//	$("button[name='faqCateZh-HK']").attr("disabled", true);
//	$("button[name='manageQuestion']").attr("disabled", true);
//	$("button[name='faqCateSave']").attr("disabled", false);
//};
//
//managerFaqCate.enterChangeToUpOrDown = function() {
//	$("button[name='faqCateAdd']").attr("disabled", true);
//	$("button[name='faqCateEdit']").attr("disabled", true);
//	$("button[name='faqCateRemove']").attr("disabled", true);
//	$("button[name='manageQuestion']").attr("disabled", true);
//	$("button[name='faqCateEng']").attr("disabled", true);
//	$("button[name='faqCateZh-CN']").attr("disabled", true);
//	$("button[name='faqCateZh-HK']").attr("disabled", true);
//
//	$("button[name='faqCateSave']").attr("disabled", false);
//};
//
//managerFaqCate.outOfUpdateOrAddOrRemove = function(){
//	$("button[name='faqCateSave']").attr("disabled", true);
//	$("button[name='manageQuestion']").attr("disabled", false);
//	$("button[name='faqCateEng']").attr("disabled", false);
//	$("button[name='faqCateZh-CN']").attr("disabled", false);
//	$("button[name='faqCateZh-HK']").attr("disabled", false);
//	
//	$("button[name='faqCateUp']").attr("disabled", false);
//	$("button[name='faqCateDown']").attr("disabled", false);
//};
//
//managerFaqCate.changeStatus = function(){
//	var status = $("tr[status='delete']").length + $("table[status='add']").length + $("tr[status='update']").length;
//	if(status==0){
//		this.outOfUpdateOrAddOrRemove();
//	} else {
//		this.enterChangToUpdateOrAddOrRemove();
//	}
//};
/**
 * find one FAQ category object from managerFaqCate cache by linkId
 */
managerFaqCate.findById = function(id){
	var array = this[this.currentLanguage + "Data"].data.data;
	for(var i=0;i<array.length;i++){
		if(array[i].cateId == id){
			return array[i];
		}
	}
};
/**
 * The three button which are named "Eng","繁" and "简" bind event.
 */
managerFaqCate.changLanguageEvent = function(l,inputNames){
	var self = this;
	$("button[name='"+inputNames[l]+"']").die().live("click", function(){
		if(self.editMode===false)
			self.trigger("changeLang", l);
	});
	
};

managerFaqCate.initSelectLanaguage = function(language){
		
	var inputNames = {
			"en" : "faqCateEng",
			"zh_CN" : "faqCateZh-CN",
			"zh_TW" : "faqCateZh-HK"
	};
	
	var lang = language||"en";
	$("button[name='"+inputNames[lang]+"']").attr("style", "");
	for(var l in inputNames) {
		this.changLanguageEvent(l, inputNames);
	}
};
/**
 * bind event of buttons. add button,cancel button of addTable
 */
managerFaqCate.addVersion = 1;
managerFaqCate.initAddEvent = function(){
	var self = this;
	//$("button[name='faqCateAdd']").die();
	$("a[name='faqCateAdd']").die().live("click",function(){
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		$("a[name='faqCateAdd']").attr("customizedDisabled", true);
		var htmlTemplate = "<div id='faqCateAddDiv" + self.addVersion + "' addVersion='" + self.addVersion + "'></div>";
		$("#faqCategory-" + self.currentLanguage+ " div[name='faqCateAddDiv']").append(htmlTemplate);
		//$("#faqCategory-" + self.currentLanguage+ " #faqCateAddDiv").append(htmlTemplate);
		self.adminUpdateOrDeleteMode(
				"faqCate", 
				"add", 
				"template/admin/managerFaqCateAdd.html",
				{ version : self.addVersion },
				"",
				"faqCateAddDiv" + self.addVersion
		).done(function(){
			$("#faqCategory-" + self.currentLanguage+ " #faqCateAddDiv" + self.addVersion).attr("condition", self.currentType + "-" + self.currentLanguage);
			self.addVersion++;
			$("a[name='faqCateAdd']").attr("customizedDisabled", false);
			self.buttonColorDisable();
		});
	});
	
	//$("button[name='faqCateAddCancelButton']").die();
	$("a[name='faqCateAddCancelButton']").die().live("click",function(){	
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true" ) {
			return ;
		}
		//$("#faqCategory-" + self.currentLanguage+ " #faqCateAddDiv").attr("status", "").empty();
		var version = $(this).siblings("input[name='version']").val();
		$("#faqCateAddDiv" + version).remove();
		self.changeMode("faqCate");
	});
};
/**
 * bind event of buttons. Edit button,cancel button of EditTr
 */
managerFaqCate.initUpdateEvent = function(){
	var self = this;
	//$("button[name='faqCateEdit']").die();
	$("a[name='faqCateEdit']").die().live("click",function(){
//		self.render(
//				"template/admin/managerFaqCateUpdate.html",
//				"faqCateShow"+cateId, 
//				cateObject
//		).done(	function(){
//			self.enterChangToUpdateOrAddOrRemove();
//			$("#faqCateShow" + cateId).attr("status", "update");
//		});
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		
		var cateId = $(this).siblings("input[name='cateId']").val();
		var cateObject = self.findById(cateId);
		self.adminUpdateOrDeleteMode(
				"faqCate", 
				"update", 
				"template/admin/managerFaqCateUpdate.html",
				cateObject,
				cateId,
				"faqCategory-" + self.currentLanguage+ " #faqCateShow"
		);
		
	});
	
	//$("button[name='faqCateUpdateCancel']").die();
	$("a[name='faqCateUpdateCancel']").die().live("click",function(){
//		self.render(
//				"template/admin/managerFaqCatePrototype.html",
//				"faqCateShow"+cateId, 
//				cate
//		).done(function(){
//			self.enterChangToUpdateOrAddOrRemove();
//			$("#faqCateShow" + cateId).attr("status", "");
//			self.changeStatus();
//		});
//		
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var cateId = $(this).siblings("input[name='cateId']").val();
		var cate = self.findById(cateId);
		self.adminCancelMethod(
				"faqCate", 
				"template/admin/managerFaqCatePrototype.html",
				cate,
				cateId,
				"faqCategory-" + self.currentLanguage+ " #faqCateShow"
		);
	});
};
/**
 * bind event of buttons. Delete button,cancel button of Delete Tr
 */
managerFaqCate.initDeleteEvent = function(){
	var self = this;
	//$("button[name='faqCateRemove']").die();
	$("a[name='faqCateRemove']").die().live("click",function(){
//		self.render(
//				"template/admin/managerFaqCateDelete.html",
//				"faqCateShow"+cateId, 
//				cate
//		).done(function(){
//			self.enterChangToUpdateOrAddOrRemove();
//			$("#faqCateShow" + cateId).attr("status", "delete");
//		});
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var cateId = $(this).siblings("input[name='cateId']").val();
		var cate = self.findById(cateId);
		
		dialog.show(lang.getMessage('confirmDeleteItems'), lang.getMessage('confirm'), lang.getMessage('buttonCacel')).done(function(clickName){
			if(clickName == lang.getMessage('confirm')){
				self.adminUpdateOrDeleteMode(
						"faqCate", 
						"delete", 
						"template/admin/managerFaqCateDelete.html",
						cate,
						cateId,
						"faqCategory-" + self.currentLanguage+ " #faqCateShow"
				);				
			}
		});
	});
	
	//$("button[name='faqCateDeleteCancel']").die();
	$("a[name='faqCateDeleteCancel']").die().live("click",function(){
//		self.render(
//				"template/admin/managerFaqCatePrototype.html",
//				"faqCateShow"+cateId, 
//				cate
//		).done(function(){
//			self.enterChangToUpdateOrAddOrRemove();
//			$("#faqCateShow" + cateId).attr("status", "");
//			self.changeStatus();
//		});
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		
		var cateId = $(this).siblings("input[name='cateId']").val();
		var cate = self.findById(cateId);
		self.adminCancelMethod(
				"faqCate", 
				"template/admin/managerFaqCatePrototype.html",
				cate,
				cateId,
				"faqCategory-" + self.currentLanguage+ " #faqCateShow"
		);
	});
};
///**
// * @param step clicked tr's customized attribute
// * @param action   up or down
// */
//managerFaqCate.upDownMethod = function(step, action) {
//	var targetStep;
//	step = parseInt(step);
//	if (action == "up") {
//		targetStep = step - 1;
//	} else if (action == "down") {
//		targetStep = step + 1;
//	} else {
//		return;
//	}
//
//	var sourceHtml = $("tr[step=" + step + "]").html();
//
//	var targetHtml = $("tr[step=" + targetStep + "]").html();
//
//	$("tr[step=" + targetStep + "]").empty();
//	$("tr[step=" + targetStep + "]").append(sourceHtml);
//
//	if ($("tr[step=" + targetStep + "]").find("td[background='true']").length) {
//		$("tr[step=" + targetStep + "]").css({
//			"background" : "yellow"
//		});
//	} else {
//		$("tr[step=" + targetStep + "]").css({
//			"background" : ""
//		});
//	}
//
//	$("tr[step=" + step + "]").empty();
//	$("tr[step=" + step + "]").append(targetHtml);
//
//	if ($("tr[step=" + step + "]").find("td[background='true']").length) {
//		$("tr[step=" + step + "]").css({
//			"background" : "yellow"
//		});
//	} else {
//		$("tr[step=" + step + "]").css({
//			"background" : ""
//		});
//	}
//};
/**
 * bind event of buttons. up or down button, cancel button of up or down button
 */
managerFaqCate.initUpDownEvent = function(){
	var self = this;

	$("a[name='faqCateUp']").die().live("click", function() {
		
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}

		$(this).parent("td").parent("tr").attr("status", "upDown");

		var step = $(this).parent("td").parent("tr").attr("step");

		// if step = 0 it is in the top
		if (step == 0) {
			return;
		}

		$(this).parent("td").attr("isBackground", "true");
		self.upDownMethod("faqCate" , step, "up", "faqCategory-" + self.currentLanguage);
	});
	
	
	$("a[name='faqCateDown']").die().live("click", function() {
	
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		
		$(this).parent("td").parent("tr").attr("status", "upDown");

		var step = $(this).parent("td").parent("tr").attr("step");

		var maxStep = $("#faqCategory-" + self.currentLanguage + " tr[step]:last").attr("step");
		// if step = max it is in the top
		if (step == maxStep) {
			return;
		}

		$(this).parent("td").attr("isBackground", "true");
		self.upDownMethod("faqCate" , step, "down", "faqCategory-" + self.currentLanguage);

	});
};

managerFaqCate.saveAdd = function(rest_requests){
	var addRequestList = {};
	$("[status='add']").each(function(i,table){
		var temps = $(table).attr("condition").split("-");
		var cateText = $(table).find("#addFaqcateTxt").val();	
		addRequestList["fcs[" + i + "].cateText"] = cateText;
		addRequestList["fcs[" + i + "].cateLang"] = temps[1];
		////In backend , the validator will validate cateText and cateSeq so I must sent a dummy of "cateSeq" field 
		addRequestList["fcs[" + i + "].cateSeq"] = -1;
		
	});
	var rest_request = {
			url:app.EPRESTAPI_CONTEXT_ROOT + "faqCategory",
			data : addRequestList,
			type:"POST",
			dataType:"json"
	};
	rest_requests.push(ajaxCall(rest_request));
};

managerFaqCate.saveUpdate = function(i,tr,base,rest_requests){
	//var cateText = $(base).find("#faqCateUpdateText").val();
	var cateText = $(base).find("input[name*=cateText]").val();
	var cateId = $(base).find("input[name='cateId']").val();
	var cate = this.findById(cateId);
	var rest_request = {
			url: app.EPRESTAPI_CONTEXT_ROOT + "faqCategory/"+cateId,
			type:"POST",
			data:{
				"_method" : "PUT", 
				"cateText" : cateText,
				//In backend , the validator will validate cateText and cateSeq so this field must be sent
				"cateSeq" : cate.cateSeq
			},
			dataType:"JSON"
	};
	rest_requests.push(ajaxCall(rest_request));
}; 

managerFaqCate.saveDelete = function(i,tr,base,rest_requests){
	var cateId = $(base).find("input[name='cateId']").val();
	var rest_request = {
			url:app.EPRESTAPI_CONTEXT_ROOT+"faqCategory/"+cateId,
			type:"DELETE",
			dataType:"JSON"
	};
	rest_requests.push(ajaxCall(rest_request));
};

managerFaqCate.setUpUpdownList = function(i, tr,upDownList, base){
	var cateId = $(base).find("input[name='cateId']").val();
	var step = $(base).attr("step");
	var cate = this.findById(cateId);
	upDownList["fcs["+i+"].cateId"] = cateId;
	upDownList["fcs["+i+"].cateSeq"] = step;
	//In backend , the validator will validate cateText and cateSeq so this field must be sent
	upDownList["fcs["+i+"].cateText"] = cate.cateText;
};

managerFaqCate.saveUpDown = function(upDownList,rest_requests){
	var rest_request = {
			url: app.EPRESTAPI_CONTEXT_ROOT+"faqCategory/reorder",
			type:"POST",
			data:upDownList,
			dataType:"JSON"
	};
	rest_requests.push(ajaxCall(rest_request));
}; 

managerFaqCate.initSaveEvent = function(){
	var self = this;
	//$("button[name='faqCateSave']").die();
	$("a[name='faqCateSave']").die().live("click",function(){
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		$("a[name='faqCateSave']").attr("customizedDisabled", true);
//		if(!$("#faqCategoryForm").valid()){
//			app.langChanged();
//			console.log("----valation return----");
//			$("button[name='faqCateSave']").attr("disabled", false);
//			return;
//		}
		var validator = new Validator(function(divId){
			var temps = divId.split("-");
			self.trigger("changeLang", temps[1]);
		});
		
		var dtdList = [];
		for ( var languageKey in self.languageMapping) {
			var ok = validator.validateDiv(self.languageMapping[languageKey]);
			dtdList.push(ok);
		}
		
		$("#mainContent").find("button").each(function(i, item){
			if( $(item).is(":enabled") ){
				$(item).attr("saveChange", "changed").attr("disabled", true);
			}
		});
		$("#mainContent").find("a").each(function(i, item){
			var checked = $(this).attr("customizedDisabled");
			if( checked == "false" ){
				$(item).attr("saveChange", "changed").attr("customizedDisabled", true);
			} else if (checked == undefined){
				$(item).attr("saveChange", "changed").attr("customizedDisabled", true);
			}
		});
		self.buttonColorDisable();
		
		app.uiLoadingStatus.setIsLoading(true);
		
		$.when.apply(null, dtdList).fail(function(){
			$("a[name='faqCateSave']").attr("customizedDisabled", false);
			$("[saveChange='changed']").attr("disabled", false).attr("customizedDisabled", false);
			
			self.buttonColorDisable();
			app.uiLoadingStatus.setIsLoading(false);
		}).done(function(){
			var rest_requests = [];
			//add
			self.saveAdd(rest_requests);
			//update
			$("[status='update']").each(function(i,tr){
				var base = this;
				self.saveUpdate(i, tr, base, rest_requests);
			});
			//delete
			$("[status=delete]").each(function(i,tr){
				var base = this;
				self.saveDelete(i, tr, base, rest_requests);
			});
//			if($("tr[status='upDown']").length){
//				var upDownList = {"_method":"PUT"};
//				$("tr[step]").each(function(i,tr){
//					var base = this;
//					self.setUpUpdownList(i, tr, upDownList, base);
//				});			
//				
//				self.saveUpDown(upDownList, rest_requests);
//			}
			
			//upDown
			$("[hasUpDown='true']").each(function(i,d){
				var upDownList = {"_method":"PUT"};
				$(d).find("[step]").each(function(j,tr){
					var base = this;
					self.setUpUpdownList(j, tr, upDownList, base);
				});
				self.saveUpDown(upDownList, rest_requests);
			});
			
			
			
			//submit
			$.when.apply(null,rest_requests)
				.fail(function(){
					$("button[name='faqCateSave']").attr("disabled", false);
					$("[saveChange='changed']").attr("disabled", false).attr("customizedDisabled", false);
					self.buttonColorDisable();
					$("#loadingDiv").empty().remove();
					app.uiLoadingStatus.setIsLoading(false);
				}).done(showSaveResult).done(function(){
					managerFaqCate.data = null;
					if(rest_requests.length == 1){
						//alert(arguments[0].data.data);
					} else {
						for(var i=0;i<arguments.length;i++){
							//alert(arguments[i][0].data.data);
						}
					}
					self.emptyCache();
					managerFaqCate.trigger("load");
					$("#loadingDiv").empty().remove();
					app.uiLoadingStatus.setIsLoading(false);
			});
		}); 
		
	});	
};

managerFaqCate.emptyCache = function(){
	this["enData"] =  null;
	this["zh_CNData"] =  null;
	this["zh_TWData"] =  null;
};

/**
 * bind event of buttons. manageQuestion button
 */
managerFaqCate.initManageQuestionEvent = function(){
	var self = this;
	//$("button[name='manageQuestion']").die();
	$("div[name='manageQuestion']").die().live("click",function(){
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var cateId = $(this).parent("td").parent("tr").find("input[name='cateId']").val();
		var cate = self.findById(cateId);
		//managerFaq.trigger("load",cate);
		
		app.trigger("load", "admin/managerFaq", cate, self.currentLanguage);
	});
}