/* managerFaq component, write logic of managerFaq module in this class */
var managerFaq = new adminComponent("admin/managerFaq");

app.registerComponent(managerFaq);



managerFaq.findByFaqId = function(id){
	var array = this.data.faqs;
	for(var i=0;i<array.length;i++){
		if(array[i].faqId == id){
			return array[i];
		}
	}
};

managerFaq.on("reloadFaq",function(){
	var self = this;
//	if (getCookie("language_lang") == null) {
//		setCookie("language_lang", "en", 10000);
//	}
//	var language = getCookie("language_lang") || "en";
//	var resultReturn = ajaxCall({url:app.EPRESTAPI_CONTEXT_ROOT+"faqCategory/language/"+language, dataType:"JSON"});
//	return resultReturn.done(function(data){
//		//update category
//		managerFaqCate.data = data;
//		var cateId = self.data.cateId;
//		var faq = managerFaqCate.findById(cateId);
//	});
	var resultReturn = ajaxCall({url:app.EPRESTAPI_CONTEXT_ROOT+"faqCategory/list/"+self.currentLanguage, dataType:"JSON"});
	return resultReturn.done(function(data){
		managerFaqCate[self.currentLanguage + "Data"] = data;
		var cateId = self.data.cateId;
		var faq = managerFaqCate.findById(cateId);
		managerFaq.trigger("load", faq, self.currentLanguage);
	});
});

managerFaq.on("load", function(cate, language) {
	var self = this,
		returnValue = this.render(
			"template/admin/managerFaq.html", 
			"mainContent",
			cate).done(function(template,data) {
				
				self.data = data;
				self.currentLanguage = language;
				$("a[name='faqSave']").attr("customizedDisabled",true);
				
				//init page
				self.initMoreOrCompress();
				self.initBackToCategoriesEvent();
				self.initAddEvent();
				self.initUpdateEvent();
				self.initDeleteEvent();
				self.initUpDownEvent();
				self.initSaveEvent();
				
//				$("#manageFaqForm").validate({
//					submitHandler : function() { 
//						return; 
//					}
//				});
				
				self.initLanguageButton(language);
				self.buttonColorDisable();
			});
	return returnValue;

});

managerFaq.showMultipleLine = function(data){
	return data.replace(/\n/g, "<br/>");
};

managerFaq.initLanguageButton = function(language){
	this.currentLanguage = language;
	$("button[name='faqzh_CN']").attr("disabled", true);
	$("button[name='faqzh_TW']").attr("disabled", true);
	$("button[name='faqen']").attr("disabled", true);
	$("button[name='faq"+ language +"']").attr("style", "").attr("disabled", false);
};

//managerFaq.enterChangToUpdateOrAddOrRemove = function() {
//	$("button[name='faqUp']").attr("disabled", true);
//	$("button[name='faqDown']").attr("disabled", true);
//	$("button[name='faqBackToCate']").attr("disabled",true);	
//	$("button[name='faqSave']").attr("disabled", false);
//};
//
//managerFaq.enterChangeToUpOrDown = function() {
//	$("button[name='faqAdd']").attr("disabled", true);
//	$("button[name='faqEdit']").attr("disabled", true);
//	$("button[name='faqRemove']").attr("disabled", true);
//	$("button[name='faqBackToCate']").attr("disabled",true);
//	$("button[name='faqSave']").attr("disabled", false);
//};
//
//managerFaq.outOfUpdateOrAddOrRemove = function(){
//	$("button[name='faqSave']").attr("disabled", true);
//	$("button[name='faqBackToCate']").attr("disabled",false);	
//	$("button[name='faqUp']").attr("disabled", false);
//	$("button[name='faqDown']").attr("disabled", false);
//};

//managerFaq.changeStatus = function(){
//	var status = $("div[status='delete']").length + $("div[status='add']").length + $("div[status='update']").length;
//	if(status==0){
//		this.outOfUpdateOrAddOrRemove();
//	} else {
//		this.enterChangToUpdateOrAddOrRemove();
//	}
//};

managerFaq.hideAnswer = function(d) {
	var len = (this.currentLanguage == "en")? 90 : 70;
	var answer = $(d).find("pre").html();
	//var height = $(d).find("pre")[0].clientHeight;
	var height = $(d).find("pre").height();
	if (height >= 45) {
		var temp = answer.substring(0, len);
		$(d).find("pre").html(temp + " ...");
		$(d).addClass("hiddenAnswer");
	} else {
		$(d).siblings("a[name='faqMoreButton']").remove();
	}
};
/**
 * bind event of buttons. more or compress button
 */
managerFaq.initMoreOrCompress = function(){
	var self = this;
	$("div[name='managerFaqAnswer']").each(function(i,d){
		self.hideAnswer(d);			
	});
	
	//$("a[name='faqMoreButton']").die();
	$("a[name='faqMoreButton']").die().live("click",function(){
		if($(this).hasClass("More")){			
			var faqId = $(this).siblings("input[name='faqId']").val();
			var faq = self.findByFaqId(faqId);
			$(this).siblings("div[name='managerFaqAnswer']").removeClass("hiddenAnswer");
			$(this).removeClass("More");
			$(this).addClass("Compress");
			$(this).html(lang.getMessage("compress"));
			$(this).attr('msgid',"compress");
			$(this).siblings("div[name='managerFaqAnswer']").find("pre").empty();
			$(this).siblings("div[name='managerFaqAnswer']").find("pre").html(lang.getMessage('a')+": " + faq.faqAnswer.replace(/\n/g, "<br/>"));
		} else {
			$(this).removeClass("Compress");
			$(this).addClass("More");
			$(this).html(lang.getMessage('publicMore'));
			$(this).attr('msgid',"publicMore");
			$(this).siblings("div[name='managerFaqAnswer']").addClass("hiddenAnswer");
			self.hideAnswer($(this).siblings("div[name='managerFaqAnswer']"), 160);	
		}
	});
};

/**
 * bind event of buttons. backToCategory button
 */
managerFaq.initBackToCategoriesEvent = function(){
	//$("button[name='faqBackToCate']").die();
	$("a[name='faqBackToCate']").die().live("click", function(){
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		managerFaqCate.trigger("load");
	});
};
/**
 * bind event of buttons. add button,cancel button of addTable
 */
managerFaq.addVersion = 1;
managerFaq.initAddEvent = function(){
	var self = this;
	//$("button[name='faqAdd']").die();
	$("a[name='faqAdd']").die().live("click",function(){
//		self.render(
//			"template/admin/managerFaqAdd.html",
//			"addFaqDiv",
//			{}
//		).done(function(template,data) {
//			self.enterChangToUpdateOrAddOrRemove(); 
//			$("button[name='faqAdd']").attr("disabled",true);
//			$("div[remark='addDiv']").attr("status", "add");
//		});
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		$("a[name='faqAdd']").attr("customizedDisabled", true);
		//self.buttonColorDisable();
		var htmlTemplate = "<div id='addFaqDiv" + self.addVersion + "' addVersion='" + self.addVersion + "'></div>";
		$("#addFaqDiv").append(htmlTemplate);
		self.adminUpdateOrDeleteMode(
				"faq", 
				"add", 
				"template/admin/managerFaqAdd.html",
				{ version : self.addVersion, faqCateLang : self.currentLanguage  },
				"",
				"addFaqDiv" + self.addVersion
		).done(function(){
			self.addVersion++;
			$("a[name='faqAdd']").attr("customizedDisabled", false);
			self.buttonColorDisable();
		});
		
		
	});
	
	//$("button[name='faqAddCancelButton']").die();
	$("a[name='faqAddCancelButton']").die().live("click",function(){
//		self.enterChangToUpdateOrAddOrRemove(); 
//		$("div[remark='addDiv']").attr("status", "");
//		$("button[name='faqAdd']").attr("disabled",false);
//		$("#addFaqDiv").empty();
//		self.changeStatus();
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var version = $(this).siblings("input[name='version']").val();
		$("#addFaqDiv" + version).remove();
		self.changeMode("faq");
	});
};
/**
 * bind event of buttons. Edit button,cancel button of EditTr
 */
managerFaq.initUpdateEvent = function(){
	var self = this;
	//$("button[name='faqEdit']").die();
	$("a[name='faqEdit']").die().live("click",function(){
//		self.render(
//				"template/admin/managerFaqUpdate.html", 
//				"faqDivShow"+faqId, 
//				faq
//		).done(function(template,data){
//			self.enterChangToUpdateOrAddOrRemove(); 
//			$("#faqDivShow"+faqId).attr("status","update");
//		});
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var faqId = $(this).siblings("input[name='faqId']").val();
		var faq = self.findByFaqId(faqId);
		self.adminUpdateOrDeleteMode(
				"faq", 
				"update", 
				"template/admin/managerFaqUpdate.html",
				$.extend(faq,{faqCateLang : self.currentLanguage}),
				faqId,
				"faqDivShow"
		).done(function(){
			//$("textarea[name='faqAnswer" + faqId + "']").val( faq.faqAnswer );
		});
		
	});
	
	//$("button[name='faqUpdateCancelButton']").die();
		$("a[name='faqUpdateCancelButton']").die().live("click",function(){
//		self.render(
//				"template/admin/managerFaqPrototype.html",
//				"faqDivShow"+faqId,
//				faq
//		).done(function(template,data){
//			self.enterChangToUpdateOrAddOrRemove(); 
//			$("#faqDivShow"+faqId).attr("status","");
//			self.hideAnswer($("#faqDivShow"+faqId).find("div[name='managerFaqAnswer']"));	
//			self.changeStatus();
//		});
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var faqId = $(this).siblings("input[name='faqId']").val();
		var faq = self.findByFaqId(faqId);
		
		self.adminCancelMethod(
				"faq", 
				"template/admin/managerFaqPrototype.html",
				faq,
				faqId,
				"faqDivShow"
		).done(function(){
			self.hideAnswer($("#faqDivShow"+faqId).find("div[name='managerFaqAnswer']"));	
		});
				
	});
};
/**
 * bind event of buttons. Delete button,cancel button of Delete Tr
 */
managerFaq.initDeleteEvent = function(){
	var self = this;
	//$("button[name='faqRemove']").die();
	$("a[name='faqRemove']").die().live("click",function(){
//		self.render(
//				"template/admin/managerFaqDelete.html",
//				"faqDivShow"+faqId,
//				faq
//		).done(function(template,data){
//			self.enterChangToUpdateOrAddOrRemove(); 
//			$("#faqDivShow"+faqId).attr("status","delete");
//		});
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		
		var faqId = $(this).siblings("input[name='faqId']").val();
		var faq = self.findByFaqId(faqId);
		dialog.show(lang.getMessage('confirmDeleteItems'), lang.getMessage('confirm'), lang.getMessage('buttonCacel')).done(function(clickName){
			if(clickName == lang.getMessage('confirm')){
				self.adminUpdateOrDeleteMode(
						"faq", 
						"delete", 
						"template/admin/managerFaqDelete.html",
						faq,
						faqId,
						"faqDivShow"
				);				
			}
		});
	});
	
	//$("button[name='faqDeleteCancelButton']").die();
	$("a[name='faqDeleteCancelButton']").die().live("click",function(){
//		self.render(
//				"template/admin/managerFaqPrototype.html",
//				"faqDivShow"+faqId,
//				faq
//		).done(function(template,data){
//			self.enterChangToUpdateOrAddOrRemove(); 
//			$("#faqDivShow"+faqId).attr("status","");
//			self.hideAnswer($("#faqDivShow"+faqId).find("div[name='managerFaqAnswer']"));
//			self.changeStatus();
//		});
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var faqId = $(this).siblings("input[name='faqId']").val();
		var faq = self.findByFaqId(faqId);
		self.adminCancelMethod(
				"faq", 
				"template/admin/managerFaqPrototype.html",
				faq,
				faqId,
				"faqDivShow"
		).done(function(){
			self.hideAnswer($("#faqDivShow"+faqId).find("div[name='managerFaqAnswer']"));	
		});
		
	});
};
/**
 * @param step clicked tr's customized attribute
 * @param action   up or down
 */
//managerFaq.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 = $("div[step=" + step + "]").html();
//
//	var targetHtml = $("div[step=" + targetStep + "]").html();
//
//	$("div[step=" + targetStep + "]").empty();
//	$("div[step=" + targetStep + "]").append(sourceHtml);
//
//	if ($("div[step=" + targetStep + "]").find("div[background='true']").length) {
//		$("div[step=" + targetStep + "]").css({
//			"background" : "yellow"
//		});
//	} else {
//		$("tr[step=" + targetStep + "]").css({
//			"background" : ""
//		});
//	}
//
//	$("div[step=" + step + "]").empty();
//	$("div[step=" + step + "]").append(targetHtml);
//
//	if ($("div[step=" + step + "]").find("div[background='true']").length) {
//		$("div[step=" + step + "]").css({
//			"background" : "yellow"
//		});
//	} else {
//		$("div[step=" + step + "]").css({
//			"background" : ""
//		});
//	}
//};
/**
 * bind event of buttons. up or down button, cancel button of up or down button
 */
managerFaq.initUpDownEvent = function(){
	var self = this;
	//$("button[name='faqUp']").die();
	$("a[name='faqUp']").die().live("click",function(){
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		$(this).parent("div").parent("div").parent(".AdminContentText").attr("status", "upDown");
		var step = $(this).parent("div").parent("div").parent(".AdminContentText").attr("step");
		// if step = 0 it is in the top
		if (step == 0) {
			return;
		}
		$(this).parent("div").attr("isBackground", "true");
		self.upDownMethod("faq" , step, "up", "adminMain");
	});
	
	//$("button[name='faqDown']").die();
	$("a[name='faqDown']").die().live("click",function(){
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		$(this).parent("div").parent("div").parent(".AdminContentText").attr("status", "upDown");
		var step = $(this).parent("div").parent("div").parent(".AdminContentText").attr("step");

		var maxStep = $("div[step]:last").attr("step");
		// if step = max it is in the top
		if (step == maxStep) {
			return;
		}

		$(this).parent("div").attr("isBackground", "true");
		self.upDownMethod("faq" , step, "down", "adminMain");
	});
};

managerFaq.saveAdd = function(rest_requests){
	var addRequestList = {},
		self = this;
	$("div[status='add']").each(function(i,d){
		var question = $(d).find("input[name='faqQuestion']").val();
		var answer = $(d).find("textarea[name='faqAnswer']").val();
		addRequestList["faqs["+ i +"].faqQuestion"] = question;
		addRequestList["faqs["+ i +"].faqAnswer"] = answer;
		addRequestList["faqs["+ i +"].cateId"] = self.data.cateId;
		//In backend, the validator will validate faqQuestion,FaqAnswer,FaqSeq.
		//so this field must be sent a dummy variable;
		addRequestList["faqs["+ i +"].faqSeq"] = -1;
		
	});
	var rest_request = {
			url:app.EPRESTAPI_CONTEXT_ROOT+"faq",
			type:"POST",
			dataType:"JSON",
			data: addRequestList
	};
	rest_requests.push(ajaxCall(rest_request));
};

managerFaq.saveUpdate = function(i,d,rest_requests){
	var question = $(d).find("input[name*='faqQuestion']").val();
	var answer = $(d).find("textarea[name*='faqAnswer']").val();
	var faqId = $(d).find("input[name='faqId']").val();
	data = this.findByFaqId(faqId);
	var rest_request = {
			url : app.EPRESTAPI_CONTEXT_ROOT + "faq/" + faqId,
			type : "POST",
			dataType : "JSON",
			data : {
				"_method" : "PUT",
				"faqQuestion" : question,
				"faqAnswer" : answer,
				"cateId" : this.data.cateId,
				//In backend, the validator will validate faqQuestion,FaqAnswer,FaqSeq.
				//so this two field must be sent;
				"faqSeq" : data.faqSeq
			}
	};
	rest_requests.push(ajaxCall(rest_request));
};

managerFaq.saveDelete = function(i,d,rest_requests){
	var faqId = $(d).find("input[name='faqId']").val();
	var rest_request = {
			url:app.EPRESTAPI_CONTEXT_ROOT+"faq/"+faqId,
			type:"DELETE",
			dataType:"JSON"
	};
	rest_requests.push(ajaxCall(rest_request));
};


managerFaq.setUpUpdownList = function(i, d,upDownList){
	var faqId = $(d).find("input[name='faqId']").val(),
	    step = $(d).attr("step"),
		data = this.findByFaqId(faqId);
	upDownList["faqs["+i+"].faqId"] = faqId;
	upDownList["faqs["+i+"].faqSeq"] = step;
	//In backend, the validator will validate faqQuestion,FaqAnswer,FaqSeq.
	//so this two field must be sent;
	upDownList["faqs["+i+"].faqQuestion"] = data.faqQuestion;
	upDownList["faqs["+i+"].faqAnswer"] = data.faqAnswer;
};

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

managerFaq.initSaveEvent = function(){
	var self = this;

	$("a[name='faqSave']").die().live("click",function(){
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		$("a[name='faqSave']").attr("customizedDisabled", true);
//		if(!$("#manageFaqForm").valid()) {
//			app.langChanged();
//			return;
//		}
		var validator = new Validator();
		
		var ok = validator.validateDiv("adminMain");
		
		$("#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);
		
		ok.fail(function(){
			$("button[name='faqSave']").attr("disabled", 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
			$("div[status='update']").each(function(i,d){
				self.saveUpdate(i, d, rest_requests);
			});
			//delete
			$("div[status='delete']").each(function(i,d){
				self.saveDelete(i, d, rest_requests);
			});
			//upDown
			if($("div[status='upDown']").length){
				var upDownList = {"_method":"PUT"};
				$("div[step]").each(function(i,d){
					self.setUpUpdownList(i, d, upDownList);
				});
				self.saveUpdown(upDownList,rest_requests);
			}
			
			//submit
			$.when.apply(null,rest_requests)
				.fail(function(){
					$("button[name='faqSave']").attr("disabled", false);
					$("[saveChange='changed']").attr("disabled", false).attr("customizedDisabled", false);
					self.buttonColorDisable();
					app.uiLoadingStatus.setIsLoading(false);
				}).done(showSaveResult).done(function(){
					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.trigger("reloadFaq");
					app.uiLoadingStatus.setIsLoading(false);
					
			});
		});
		
		
	});
};