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

/**
 * When this js have been loaded , put this object into app cache
 */ 
app.registerComponent(managerLink);


managerLink.on("load", function() {
	var self = this;
	self.editMode = false;
//	if (getCookie("language_lang") == null) {
//		setCookie("language_lang", "en", 10000);
//	}
	var language = "en",
		linkType = app.user.role.checkAdminRole(),
		typeMapping = {
			"both" : ["admin1-en", "admin1-zh_CN", "admin1-zh_TW", "admin2-en", "admin2-zh_CN", "admin2-zh_TW"],
			"admin1" : ["admin1-en", "admin1-zh_CN", "admin1-zh_TW"],
			"admin2" : ["admin2-en", "admin2-zh_CN", "admin2-zh_TW"]
		},
		divHtml = "";
	
	var divArray = typeMapping[linkType];
	
	self.divArray = divArray;
	
	for( var i = 0; i < divArray.length; i++ ) {
		divHtml += "<div id='"+divArray[i]+"' style='display:none'></div>"
	}
	this.showLoading("mainContent");
	$("#mainContent").append(divHtml);
	var dtdList = [];
	for( var i = 0; i < divArray.length; i++ ) {
		var temps = divArray[i].split("-");
		dtdList.push(self.render(
				"template/admin/managerLink.html",
				divArray[i],
				"quickAccessLink/"+temps[0]+"/list/"+temps[1]
		));
	}
	
	return $.when.apply(null, dtdList).done(function(){
	    $("#loadingDiv").empty().remove();
		$("#" + divArray[0]).show();
		var temps = divArray[0].split("-");
		self.currentType = temps[0];
		self.currentLanguage = temps[1];
		self.controlTypeButton();
		self.initSelectLanguage(temps[1]);
		$("a[name='linkSave']").attr("customizedDisabled", true);
		//cacheData
		for (var i=0; i < arguments.length; i++) {
			self[self.divArray[i]] = arguments[i][1];
		}
		self.initAddEvent();
		self.initSaveEvent();
		self.initUpdateEvent();
		self.initDeleteEvent();
		self.initUpDownEvent();
		self.buttonColorDisable();
	});
	
});

managerLink.on("changeStatus", function(type,language){
	this.initialTemplate();
	this.currentType = type || this.currentType ;
	this.currentLanguage = language || this.currentLanguage;
	
	for( var i = 0; i < this.divArray.length; i++ ) {
		$("#" + this.divArray[i]).hide();
	}
	//alert(this.currentType + "-" + this.currentLanguage);
	$("#" + this.currentType + "-" + this.currentLanguage).show();
	this.controlTypeButton();
	this.initSelectLanguage(this.currentLanguage);
});

managerLink.initialTemplate = function(){
	$("button[name='linkListadmin2']").attr("style","background:#737173");
	$("button[name='linkListadmin1']").attr("style","background:#737173");
	$("button[name='linkEng']").attr("style","background:#737173");
	$("button[name='linkZh-CN']").attr("style","background:#737173");
	$("button[name='linkZh-HK']").attr("style","background:#737173");
	
};

managerLink.controlTypeButton = function(){
	var self = this;
	if( !(app.user.role.checkAdminRole() == "both") && app.user.role.isAdmin1()) {
		$("button[name='linkListadmin2']").attr("disabled", true);
	} else if(!(app.user.role.checkAdminRole() == "both") && app.user.role.isAdmin2()){
		$("button[name='linkListadmin1']").attr("disabled", true);
	}
	
	$("button[name='linkList" + this.currentType + "']").attr("style", "");
	
	$("button[name='linkListadmin2']").die().live("click", function(){
		if(self.editMode===false)
			self.trigger("changeStatus", "admin2", null);
	});
	$("button[name='linkListadmin1']").die().live("click", function(){
		if(self.editMode===false)
			self.trigger("changeStatus", "admin1", null);
	});
};

managerLink.initSelectLanguage = function(language) {
//	if (getCookie("language_lang") == null) {
//		setCookie("language_lang", "en", 10000);
//	}
	
	var inputNames = {
			"en" : "linkEng",
			"zh_CN" : "linkZh-CN",
			"zh_TW" : "linkZh-HK"
	};
	var lang = language || "en";
	$("button[name='" + inputNames[lang] + "']").attr("style", "");
	for (lang in inputNames) {
		managerLink.setLanguageEvent(lang, inputNames[lang]);
	}
	
};
/**
 * The three button which are named "Eng","繁" and "简" bind event.
 */
managerLink.setLanguageEvent = function (lang, inputName) {
	var self=this;
	$("button[name='" + inputName + "']").die().live("click", function() {
		if(self.editMode===false)
			managerLink.trigger("changeStatus", null, lang);
	});
};

/**
 * find one QLink object from managerLink cache by linkId
 */
managerLink.findById = function(linkId){
	var array = this[this.currentType + "-" + this.currentLanguage].data.data;
	for(var i=0;i<array.length;i++){
		if(array[i].linkId == linkId){
			return array[i];
		}
	}
	
};

//managerLink.enterChangToUpdateOrAddOrRemove = function() {
//	$("button[name='linkUp']").attr("disabled", true);
//	$("button[name='linkDown']").attr("disabled", true);
//	
//	$("button[name='linkEng']").attr("disabled", true);
//	$("button[name='linkZh-CN']").attr("disabled", true);
//	$("button[name='linkZh-HK']").attr("disabled", true);
//	
//	$("button[name='linkSave']").attr("disabled", false);
//};
//
//managerLink.enterChangeToUpOrDown = function() {
//	$("button[name='linkAdd']").attr("disabled", true);
//	$("button[name='linkEdit']").attr("disabled", true);
//	$("button[name='linkRemove']").attr("disabled", true);
//
//	$("button[name='linkEng']").attr("disabled", true);
//	$("button[name='linkZh-CN']").attr("disabled", true);
//	$("button[name='linkZh-HK']").attr("disabled", true);
//
//	$("button[name='linkSave']").attr("disabled", false);
//};
//
//managerLink.outOfUpdateOrAddOrRemove = function(){
//	$("button[name='linkSave']").attr("disabled", true);
//	
//	$("button[name='linkEng']").attr("disabled", false);
//	$("button[name='linkZh-CN']").attr("disabled", false);
//	$("button[name='linkZh-HK']").attr("disabled", false);
//	
//	$("button[name='linkUp']").attr("disabled", false);
//	$("button[name='linkDown']").attr("disabled", false);
//};
//
//managerLink.changeStatus = function(){
//	var status = $("tr[status='delete']").length + $("table[status='add']").length + $("tr[status='update']").length;
//	if(status == 0){
//		managerLink.outOfUpdateOrAddOrRemove();
//	} else {
//		managerLink.enterChangToUpdateOrAddOrRemove();
//	}
//};

/**
 * bind event of buttons. add button,cancel button of addTable
 */
managerLink.addVersion = 1;
managerLink.initAddEvent = function() {
	var self = this;
	$("a[name='linkAdd']").die().live("click", function() {	
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		$("a[name='linkAdd']").attr("customizedDisabled", true);
		var htmlTemplate = "<div id='addLinkTable" + self.addVersion + "' addVersion='" + self.addVersion + "'></div>";
		$("#" + self.currentType + "-" + self.currentLanguage + " div[name='addLinkTable']").append(htmlTemplate);
		self.adminUpdateOrDeleteMode(
				"link", 
				"add", 
				"template/admin/managerLinkAdd.html",
				{ version : self.addVersion },
				"",
				"addLinkTable" + self.addVersion
		).done(function(){
			$("#addLinkTable" + self.addVersion).attr("condition", self.currentType + "-" + self.currentLanguage);
			 self.addVersion++;
			 $("a[name='linkAdd']").attr("customizedDisabled", false);
			 self.buttonColorDisable();
		});
		
	});
	
	//$("button[name='linkCancelAddButton']").die();
	$("a[name='linkCancelAddButton']").die().live("click",function() {
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		//$("#" + self.currentType + "-" + self.currentLanguage+ " #addLinkTable").attr("status", "").empty();
		var version = $(this).siblings("input[name='version']").val();
		$("#addLinkTable" + version).remove();
		self.changeMode("link");
	});
};

/**
 * bind event of buttons. Edit button,cancel button of EditTr
 */
managerLink.initUpdateEvent = function() {
	var self = this;
	//$("button[name='linkEdit']").die();
	$("a[name='linkEdit']").die().live("click",function() {
//		self.enterChangToUpdateOrAddOrRemove();
//		// load update temp
//		var linkId = $(this).siblings("input[name='linkId']").val();
//		var data = self.findById(linkId);
//		self.render(
//				"template/admin/managerLinkUpdate.html",
//				"qlinkShow" + linkId, 
//				data
//		).done(function(){
//			// change form status
//			$("#qlinkShow" + linkId).attr("status", "update");
//		});
//		
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var linkId = $(this).siblings("input[name='linkId']").val();
		var data = self.findById(linkId);
		
		self.adminUpdateOrDeleteMode(
				"link", 
				"update", 
				"template/admin/managerLinkUpdate.html",
				data,
				linkId,
				self.currentType + "-" + self.currentLanguage+ " #qlinkShow"
		).done(function(){
			$("#" + self.currentType + "-" + self.currentLanguage+ " #qlinkShow" + linkId).attr("condition", self.currentType + "-" + self.currentLanguage);
		});
		
		
	});
	
	//$("button[name='linkUpdateCancel']").die();
	$("a[name='linkUpdateCancel']").die().live("click",function() {
//		var linkId = $(this).siblings("input[name='linkId']").val();
//        var data = self.findById(linkId);				
//		self.render(
//				"template/admin/managerLinkProtoType.html",
//				"qlinkShow" + linkId, 
//				data
//		);
//		// change form status
//		$("#qlinkShow" + linkId).attr("status", "");
//		self.changeStatus();
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		
		var linkId = $(this).siblings("input[name='linkId']").val();
		var data = self.findById(linkId);
		
		self.adminCancelMethod(
				"link", 
				"template/admin/managerLinkProtoType.html",
				data,
				linkId,
				self.currentType + "-" + self.currentLanguage+ " #qlinkShow"
		).done(function(){
			$("#" + self.currentType + "-" + self.currentLanguage+ " #qlinkShow" + linkId).attr("condition", self.currentType + "-" + self.currentLanguage);
		});
		
	});

};
/**
 * bind event of buttons. Delete button,cancel button of Delete Tr
 */
managerLink.initDeleteEvent = function() {
	var self = this;
	//$("button[name='linkRemove']").die();
	$("a[name='linkRemove']").die().live("click",function() {
//		self.enterChangToUpdateOrAddOrRemove();
//
//		var linkId = $(this).siblings("input[name='linkId']").val();
//		var data = self.findById(linkId);
//		$("#qlinkShow" + linkId).empty();
//		self.render(
//				"template/admin/managerLinkDelete.html",
//				"qlinkShow" + linkId, data);
//		// change form status
//		$("#qlinkShow" + linkId).attr("status", "delete");
		
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}		
		var linkId = $(this).siblings("input[name='linkId']").val();
		var data = self.findById(linkId);
		dialog.show(lang.getMessage('confirmDeleteItems'), lang.getMessage('confirm'), lang.getMessage('buttonCacel')).done(function(clickName){
			if(clickName == lang.getMessage('confirm')) {
				self.adminUpdateOrDeleteMode(
						"link", 
						"delete", 
						"template/admin/managerLinkDelete.html",
						data,
						linkId,
						self.currentType + "-" + self.currentLanguage+ " #qlinkShow"
				).done(function(){
					$("#" + self.currentType + "-" + self.currentLanguage+ " #qlinkShow" + linkId).attr("condition", self.currentType + "-" + self.currentLanguage);
				});				
			}
			
			
		});
		
	});
	
	//$("button[name='linkDeleteCancel']").die();
	$("a[name='linkDeleteCancel']").die().live("click",function() {
//		var linkId = $(this).siblings("input[name='linkId']").val();
//		var data = managerLink.findById(linkId);
//		self.render(
//				"template/admin/managerLinkProtoType.html",
//				"qlinkShow" + linkId, data);
//		// change form status
//		$("#qlinkShow" + linkId).attr("status", "");
//		self.changeStatus();
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		var linkId = $(this).siblings("input[name='linkId']").val();
		var data = self.findById(linkId);
		
		self.adminCancelMethod(
				"link", 
				"template/admin/managerLinkProtoType.html",
				data,
				linkId,
				self.currentType + "-" + self.currentLanguage+ " #qlinkShow"
		).done(function(){
			$("#" + self.currentType + "-" + self.currentLanguage+ " #qlinkShow" + linkId).attr("condition", self.currentType + "-" + self.currentLanguage);
		});
		
	});

};
///**
// * @param step clicked tr's customized attribute
// * @param action   up or down
// */
//managerLink.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
 */
managerLink.initUpDownEvent = function() {
	var self = this;
	//$("button[name='linkUp']").die();
	$("a[name='linkUp']").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("link" , step, "up", self.currentType + "-" + self.currentLanguage);
	});
	
	//$("button[name='linkDown']").die();
	$("a[name='linkDown']").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 = $( "#" + self.currentType + "-" + self.currentLanguage + "tr[step]:last").attr("step");
		
		// if step = max it is in the top
		if (step == maxStep) {
			return;
		}

		$(this).parent("div").attr("isBackground", "true");
		self.upDownMethod("link", step, "down", self.currentType + "-" + self.currentLanguage);

	});
};

managerLink.saveDelete = function(f,tr,rest_requestList){
	var linkId = $(tr).find("input[name='linkId']").val();
	var rest_request = {
			url : app.EPRESTAPI_CONTEXT_ROOT + "quickAccessLink/" + linkId,
			data : {},
			type : "DELETE",
			dataType : "json"
	};
	rest_requestList.push(ajaxCall(rest_request));
};

managerLink.saveAdd = function(rest_requestList){
	var addRequestList = {};
	$("[status='add']").each(
			function(i, t) {
				var condition =  $(t).attr("condition");
				var title = $(t).find("#addTitleTxt").val();
				var url =  $(t).find("#addUrlTxt").val();
				var temps = condition.split("-");
				var type = temps[0];
				var language = temps[1];
				addRequestList["qlinks["+i+"].linkTitle"] = title;
				addRequestList["qlinks["+i+"].linkUrl"] = url;
				addRequestList["qlinks["+i+"].linkType"] = type;
				addRequestList["qlinks["+i+"].linkLang"] = language;
				addRequestList["qlinks["+i+"].linkSeq"] = -1;
			}
	);
		
	var rest_request = {
		url : app.EPRESTAPI_CONTEXT_ROOT + "quickAccessLink",
		data : addRequestList,
		type : "POST",
		dataType : "json"
	};
	rest_requestList.push(ajaxCall(rest_request));
};

managerLink.saveUpdate = function(f, tr ,rest_requestList){
	var title = $(tr).find("input[name*='linkTitle']").val(),
		url = $(tr).find("input[name*='linkUrl']").val(),
		linkId = $(tr).find("input[name*='linkId']").val(),
		data = this.findById(linkId);

	var rest_request = {
			url : app.EPRESTAPI_CONTEXT_ROOT+"quickAccessLink/" + linkId,
			data : {
				_method : "PUT",
				"linkTitle" : title,
				"linkUrl" : url,
				//backend will validate seq,title and url.so this field must be sent.
				"linkSeq" : data.linkSeq
			},
			type : "POST",
			dataType : "json"
	};
	rest_requestList.push(ajaxCall(rest_request));
};

managerLink.setUpQlinks = function(i,tr,qlinks){
	var linkId = $(tr).find("input[name*='linkId']").val();
	var seq = $(tr).attr("step");
	var linkSeq = parseInt(seq) + 1;
	var data = this.findById(linkId);
	qlinks["qlinks[" + i + "].linkId"] = linkId;
	qlinks["qlinks[" + i + "].linkSeq"] = linkSeq;
	
	//backend will validate seq,title and url.so this two field must be sent.
	qlinks["qlinks[" + i + "].linkUrl"] = data.linkUrl;
	qlinks["qlinks[" + i + "].linkTitle"] = data.linkTitle;
};

managerLink.saveUpDown = function(qlinks,rest_requestList){
	var rest_request = {
			url :app.EPRESTAPI_CONTEXT_ROOT + "quickAccessLink/reorder",
			data : qlinks,
			type : "POST",
			dataType : "json"
	};
	
	rest_requestList.push(ajaxCall(rest_request));
};

managerLink.initSaveEvent = function() {
	
	var self = this;
	$("a[name='linkSave']").die().live("click",function() {
		var disabledChecked = $(this).attr("customizedDisabled");
		if ( disabledChecked == "true") {
			return ;
		}
		$("a[name='linkSave']").attr("customizedDisabled", true);
		//validate
		var validator = new Validator(function(divId){
			var temps = divId.split("-");
			self.trigger("changeStatus", temps[0], temps[1]);
		});
		
		var dtdList = [];
		for( var i = 0; i < self.divArray.length; i++ )  {
			var ok = validator.validateDiv(self.divArray[i]);
			dtdList.push(ok);
//			if(!ok) {
//				$("button[name='linkSave']").attr("disabled", false);
//				return ;
//			}
		} 
		
		//$("#mainContent").find("button").attr("disabled", true);
		$("#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='linkSave']").attr("customizedDisabled", false);
			$("[saveChange='changed']").attr("disabled", false);
			$("[saveChange='changed']").attr("customizedDisabled", false);
			self.buttonColorDisable();
			app.uiLoadingStatus.setIsLoading(false);
		}).done(function(){
			var rest_requestList = [];
			// delete
			$("[status='delete']").each(
				function(f, tr) {
					self.saveDelete(f, tr, rest_requestList);
				}
			);
			
			// add
//			$("[status='add']").each(
//				function(i, t) {
//					self.saveAdd(i, t, rest_requestList);
//				}
//			);
			self.saveAdd(rest_requestList);
			
			// update
			$("[status='update']").each(
				function(f, tr) {
					self.saveUpdate(f, tr, rest_requestList);
				}
			);
			
			// updown
			$("[hasUpDown='true']").each(function(i,d){
				var qlinks = {_method:"PUT"};
				$(d).find("[step]").each(function(j,t){
					self.setUpQlinks(j, t, qlinks);
				});
				self.saveUpDown(qlinks, rest_requestList);
			});
			
//			if ($("[hasUpDown='true']").length) {
//				var qlinks = {_method:"PUT"};
//			    
//				$("[step]").each(
//						function(i, tr) {
//							self.setUpQlinks(i, tr, qlinks);		
//						}
//				);		
//				self.saveUpDown(qlinks, rest_requestList);
//			}
			
			$.when.apply(null, rest_requestList)
				.fail(function(){
					$("a[name='linkSave']").attr("customizedDisabled", false);
					$("[saveChange='changed']").attr("disabled", false);
					$("[saveChange='changed']").attr("customizedDisabled", false);
					self.buttonColorDisable();
					$("#loadingDiv").empty().remove();
					app.uiLoadingStatus.setIsLoading(false);
				}).done(showSaveResult).done(function(){
					if (rest_requestList.length == 1){
						
						//alert(arguments[0].data.data);
					} else {
						for(var i=0;i<arguments.length;i++){
						
							//alert(arguments[i][0].data.data);
						}
					}
					managerLink.trigger("load");
					$("#loadingDiv").empty().remove();
					app.trigger("load","quickAccessLink");
					app.uiLoadingStatus.setIsLoading(false);
				}
			);
		});
		
		
	});
};



//managerLink.on("close",function(){
//	var status = $("tr[status='delete']").length + $("table[status='add']").length + $("tr[status='update']").length+$("tr[status='upDown']").length;
//	if(status != 0){
//		return confirm("Are you sure to leave?");
//	} else{
//		return true;
//	}
//});

