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

managerAnnouncementList.cacheData = {currentUrl:"",previoursUrl:"",cacheData:{}};
managerAnnouncementList.announceType = "";
managerAnnouncementList.pageNo = 1;
managerAnnouncementList.currentLang = "en" ;
managerAnnouncementList.isChangeStatus= false;
managerAnnouncementList.isSaving = false;
var inputNames = {
        "en" : "linkEng",
        "zh_CN" : "linkZh-CN",
        "zh_TW" : "linkZh-HK"
  };

var langFields = {
        "en":["announceTitleEN","announceContentEN","announceCatEN"],
        "zh_CN":["announceTitleSC","announceContentSC","announceCatSC"],
        "zh_TW":["announceTitleTC","announceContentTC","announceCatTC"]
};

/**
 * pagination callback.
 */
managerAnnouncementList.listCallBack = function(template, data){
    var html = genPaginationFooter(data.pagination,"managerAnnouncementList.list");
    $("#announcementPagination").empty();
    $("#announcementPagination").append(html);
    managerAnnouncementList.initSelectLanguage();
};


managerAnnouncementList.setLanguageButtonEvent = function (lang, inputName) {
    $("button[name='" + inputName + "']").click(function() {        
        managerAnnouncementList.loadData(managerAnnouncementList.announceType,false,lang,1);
    });
};


/**
 * according currentPage ,get announcement list.
 */
managerAnnouncementList.list = function(currentPage){
    managerAnnouncementList.pageNo = currentPage;    
    var type = managerAnnouncementList.announceType;
    return managerAnnouncementList.loadData(type,false,managerAnnouncementList.currentLang);
};

managerAnnouncementList.initAdminBar = function(type){
    var isAdmin1 = app.user.role.isAdmin1();
    var isAdmin2 = app.user.role.isAdmin2();   
    $("#admin1_btn").attr("disabled", !isAdmin1);
    $("#admin2_btn").attr("disabled", !isAdmin2);    
    background = type == "ADMIN1"? ["#292C29","#737173"]:["#737173","#292C29"];    
    
    if (!isAdmin1){
        $("#admin1_btn").css({ "background-color" : "#ccc" });
    }
    else{
        $("#admin1_btn").css({ "background-color" : background[0] });
    }
    if (!isAdmin2){
        $("#admin2_btn").css({ "background-color" : "#ccc" });
    }
    else{
        $("#admin2_btn").css({ "background-color" : background[1] });
    }
    
};

managerAnnouncementList.init = function(template, data){    
    managerAnnouncementList.listCallBack(template, data);
    managerAnnouncementList.buttonEvent();   
};

/**
 * default current page is 1.
 * load administrator main page.
 */
managerAnnouncementList.on( "load", function(){    
    var isAdmin1 = app.user.role.isAdmin1();
    var type = isAdmin1 ? "ADMIN1" :"ADMIN2";  
    var lang = "en" ,
        pageNo = 1;
    if (arguments.length > 0){
        managerAnnouncementList.announceType= arguments[0];
        type = managerAnnouncementList.announceType;
        lang = arguments[1] ;
        pageNo = arguments[2] ;
    }
    return managerAnnouncementList.loadData(type,false,lang,pageNo);
});

managerAnnouncementList.loadData = function(type,flag,currentLang,pageNo){
    trackAction("Announcement - List");
    trackAction("Announcement - ChangePage");
    $("#mainContent").empty();
    managerAnnouncementList.showLoading("mainContent");
    managerAnnouncementList.currentLang = currentLang ;
    var lang = managerAnnouncementList.currentLang ;   
    var isAdmin1 = app.user.role.isAdmin1();
    var mytype = "";
    if (managerAnnouncementList.announceType != ""){
        mytype = managerAnnouncementList.announceType;
    }
    else{
        mytype = isAdmin1 ? "ADMIN1" :"ADMIN2"; 
    }
    if (flag){
        mytype = type;
    }
    if (pageNo){
        managerAnnouncementList.pageNo = pageNo ;        
    }
    managerAnnouncementList.announceType = mytype;
    var requestUrl = app.EPRESTAPI_CONTEXT_ROOT + 
                    "announcement/page/" + managerAnnouncementList.pageNo +"?pageSize=" + app.ANNOUNCEMENT_PAGESIZE + "&type="+ mytype + "&language=" + lang ;
    
//    if (requestUrl == managerAnnouncementList.cacheData.currentUrl){
//        managerAnnouncementList.renderList(managerAnnouncementList.cacheData.cacheData,type);
//    }else{    
        var request = {url : requestUrl, data : {}, type : "GET" , async : true};
        return ajaxCall(request).done(function(returnData){        
            managerAnnouncementList.cacheData.previoursUrl = managerAnnouncementList.cacheData.currentUrl;
            managerAnnouncementList.cacheData.currentUrl = requestUrl;
            managerAnnouncementList.cacheData.cacheData = returnData;       
            
            var renderData = {};
            renderData.meta = returnData.meta;
            renderData.pagination = returnData.pagination;
            renderData.data = {};        
           
            renderData.data.data = [];
            if (returnData.data.data){
                for (var i = 0 ; i < returnData.data.data.length ; i++){
                     var sourceObj = returnData.data.data[i];
                     var announceObj = managerAnnouncementList.copyData(sourceObj,lang);
                     renderData.data.data.push(announceObj);
                } 
            }
            managerAnnouncementList.renderList(renderData,mytype);
        });  
//    }
};

managerAnnouncementList.renderList = function(renderData,type){
    var template = "template/admin/managerAnnouncement.html";
    return managerAnnouncementList.render(
            template, 
            "mainContent", 
            renderData
       ).done( function(template,data){           
             managerAnnouncementList.init(template,data);              
             managerAnnouncementList.initAdminBar(type);           
       });
};

/**
 * announcement title display more content if the length of title exceed 10 ?? character
 */
managerAnnouncementList.displayMore = function(id){
    $("#showMore_" + id).css("display","none");
    $("#showCompress_" + id).css({"display":"block"});
};

/**
 * @param id ,announcement id.
 * announcement title display compress content.
 */
managerAnnouncementList.displayCompress = function(id){
    $("#showMore_" + id).css("display","block");
    $("#showCompress_" + id).css({"display":"none"});
};


managerAnnouncementList.changeLangBtnCss = function(currentLang){
    var background = [];
    ["en","zh_CN","zh_TW"].forEach(function(lang){
        background = currentLang == lang ? ["#C00"]:["#737173"];       
        $("button[name='" + inputNames[lang] + "']").css({ "background-color" : background[0] }); 
    });
    
};

managerAnnouncementList.initSelectLanguage = function() {
    
    var currentLang = managerAnnouncementList.currentLang;
    managerAnnouncementList.changeLangBtnCss(currentLang);
    
    for (var lang in inputNames) {
        managerAnnouncementList.setLanguageButtonEvent(lang, inputNames[lang]);
    }
    
};

/**
 * change status of save button,
 * if sonme item are marked as deleted item. then save button disable = true.
 */
managerAnnouncementList.changeStatus = function(){    
    var status = $("#appTable tr[status = 'delete']").length;
    var isEnable = status == 0 ? true : false;
    managerAnnouncementList.isChangeStatus= !isEnable ;
    $("button[name='saveButton']").attr("disabled", isEnable);
    $("button[name='editButton']").attr("disabled", !isEnable);
    if (isEnable) {
        /*
         * $(button).removeClass("greyDivButton");
           $(button).addClass("redDivButton");
         * */
        $("a[name='saveButton']").each(function(){            
            $(this).removeClass("redDivButton").addClass("greyDivButton") ;
        });
        
        $("a[name='addButton']").each(function(){
            $(this).removeClass("greyDivButton").addClass("redDivButton") ;
        });
        
        $("a[name='editButton']").each(function(){
            $(this).removeClass("greyDivButton").addClass("redDivButton") ;
        });
        
        $("button[name='linkEng']").css({"background-color":"#737173"}) ;
        $("button[name='linkZh-HK']").css({"background-color":"#737173"}) ;
        $("button[name='linkZh-CN']").css({"background-color":"#737173"}) ;
        $("button[name='"+inputNames[managerAnnouncementList.currentLang]+"']").css({"background-color":"#CE0000"}); 
    }
    else{
        $("a[name='saveButton']").each(function(){
            $(this).removeClass("greyDivButton").addClass("redDivButton") ;
        });
        
        $("a[name='addButton']").each(function(){
            $(this).removeClass("redDivButton").addClass("greyDivButton") ;
        });
        
        $("a[name='editButton']").each(function(){
            $(this).removeClass("redDivButton").addClass("greyDivButton") ;
        });
        
        $("button[name='linkEng']").css({"background-color":"#ccc"}) ;
        $("button[name='linkZh-HK']").css({"background-color":"#ccc"}) ;
        $("button[name='linkZh-CN']").css({"background-color":"#ccc"}) ;
        $("button[name='"+inputNames[managerAnnouncementList.currentLang]+"']").css({"background-color":"#737173"});
        
    }
    ["linkEng","linkZh-HK","linkZh-CN"].forEach(function(btnName){
        $("button[name='" + btnName + "']").attr("disabled", !isEnable);       
    });
    
    var isAdmin1 = app.user.role.isAdmin1();
    var isAdmin2 = app.user.role.isAdmin2();
    if (isAdmin1){
        $("button[name='admin1_btn']").attr("disabled", !isEnable); 
    }
    if (isAdmin2){
        $("button[name='admin2_btn']").attr("disabled", !isEnable);  
    }
   
};

function loadAnnoucementDetailComponent(id){
    function initComponent(currentLang,pageNo){
        loadScript(["scripts/jquery-fileupload/jquery.ui.widget.js",
                    "scripts/jquery-fileupload/jquery.iframe-transport.js",
                    "scripts/jquery-fileupload/jquery.fileupload.js",
                    "scripts/jquery-fileupload/jquery.fileupload-process.js",
                    "scripts/jquery-fileupload/jquery.fileupload-validate.js",
                    "scripts/jquery-fileupload/jquery.fileupload-ui.js",
                    "scripts/jquery-fileupload/wmd.upload.js"]
        ); 
        app.trigger('load', 'admin/managerAnnouncement',currentLang,managerAnnouncementList.announceType,pageNo);
    }
    if (id){
        managerAnnouncementList.render("template/admin/managerAnnouncementUpdate.html", 
            "mainContent", 
            "announcement/" + id 
        ).done( function(template,returnData){
            var langCurr = managerAnnouncementList.currentLang ;
            managerAnnouncementList.buttonEvent();
            initComponent(langCurr,managerAnnouncementList.pageNo);
            if ( managerAnnouncementList.announceType == "ADMIN2" ){
            	$("#announceCatEN").val("Market Insights").attr("NotAllowed", "false").hide();            	
            	$("#announceCatTC").val("市場透視").attr("NotAllowed", "false").hide(); 
            	$("#announceCatSC").val("市场透视").attr("NotAllowed", "false").hide(); 
            	$("#announceCatEN").parent().append("<label style='margin-left:0px;'>Market Insights</label>");
                $("#announceCatTC").parent().append("<label style='margin-left:0px;'>市場透視</label>");
                $("#announceCatSC").parent().append("<label style='margin-left:0px;'>市场透视</label>");
            }

            ["EN","SC","TC"].forEach( function(pLang){
                if ( $.trim(returnData.data.data["announceTitle" + pLang]) == '' ){
                    $("#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"); 
                    $("#skip_" + pLang).attr("checked" , true) ;
                }
            });            
        });    
    }
    else{
        managerAnnouncementList.render(
            "template/admin/managerAnnouncementAdd.html",
            "mainContent",
            {}
        ).done(function(){
            var langEN = "en";
            initComponent(langEN,1);
            if ( managerAnnouncementList.announceType == "ADMIN2" ){
            	$("#announceCatEN").val("Market Insights").attr("NotAllowed", "false").hide();             	
            	$("#announceCatTC").val("市場透視").attr("NotAllowed", "false").hide(); 
            	$("#announceCatSC").val("市场透视").attr("NotAllowed", "false").hide(); 
            	
            	$("#announceCatEN").parent().append("<label style='margin-left:0px;'>Market Insights</label>");
            	$("#announceCatTC").parent().append("<label style='margin-left:0px;'>市場透視</label>");
            	$("#announceCatSC").parent().append("<label style='margin-left:0px;'>市场透视</label>");
            }
        });
    }
}

/**
 * copy data from source announcement object.
 */
managerAnnouncementList.copyData = function(sourceObj,currentLang){
    var announceObj = {};
    announceObj.announceId = sourceObj.announceId;
    announceObj.announceTitle = sourceObj[ langFields[currentLang][0] ];
    announceObj.announceContent = sourceObj[ langFields[currentLang][1] ];
    announceObj.announceCat = sourceObj[ langFields[currentLang][2] ];
    announceObj.createdDate = sourceObj.createdDate;
    announceObj.createdDateStr = sourceObj.createdDateStr;
    announceObj.attachCount = sourceObj.attachCount;
    announceObj.announceStaus = sourceObj.announceStaus;
    announceObj.attachments = [];
    for(var j = 0 ; j<sourceObj.attachments.length ; j++){
        if (sourceObj.attachments[j].announceLang == currentLang){
            announceObj.attachments.push(sourceObj.attachments[j]);
        }
    }
    return announceObj;
};

managerAnnouncementList.changeButtonStatus = function(flag) { 
    btnArray = ["linkEng","linkZh-HK","linkZh-CN","admin1_btn","admin2_btn"];
    btnArray.forEach(function(btnName){
        $("button[name='" + btnName +"']").attr("disabled", flag);
    });
};


/**
 * bind event to eidt,cancel,save,add button.
 */
managerAnnouncementList.buttonEvent = function () {
    $("a[name = 'addButton']").die();
    $("a[name = 'addButton']").live("click", function(){
        if ( !managerAnnouncementList.isChangeStatus){
            loadAnnoucementDetailComponent();
        }
    });
    
    $("a[name = 'editButton']").die();
    $("a[name = 'editButton']").live("click", function(){
        if ( managerAnnouncementList.isChangeStatus){
            return ;
        } 
        var id = $(this).siblings("input[id = 'announcementDbId']]").val();        
        loadAnnoucementDetailComponent(id);
    });
    
    $("a[name = 'removeButton']").die();
    $("a[name = 'removeButton']").live("click", function(){
        if ( managerAnnouncementList.isSaving ){
            return ;
        }
        var id = $(this).siblings("input[id = 'announcementDbId']]").val();
        var titleShowId = "#titleShow" + id;       
        dialog.show(lang.getMessage('confirmDeleteItems'), lang.getMessage('confirm'), lang.getMessage('buttonCacel')).done( function(btnBtn) {
             if (btnBtn === lang.getMessage('confirm')) {            
                 $(titleShowId).css({"text-decoration" : "line-through"});
                 $("#announcementTr" + id).attr("status", "delete");
                 $("#editButton" + id).hide();
                 $("#removeButton" + id).hide();
                 $("#cancelButton" + id).show();
                 managerAnnouncementList.changeStatus();
            }
         }); 
       
    });

    $("a[name = 'cancelButton']").die();
    $("a[name = 'cancelButton']").live("click", function(){
        if ( managerAnnouncementList.isSaving ){
            return ;
        }
        var id = $(this).siblings("input[id='announcementDbId']]").val();
        var titleShowId = "#titleShow" + id;
        $(titleShowId).removeAttr("style");
        $("#announcementTr" + id).attr("status", "");
        $("#editButton" + id).show();
        $("#removeButton" + id).show();
        $("#cancelButton" + id).hide();
        managerAnnouncementList.changeStatus();
    });
    
    /*save enent of list page*/
    $("a[name = 'saveButton']").die();
    $("a[name = 'saveButton']").live("click", function(){  
        var delLength = $("#appTable tr[status = 'delete']").length;
        if (delLength == 0){
            return ;
        }
        $("a[name='saveButton']").each(function(){
            $(this).removeClass("redDivButton").addClass("greyDivButton") ;
        });
        
        $("a[name='cancelButton']").each(function(){
            $(this).removeClass("redDivButton").addClass("greyDivButton") ;
        });
        
        $("a[name='removeButton']").each(function(){
            $(this).removeClass("redDivButton").addClass("greyDivButton") ;
        });
        
        
        rest_requests = [];
        $("tr[status='delete']").each(
            function(f, tr) {
                var announcementId = $(tr).find("td").find("input[id = 'announcementDbId']").val();
                var rest_request = {
                    url : app.EPRESTAPI_CONTEXT_ROOT + "announcement/" + announcementId,
                    data : {},
                    type : "DELETE",
                    dataType : "json"
                };
                rest_requests.push(ajaxCall(rest_request));               
        });
        app.uiLoadingStatus.setIsLoading(true);
        managerAnnouncementList.changeButtonStatus(true);
        managerAnnouncementList.isSaving = true;
        $.when.apply(null, rest_requests) 
        .always(function(){
            managerAnnouncementList.isSaving = false;
        })
        .done(showSaveResult)
        .fail(function(){
            managerAnnouncementList.changeButtonStatus(false);
            $("a[name='saveButton']").each(function(){
                $(this).removeClass("greyDivButton").addClass("redDivButton") ;
            });
            $("a[name='cancelButton']").each(function(){
                $(this).removeClass("greyDivButton").addClass("redDivButton") ;
            });
            $("a[name='removeButton']").each(function(){
                $(this).removeClass("greyDivButton").addClass("redDivButton") ;
            });
            app.uiLoadingStatus.setIsLoading(false);
        })
        .done(function(){
            managerAnnouncementList.isChangeStatus= false;
            app.uiLoadingStatus.setIsLoading(false);
            app.trigger('load', 'admin/managerAnnouncementList',
                         managerAnnouncementList.announceType,
                         managerAnnouncementList.currentLang,
                         managerAnnouncementList.pageNo                         
                    );  
        });
    });
   
};
