var managerAnnouncement = new Component("admin/managerAnnouncement");
app.registerComponent(managerAnnouncement);

managerAnnouncement.currentLanguage = "en";
managerAnnouncement.announceType = "ADMIN1";
managerAnnouncement.pageNo = 1;

managerAnnouncement.isSaving = false;
managerAnnouncement.isClearFiles = true;

var inputNames = {
        "en" : "linkEng",
        "zh_CN" : "linkZh-CN",
        "zh_TW" : "linkZh-HK"
  };
var skipLang = {
        "en" : "EN",
        "zh_CN" : "SC",
        "zh_TW" : "TC"
  };

/**
 * init event when page is loaded.
 */
managerAnnouncement.on( "load", function(currentLang,type,pageNo){
    managerAnnouncement.announceType = type;
    managerAnnouncement.pageNo = pageNo;
    managerAnnouncement.buttonEvent();
    return managerAnnouncement.initSelectLanguage(currentLang);    
});
managerAnnouncement.divs = [
            {erlang:"zh_CN",div:"div_lang-zh_CN",link:"linkZh-CN",skipid:"skip_SC"},
            {erlang:"zh_TW",div:"div_lang-zh_TW",link:"linkZh-HK",skipid:"skip_TC"},
            {erlang:"en",div:"div_lang-en",link:"linkEng",skipid:"skip_EN"}
];

managerAnnouncement.autocompleteIds = {
        "en":"announceCatEN",
        "zh_CN":"announceCatSC",
        "zh_TW":"announceCatTC"
};


managerAnnouncement.autoCompleteCategory = function(erlang,data){
    var autocompleteData =data.data.data;
    var langId = managerAnnouncement.autocompleteIds[erlang];
    $("#" + langId).autocomplete({       
        source: autocompleteData,
        minLength : 0,        
        select : function(){
            $this = $(this);
            setTimeout(function(){
                $this.blur();
            },1);
        }        
    }).focus(function(){
        $(this).autocomplete("search");
        return false;
    });
};

managerAnnouncement.showFileListByLang = function(language){  
    var displayMode = [];
    $("#fileListTable tr").each(function(){
        displayMode = this.lang == language ? ["","none"]:["none",""];      
        $(this).css({ "display" : displayMode[0] });       
    });
    var operationMode = $("#operationMode").val();
    if (operationMode == "edit"){
        $("#alreadyUploadFile tr").each(function(){
            if (this.lang != "all"){
                displayMode = this.lang == language ? ["","none"]:["none",""];      
                $(this).css({ "display" : displayMode[0] }); 
            }
        });
    }
};

managerAnnouncement.filterCategory = function(language ,data){
	var ary = data.data.data,
		hasGeneral = false,
		mapping = {
			"ADMIN1-en" : "General",
			"ADMIN1-zh_CN" : "一般",
			"ADMIN1-zh_TW" : "一般",
			"ADMIN2-en" : "Market Insights",
			"ADMIN2-zh_CN" : "市场透视",
			"ADMIN2-zh_TW" : "市場透視"
				
		},
		languageMapping = ["en", "zh_CN", "zh_TW"];
	if (this.announceType == "ADMIN1"){
		for (var i = ary.length; i >= 0; i--){
			if(ary[i] == mapping[this.announceType + "-" + language] ) {
				hasGeneral = true;
			}
			for (var j=0; j<languageMapping.length; j++){
				if (ary[i] == mapping[ "ADMIN2" + "-" + languageMapping[j]]) {
					ary.splice(i , 1);
				}				
			};
		}
		if (!hasGeneral) {
			ary.push( mapping[this.announceType + "-" + language] );
		}
		data.data.data = ary;
	} else if (this.announceType == "ADMIN2") {
		data.data.data = [ mapping[this.announceType + "-" + language] ];
	}
	return data;
	
};

managerAnnouncement.displayDiv = function(language){    
    
    var rest_request = {
            url : app.EPRESTAPI_CONTEXT_ROOT + "announcement/category/" + language,
            data : {},
            type : "GET",
            dataType : "json"
        };
    var result =  ajaxCall(rest_request); 
    result.done(
            function(data){
            	if (data.data.language !== managerAnnouncement.currentLanguage){
            		//async load category list, so the return list maybe not current language if user quickly switch language
            		return;
            	}
            	data = managerAnnouncement.filterCategory(language,data);
            	if (managerAnnouncement.announceType == "ADMIN2") {
            	    return ;
            	}
                managerAnnouncement.autoCompleteCategory(language,data);                
            }
    ); 
    
    var skipId = "#skip_" + skipLang[language] ;
    var isCheck = $(skipId).attr("checked");
    if (isCheck){
        $("#files").attr("disabled" , true) ;  
    }
    else{
        $("#files").attr("disabled" , false) ;
    }
    managerAnnouncement.skipButtonChangeStatus(isCheck);
    
    setCookie("language_lang", language, 10000);
    managerAnnouncement.currentLanguage = language ;
    for (var i = 0;i < managerAnnouncement.divs.length; i++){        
        if (language == managerAnnouncement.divs[i].erlang){
            $("button[name='" + managerAnnouncement.divs[i].link + "']").css({ "background-color" : "#C00" });
            $("#" + managerAnnouncement.divs[i].div).css({ "display" : "block" });
        }
        else{
            $("button[name='" + managerAnnouncement.divs[i].link + "']").css({ "background-color" : "#737173" });
            $("#" + managerAnnouncement.divs[i].div).css({ "display" : "none" });
        }       
    }
    managerAnnouncement.showFileListByLang(language);    
    
};


managerAnnouncement.initSelectLanguage = function(erlang) {   
    managerAnnouncement.displayDiv(erlang);    
};

managerAnnouncement.changeButtonStatus = function(flag) { 
    btnArray = ["addAttachment","addUpdateCancel","newSaveBtn","cancelUploadFileBtn","deleteAttachment","cancelDeleteAttachment"];
    btnArray.forEach(function(btnName){
        //$("a[name='" + btnName +"']").attr("disabled", flag);
        if (flag) {
            $("[name='" + btnName + "']").each(function(){            
                $(this).removeClass("redDivButton").addClass("greyDivButton") ;
            }); 
            
            ["linkEng","linkZh-HK","linkZh-CN"].forEach(function(btnName){
                $("button[name='" + btnName + "']").attr("disabled", true); 
                $("button[name='" + btnName + "']").css({"background-color":"#CCC"}) ;                
            });           
        }
        else{
            $("[name='" + btnName + "']").each(function(){            
                $(this).removeClass("greyDivButton").addClass("redDivButton") ;
            }); 
            ["en","zh_CN","zh_TW"].forEach(function(lang){
                $("button[name='" + inputNames[lang] + "']").attr("disabled", false);
                background = managerAnnouncement.currentLanguage == lang ? ["#C00"]:["#737173"];       
                $("button[name='" + inputNames[lang] + "']").css({ "background-color" : background[0] }); 
            });           
        }
    });
    
};

managerAnnouncement.clearSkipFileUpload = function() {
    managerAnnouncement.isClearFiles = false;
    $("#fileListTable tr").each(function(){
        var skipid = "#skip_" + skipLang[this.lang] ;
        var isCheck = $(skipid).attr("checked");
        if (isCheck){
            var cancelButton = $(this).find('.button').get(0);
            var fileName = $(this).find("td").eq(1).text();
            var fileSize = $(this).find("td").eq(2).text();
            cancelUpload(cancelButton , $.trim(fileName) + $.trim(fileSize)) ;
        }
    });
    managerAnnouncement.isClearFiles = true;
};

managerAnnouncement.getAllFileOfLanguage = function() {
    var sb = new StringBuffer();
    $("#fileListTable tr").each(function(){
        var skipid = "#skip_" + skipLang[this.lang] ;
        var isCheck = $(skipid).attr("checked");
        if ( !isCheck ){
            var fileName = $(this).find("td").eq(1).text();
            var fileSize = $(this).find("td").eq(2).text();
            sb.append('{"fileKey":');
            sb.append('"' + $.trim(fileName) + "_#_" + $.trim(fileSize) + '"');
            sb.append(',');
            sb.append('"lang":');       
            sb.append('"' + this.lang + '"');
            sb.append('},'); 
        }
    });
    
    var uploadFilesStr = sb.toString();
    return '{"fileLangs":' + '[' + uploadFilesStr.substring(0,uploadFilesStr.length-1) + ']}';    
};

managerAnnouncement.validateFileUpload = function(operationMode){
    var flag = true;
    var langs = ["en","zh_CN","zh_TW"];
    for(var i = 0;i < langs.length; i++){
        var skipid = "#skip_" + skipLang[langs[i]] ;
        var isCheck = $(skipid).attr("checked");
        if ( !isCheck ){
            var filesNum = $("#fileListTable tr[lang='" + langs[i] + "']").length;
            var alereadyUploadFilesNum = 0;
            if (operationMode == "edit"){
                alereadyUploadFilesNum = $("#alreadyUploadFile tr[status='normal']&&[lang='" + langs[i] + "']").length;
            }
            totalFileNum = filesNum + alereadyUploadFilesNum;
            if (totalFileNum > 5){
                managerAnnouncement.displayDiv(langs[i]);
                //alert('exceed five files');
                dialog.show(lang.getMessage("msgExceedMaxFileCount"), "Ok");  
                flag = false; 
                break;            
            }
        }
    }    
    return flag;
};

managerAnnouncement.checkInputLang = function(checkbox){
    //announceCatEN,announceTitleEN,announceContentEN
    var pLang = checkbox.lang ;
    var isCheck = $(checkbox).attr("checked");
    if (isCheck){        
       $("#announceCat" + pLang).css({"background-color":"#ccc"}).attr("disabled","true");
       $("#announceTitle" + pLang).css({"background-color":"#ccc"}).attr("disabled","true");   
       $("#announceContent" + pLang).css({"background-color":"#ccc"}).attr("disabled","true"); 
       $("#files").attr("disabled" , true) ; 
       
       if($("#announceCat" + pLang).siblings("[validationError]").length != 0 ){
           $("#announceCat" + pLang).siblings("[validationError]").remove();                         
       }
       if($("#announceTitle" + pLang).siblings("[validationError]").length != 0 ){
           $("#announceTitle" + pLang).siblings("[validationError]").remove();                         
       }
       if($("#announceContent" + pLang).siblings("[validationError]").length != 0 ){
           $("#announceContent" + pLang).siblings("[validationError]").remove();                         
       }       
    }
    else{
        $("#announceCat" + pLang).css({"background-color":"#fff"}).removeAttr("disabled");
        $("#announceTitle" + pLang).css({"background-color":"#fff"}).removeAttr("disabled");   
        $("#announceContent" + pLang).css({"background-color":"#fff"}).removeAttr("disabled");  
        $("#files").attr("disabled" , false) ;  
    } 
    managerAnnouncement.skipButtonChangeStatus(isCheck);
};


managerAnnouncement.skipButtonChangeStatus = function(flag){
    btnArray = ["addAttachment","cancelUploadFileBtn","deleteAttachment","cancelDeleteAttachment"];
    btnArray.forEach(function(btnName){       
        if (flag) {
            $("[name='" + btnName + "']").each(function(){            
                $(this).removeClass("redDivButton").addClass("greyDivButton") ;
            }); 
        }
        else{
            $("[name='" + btnName + "']").each(function(){            
                $(this).removeClass("greyDivButton").addClass("redDivButton") ;
            });                  
        }
    });
};


managerAnnouncement.validSelectLanguage = function(){
    var flag = false ;
    ["EN","SC","TC"].forEach(function(pLang){
        var isCheck = $("#skip_" + pLang).attr("checked");
        if (!isCheck){
            flag = true;
        }
    });
    return flag ;    
};

managerAnnouncement.skipButtonEvent = function(){    
    var isCheck = $("#skip_" + skipLang[managerAnnouncement.currentLanguage]).attr("checked");
    return isCheck ;
};

managerAnnouncement.checkEnglishContent = function(){    
    var enCheckList = ["announceCatEN","announceTitleEN","announceContentEN"];
    var flag = true ;
    for(var k=0;k<enCheckList.length;k++){
        flag = checkEnglistContent( $("#" + enCheckList[k]).val() );
        if (!flag){
            break;
        }
    }
    return flag ;
};

managerAnnouncement.processSaveAnnounce = function(){
    var operationMode = $("#operationMode").val(),
    isActive = $("#announceStaus").attr("checked"),
    status = isActive ? "A":"O";  
    
    var cnumber = getCookie("cnumber");
    var requestUrl = app.EPRESTAPI_CONTEXT_ROOT + "announcement";        
    var requestData = {
           announceTitleEN:$("#skip_EN").attr("checked") ? "" : $("#announceTitleEN").val(),
           announceContentEN:$("#skip_EN").attr("checked") ? "" : $("#announceContentEN").val(),
           announceTitleSC:$("#skip_SC").attr("checked") ? "" : $("#announceTitleSC").val(),
           announceContentSC:$("#skip_SC").attr("checked") ? "" : $("#announceContentSC").val(),
           announceTitleTC:$("#skip_TC").attr("checked") ? "" : $("#announceTitleTC").val(),
           announceContentTC:$("#skip_TC").attr("checked") ? "" : $("#announceContentTC").val(),
           announceCatSC:$("#skip_SC").attr("checked") ? "" : $("#announceCatSC").val(),
           announceCatEN:$("#skip_EN").attr("checked") ? "" : $("#announceCatEN").val(),
           announceCatTC:$("#skip_TC").attr("checked") ? "" : $("#announceCatTC").val(),
           announceStaus:status,
           announceType:managerAnnouncement.announceType
    };
    
    //clear up skip files.
    managerAnnouncement.clearSkipFileUpload();
    
    if (operationMode == "edit"){
        var announceId = $("#announcementId").val();            
        requestUrl = requestUrl+ "/edit/" + announceId;            
        var deletedAttachmentIds = [];                
        
        $("#alreadyUploadFile tr").each(function(){
            var skipid = "#skip_" + skipLang[this.lang] ;
            var isCheck = $(skipid).attr("checked");
            if ( isCheck || $(this).attr('status') == 'delete'){
                var announcementId = $(this).find("td").find("input[name='attachmentId']").val();
                deletedAttachmentIds.push(announcementId);
            }                    
        });
       
        requestData.deletedAttachmentIds = deletedAttachmentIds.join(",");
        $("#deletedAttachmentIds").val(deletedAttachmentIds);            
    }else{
        $("#announceType").val(managerAnnouncement.announceType);
    }
    
    var uploadFiles = managerAnnouncement.getAllFileOfLanguage();       
    $("#languageFilesMapping").val(uploadFiles);
    requestData.languageFilesMapping = $("#languageFilesMapping").val();            
    //validate files num here.
    var isValidNum = managerAnnouncement.validateFileUpload(operationMode);
    if (!isValidNum){
        return false;
    }
    var newFileNumber = 0 ;
    $("#fileListTable tr[status='normal']").each(function(){
        var skipid = "#skip_" + skipLang[this.lang] ;
        var isCheck = $(skipid).attr("checked");
        if (!isCheck){
            newFileNumber = newFileNumber + 1 ;
        }
    });
    managerAnnouncement.changeButtonStatus(true);
    $("#files").attr("disabled", true);
    app.uiLoadingStatus.setIsLoading(true);
    managerAnnouncement.isSaving = true;
    if (newFileNumber == 0){
        var rest_requests = [];
        var rest_request = {url : requestUrl, data : requestData, type : "POST" };
        rest_requests.push(ajaxCall(rest_request));             
        $.when.apply(null, rest_requests)
           .always(function(){
               managerAnnouncement.isSaving = false;
               $("#files").attr("disabled", false);
               app.uiLoadingStatus.setIsLoading(false);
           })
           .done(showSaveResult)
           .fail(function(){                       
               managerAnnouncement.changeButtonStatus(false);                       
           })
           .done(function(){                       
               app.trigger('load', 'admin/managerAnnouncementList',
                       managerAnnouncement.announceType,
                       managerAnnouncement.currentLanguage,
                       managerAnnouncement.pageNo
               ); 
     }); 
    }
    else{
        requestUrl = requestUrl + "?cnumber=" + cnumber + "&rand=" + (new Date().getTime());
        $("#fileupload").fileupload({                    
            url : requestUrl,
            type : "POST",
            formData : requestData
        });
        
        $("#jqueryFileUploadBtn").click();
    }  
};


/**
 * bind event of buttons. save button,cancel button,delete button.
 */
managerAnnouncement.buttonEvent = function () {	
    
    $("a[name = 'addUpdateCancel']").die().live("click", function(){
        if (managerAnnouncement.isSaving){
            return ;
        } 
        app.trigger('load', 'admin/managerAnnouncementList',
                     managerAnnouncement.announceType,            managerAnnouncement.currentLanguage,
                     managerAnnouncement.pageNo
                   );       
    });
    
    //save event of new age and update page
    $("a[name = 'newSaveBtn']").die();
    $("a[name = 'newSaveBtn']").live("click", function(){
        var flag = managerAnnouncement.validSelectLanguage();
        if (!flag){            
            dialog.show(lang.getMessage("skipSaveMessage"), "Ok");            
            return ;
        }
        if (managerAnnouncement.isSaving){
            return ;
        }       

        var validator = new Validator(function(divId){
            var temps = divId.split("-");
            managerAnnouncement.displayDiv(temps[1]);
        });       
        
        var dtdList = [];
        for( var i = 0; i < managerAnnouncement.divs.length; i++ )  {
            var flag = $("#" + managerAnnouncement.divs[i].skipid).attr("checked") ;
            if ( flag ) {
                continue ;
            }
            var ok = validator.validateDiv(managerAnnouncement.divs[i].div);
            dtdList.push(ok);
        } 
        
        $.when.apply(null, dtdList).fail(function(){
            
        }).done(function(){
            /*****validate english content*********/
            var flag = managerAnnouncement.checkEnglishContent();
            if(flag){
                managerAnnouncement.processSaveAnnounce();
            }
            else{                
                dialog.show("<div style='height: 50px;'>" + lang.getMessage('msgenglishContent') + "</div>", lang.getMessage('confirm'), lang.getMessage('buttonCacel')).done( function(btnBtn) {
                    if (btnBtn === lang.getMessage('confirm')) {
                        managerAnnouncement.processSaveAnnounce();
                   }
                    else{
                        managerAnnouncement.displayDiv('en');
                        return;
                    }
                }); 
            }
            /*****english content end**************/
        });        
    });
        
    //update page delete event
    $("a[name = 'deleteAttachment']").die().live("click", function(){        
        if ( managerAnnouncement.isSaving || managerAnnouncement.skipButtonEvent() ){
            return ;
        } 
        var id = $(this).siblings("input[id='attachmentId']]").val();
        var titleShowId = "#titleShow" + id;
        $(titleShowId).css({"text-decoration" : "line-through"});
        $("#attachmentTr" + id).attr("status", "delete");       
        $("#deleteAttachBtn" + id).hide();
        $("#cancelDeleteAttachBtn" + id).show();
    });
    
    //update page cancel attachment event
    $("a[name = 'cancelDeleteAttachment']").die().live("click", function(){
        if ( managerAnnouncement.skipButtonEvent() || managerAnnouncement.isSaving ){
            return ;
        }       
        var id = $(this).siblings("input[id='attachmentId']]").val();
        var titleShowId = "#titleShow" + id;
        $(titleShowId).removeAttr("style");
        $("#attachmentTr" + id).attr("status", "normal");       
        $("#deleteAttachBtn" + id).show();
        $("#cancelDeleteAttachBtn" + id).hide();      
    });
    
    $("input[skip = 'true']").die().live("click", function(){
        managerAnnouncement.checkInputLang(this);
    });
    
    
};

