/// <reference path="../common/js/avweb.js" />
/// <reference path="../common/js/common.js" />
/// <reference path="../common/js/i18n.js" />
/// <reference path="../common/js/jquery-1.8.1.min.js" />
/// <reference path="../common/js/jquery-ui-1.8.23.custom.min.js" />
/// <reference path="../common/js/jquery.toastmessage.js" />


var timeWaitCloseNewInfoPushMessage = 5000; // time wait close info new push message 5 seconds
var currentPagePushMessage = 1;
var isHoverOn = false;

$(document).ready(function () {

    if (!avwCheckLogin(ScreenIds.Login)) return;

    // Set event to prevent leave
    //avwSetLogoutNortice();
    if (ClientData.requirePasswordChange() != 1) {
        ToogleLogoutNortice();
    }

    //Toggle Searchbox
    $('input#searchbox-key').click(toggleSearchPanel);

    $("#searchbox-key").attr('placeholder', i18nText('msgPlaceHolder'));

    //Go to Search Page
    $('#searchbox-search').click(searchHeaderButtonFunction);

    //Change Language JP
    $('#language-jp').click(changeLanguageJa);

    //Change Language KR
    $('#language-kr').click(changeLanguageKo);

    //Change Language EN
    $('#language-en').click(changeLanguageEn);

    //Go To Bookmark Page
    $('#dspShiori').click(bookmarkFunction);

    //Go To update configuration
    $('#dspSetting').click(updateConfigFunction);

    // hide logout button with anonymous user
    if (isAnonymousLogin()) {
        $('#dspLogout').hide();
        $('#dspSetting').hide();
    }
    else {
        //Go To Login Page
        $('#dspLogout').click(logoutFunction);
        $('#dspLogout').show();
        $('#dspSetting').show();
    }

    $('#dspViewHistory').click(historyClickFunction);

    $('#dspHome').click(homeClickFunction);

    //Hide search panel until click on text field
    $('div#header-searchbox').css('display', 'none');

    if (isAnonymousLogin()) {
        $('#li-login-username').hide();
    }
    else {
        //li-login-username
        $('#li-login-username').show();
        //Display user name
        $('#login-username').text(ClientData.userInfo_userName());
    }

    $('#dlgConfirmBackup-backup').click(confirmWithBackupFunction);

    $('#dlgConfirmBackup-withoutbackup').click(confirmWithoutBackupFunction);

    $('#dlgConfirmBackup1').hide();

    $('#searchbox-key').keydown(headerSearchKeyDownEventFunction);

    $('#searchbox-content-header').click(headerSearchContentClickFunction);

    $('#searchbox-tag-header').click(headerSearchTagClickFunction);

    $('#searchbox-body-header').click(headerSearchBodyClickFunction);

    //init push message
    initPushMessage();

    //$('*').click(handleHeaderSearchBoxEvent);

    if (isTouchDevice() == false) {
        $('#searchbox-key').hover(searchBoxHoverFunction, searchBoxHoverOffFunction);

        $('#header-searchbox').hover(searchBoxHoverFunction, searchBoxHoverOffFunction);
    }

    if (isTouchDevice() == true) {
        var bodyTag = document.getElementsByTagName('body')[0];
        bodyTag.addEventListener('touchstart', bodyClickFunction, false);
    }
    else {
        $('body').click(bodyClickFunction);
    }

});

function searchBoxHoverFunction(){
	isHoverOn = true;
};

function searchBoxHoverOffFunction() {
	isHoverOn = false;
};

// check disabled button
function checkDisabledButton(selector, buttonid) {
    $(selector).click(
            function () {
                setDisabledButton(selector, buttonid);
            });
    setDisabledButton(selector, buttonid);
};

function setDisabledButton(selector, buttonid) {
    var isDisabled = $(selector + ':checked').length == 0;
    if (isDisabled) {
        $(buttonid).addClass('disabled');
    }
    else {
        $(buttonid).removeClass('disabled');
    }
};


function bodyClickFunction(event) {
    if (isTouchDevice()) {
        
        // Check mouse is in rectangle of searching panel
        if ($('#header-searchbox').is(":visible"))  //if ($('#header-searchbox').css('display') != "none") 
        {

            var currPosX, currPosY;
            var avwUserEnvObj = new UserEnvironment();

            if (avwUserEnvObj.os == 'android') {
                //$("#searchbox-key").val(event.targetTouches[0].pageX + "_" + $('#header-searchbox').position().left + ":" + ($('#header-searchbox').position().left + $('#header-searchbox').width()));
                currPosX = event.targetTouches[0].pageX;
                currPosY = event.targetTouches[0].pageY;
            }
            else {
                currPosX = event.targetTouches[0].clientX;
                currPosY = event.targetTouches[0].clientY;
            }

            var leftsearch = $('#header-searchbox').offset().left;
            var topsearch = $('#header-searchbox').offset().top;
            var rightsearch = $('#header-searchbox').width() + leftsearch;
            var bottomsearch = $('#header-searchbox').height() + topsearch;

            // check mouse position in search region
            if (currPosX >= leftsearch && currPosX <= rightsearch && currPosY >= topsearch && currPosY <= bottomsearch) {
                isHoverOn = true;
            }
            else {
                isHoverOn = false;
                $('#header-searchbox').hide();
            }


//            if (currPosX >= $('#header-searchbox').position().left
//                && currPosX <= ($('#header-searchbox').position().left + $('#header-searchbox').width())
//                && currPosY >= $('#header-searchbox').position().top
//                && currPosY <= ($('#header-searchbox').position().top + $('#header-searchbox').height())) {

//                isHoverOn = true;
//            }
//            else {
//                isHoverOn = false;
//            }
        }
    }
    else {
        if (!isHoverOn) {
            $('#header-searchbox').hide();
        }
    }
};

function headerSearchBodyClickFunction() {
    
	$('#searchbox-body').attr('checked','checked');
	$('#searchbox-tag').removeAttr('checked');
	$('#searchbox-content').removeAttr('checked');
	isHoverOn = true;
};

function headerSearchTagClickFunction() {
    
	$('#searchbox-tag').attr('checked','checked');
	$('#searchbox-body').removeAttr('checked');
	$('#searchbox-content').removeAttr('checked');
	isHoverOn = true;
};

function headerSearchContentClickFunction() {
    
	$('#searchbox-content').attr('checked','checked');
	$('#searchbox-tag').removeAttr('checked');
	$('#searchbox-body').removeAttr('checked');
	isHoverOn = true;
};


//function header search box key down function
function headerSearchKeyDownEventFunction(e){
 	var code = (e.keyCode ? e.keyCode : e.which);
 	if(code == 13) { //Enter keycode
   		$('#searchbox-search').click();
 }
 isHoverOn = true;
};

//Toggle Search Panel Click function
function toggleSearchPanel(){
    if ($("div#header-searchbox").is(":hidden")) {

        // show radio options
        $('div#header-searchbox').slideDown('slow');

        // set default option search
        if ($('#header-searchbox input:checked').length == 0) {
            // set option default is searchbox content
            $('#searchbox-content').attr('checked', 'checked');
        }

	} else {
		$('div#header-searchbox').hide();
	}	
};

//Button Search Event function
function searchHeaderButtonFunction(){
	var content = $('#searchbox-content').attr('checked');
	var tag = $('#searchbox-tag').attr('checked');
	var body = $('#searchbox-body').attr('checked');
	
	var searchDivision;
	var searchText = $('#searchbox-key').val();
	if(content == 'checked')
	{
		searchDivision = $('#searchbox-content').val();
	}
	if(tag == 'checked')
	{
		searchDivision = $('#searchbox-tag').val();
	}
	if(body == 'checked')
	{
		searchDivision = $('#searchbox-body').val();
	}			

	ClientData.searchCond_searchText(searchText);
	ClientData.searchCond_searchDivision(searchDivision);
	//window.location = ScreenIds.ContentSearch;
	avwScreenMove(ScreenIds.ContentSearch);
};

function homeClickFunction(){
    //window.location = ScreenIds.Home;
    avwScreenMove(ScreenIds.Home);
};

//Change Language Japanese function
function changeLanguageJa(){
	changeLanguage(Consts.ConstLanguage_Ja);	
	//ClientData.userInfo_language(Consts.ConstLanguage_Ja);
	//$('#control-sort-titlekana').css('display','inline-block');
	//$('#separate').css('display','inline-block');
	//formatDisplayMoreRecord();
	if(window.changeLanguageCallBackFunction){
		changeLanguageCallBackFunction();
	}
    $("#searchbox-key").attr('placeholder', i18nText('msgPlaceHolder'));
};

//Change Language English functions
function changeLanguageEn(){
	changeLanguage(Consts.ConstLanguage_En);	
	//ClientData.userInfo_language(Consts.ConstLanguage_En);
	//$('#control-sort-titlekana').css('display','none');
	//$('#separate').css('display','none');
	//formatDisplayMoreRecord();
	if(window.changeLanguageCallBackFunction){
		changeLanguageCallBackFunction();
	}
    $("#searchbox-key").attr('placeholder', i18nText('msgPlaceHolder'));
};

//Change Language English function
function changeLanguageKo(){
	changeLanguage(Consts.ConstLanguage_Ko);	
	//ClientData.userInfo_language(Consts.ConstLanguage_Ko);
	//$('#control-sort-titlekana').css('display','none');
	//$('#separate').css('display','none');
	//formatDisplayMoreRecord();
	if(window.changeLanguageCallBackFunction){
		changeLanguageCallBackFunction();
    }
    $("#searchbox-key").attr('placeholder', i18nText('msgPlaceHolder'));
};

//Shiori function
function bookmarkFunction(){
    //window.location = ScreenIds.BookmarkList;
    avwScreenMove(ScreenIds.BookmarkList);
};

//Update Config function
function updateConfigFunction(){
    //window.location = ScreenIds.Setting;
    avwScreenMove(ScreenIds.Setting);
};

//Logout function
function logoutFunction() {

    // check content is changed, update status option backup

    if (ClientData.isChangedBookmark()) 
    {
        if (ClientData.userOpt_bkShioriFlag() == 0) {
            $("#chkBkAllShiori").removeAttr('checked');
        }
        else {
            $("#chkBkAllShiori").attr('checked', 'checked');
        }        
    }
    else {
        $('#chkBkAllShiori').attr('disabled', 'disabled').removeAttr('checked');
    }

    if (ClientData.isChangedMemo()) {

        if (ClientData.userOpt_bkMemoFlag() == 0) {
            $("#chkBkAllMemo").removeAttr('checked');
        }
        else {
            $("#chkBkAllMemo").attr('checked', 'checked');
        }        
    }
    else 
    {
        $('#chkBkAllMemo').attr('disabled', 'disabled').removeAttr('checked');
    }

    if (ClientData.isChangedMarkingData()) 
    {
        if (ClientData.userOpt_bkMakingFlag() == 0) {
            $("#chkBkAllMarking").removeAttr('checked');
        }
        else {
            $("#chkBkAllMarking").attr('checked', 'checked');
        }        
    }
    else {
        $('#chkBkAllMarking').attr('disabled', 'disabled').removeAttr('checked');
    }


    if (ClientData.isChangedBookmark() == true || ClientData.isChangedMarkingData() == true || ClientData.isChangedMemo() == true) {
        // In case: user_data_backup = "Y" -> backup
        if (ClientData.serviceOpt_user_data_backup() == "Y") {

            if (ClientData.userOpt_bkConfirmFlg() == 1) {  // Show confirming dialog                
                //$('#dlgConfirmBackup1').dialog({ width: 600, height: 200, modal: true });
                lockLayout();
                $('#dlgConfirmBackup1').show();
                $('#dlgConfirmBackup1').center();

                // check disabled button backup
                checkDisabledButton('#dlgConfirmBackup1 .option_backup input', '#dlgConfirmBackup-backup');
            }
            else {  // Do not show confirming dialog
                if (ClientData.userOpt_logoutMode() == null || ClientData.userOpt_logoutMode() == undefined) {
                    //$('#dlgConfirmBackup1').dialog({ width: 600, height: 200, modal: true });
                    lockLayout();
                    $('#dlgConfirmBackup1').show();
                    $('#dlgConfirmBackup1').center();
                }
                else {
                    if (ClientData.userOpt_logoutMode() == 0) {  // Logout with backup                        
                        
                        var isBackupMarking=ClientData.userOpt_bkMakingFlag() == 1;
                        var isBackupMemo=ClientData.userOpt_bkMemoFlag() == 1;
                        var isBackupBookmark = ClientData.userOpt_bkShioriFlag() == 1;

                        DoBackup(isBackupMarking, isBackupMemo, isBackupBookmark, true);
                    }
                    else if (ClientData.userOpt_logoutMode() == 1) {  // Logout without backup
                        // Do nothing
                        //Logout
                        webLogoutEvent();
                    }
                }
            }
        }
        // In case: user_data_backup != "Y" -> No backup, logout
        else { 
            webLogoutEvent();
        }
	}
	else{
		webLogoutEvent();
	}
};

function historyClickFunction(){
    //window.location = ScreenIds.History;
    avwScreenMove(ScreenIds.History);
};

//Web Logout Event
function webLogoutEvent(){

    var params = {
        sid: ClientData.userInfo_sid()
    };

    avwCmsApiSync(ClientData.userInfo_accountPath(), "webLogout", "GET", params,
                    function (data) {
                        SessionStorageUtils.clear();
                        avwUserSetting().remove(Keys.userInfo_sid);
                        // Move to login screen
                        //window.location = ScreenIds.Login;
                        avwScreenMove(ScreenIds.Login);
                    },
                    null);
};

//Logout Without Backup function
function confirmWithoutBackupFunction(e) {
    e.preventDefault();
	var remember = $('#chkRememberBackup').attr('checked');
	
	if(remember == 'checked'){
	    ClientData.userOpt_bkConfirmFlg(0); // Do not show dialog in next time
	}
	else{
	    ClientData.userOpt_bkConfirmFlg(1); // Show dialog in next time
	}

	ClientData.userOpt_logoutMode(1); // In next time, if choose: [do not show dialog], will not backup and logout
	//window.location = ScreenIds.Login;
	webLogoutEvent();
};

//Logout With Backup function
function confirmWithBackupFunction(e) {
    e.preventDefault();

    // check button is disabled
    if ($(this).hasClass('disabled'))
        return;

    // update status flag update options No.17

    var isBackupMarking=$("#chkBkAllMarking").attr('checked') == 'checked';
    var isBackupMemo = $("#chkBkAllMemo").attr('checked') == 'checked';
    var isBackupBookmark = $("#chkBkAllShiori").attr('checked') == 'checked';
    
	var remember = $('#chkRememberBackup').attr('checked');
	unlockLayout();
	$('#dlgConfirmBackup1').css('z-index', '99');
	lockLayout();

	if (remember == 'checked') {

	    ClientData.userOpt_bkConfirmFlg(0);  // Do not show dialog in next time

	    // update status backup in setting
	    ClientData.userOpt_bkMakingFlag(isBackupMarking);
	    ClientData.userOpt_bkMemoFlag(isBackupMemo);
	    ClientData.userOpt_bkShioriFlag(isBackupBookmark);

        DoBackup(isBackupMarking, isBackupMemo, isBackupBookmark, true);
	}
	else{
		ClientData.userOpt_bkConfirmFlg(1);  // Show dialog in next time
		DoBackup(isBackupMarking, isBackupMemo, isBackupBookmark, true);
	}
	
	ClientData.userOpt_logoutMode(0);  // In next time, if choose: [do not show dialog], will backup and logout
	//webLogoutEvent();
};
//Confirm Back Up Ok
function DoBackup(isBackupMarking, isBackupMemo, isBackupBookmark,isLogout,funcCallback) {
    // ----------------------------
    // Process backup here
    // ----------------------------

     //Bakup memo/marking/bookmark

//    var params = [
//        { name: 'sid', content: ClientData.userInfo_sid() },
//        { name: 'deviceType', content: '4' },
//        { name: 'formFile', content: JSON.stringify(buildBackupData()), fileName: 'webBackupData.json', contentType: 'text-plain' }
//    ];
//        avwUploadBackupFile(ClientData.userInfo_accountPath(), params, false,
//                        function (data) {
//                            if (JSON.parse(data).result == "success") {
//                                ClientData.isChangedBookmark(false);
//                                ClientData.isChangedMarkingData(false);
//                                ClientData.isChangedMemo(false);
//                                //alert(i18nText('msgBackupSuccess'));
//															   							  
//                               // Show message: msgBackupSuccess
//                               $().toastmessage({ position: 'middle-center' });
//                               $().toastmessage('showToast', {
//                                   type: 'success',
//                                   sticky: true,
//                                   text: i18nText('msgBackupSuccess'),                                   									
//                               });
//                               $('.toast-position-middle-center').css('width', '500px');
//                               $('.toast-position-middle-center').css('margin-left', '-250px');
//                               $('.toast-item-close').live('click', webLogoutEvent);                               
//                            }
//                            else {
//                                //alert(i18nText('msgBackupFailed'));
//                               // Show error message: msgBackupFailed
//                               $().toastmessage({ position: 'middle-center' });
//                               $().toastmessage('showToast', {
//                                   type: 'error',
//                                   sticky: true,
//                                   text: i18nText('msgBackupFailed')
//                               });
//                               $('.toast-position-middle-center').css('width', '500px');
//                               $('.toast-position-middle-center').css('margin-left', '-250px');
//                               $('.toast-item-close').live('click', webLogoutEvent);
//                            }
//                        },
//                        function (a, b, c) {
//                            //alert(i18nText('msgBackupFailed'));
//                           // Show error message: msgBackupFailed
//                           $().toastmessage({ position: 'middle-center' });
//                           $().toastmessage('showToast', {
//                               type: 'error',
//                               sticky: true,
//                               text: i18nText('msgBackupFailed')
//                           });
//                           $('.toast-position-middle-center').css('width', '500px');
//                           $('.toast-position-middle-center').css('margin-left', '-250px');
//                           $('.toast-item-close').live('click', webLogoutEvent);
//                            });

    // Backup for No.17    

//    if (!isBackupMarking && !isBackupMemo && !isBackupBookmark)
//        return;

    // check if data is changed and has option backup
    if ((ClientData.isChangedBookmark() == true && isBackupBookmark) || (ClientData.isChangedMarkingData() == true && isBackupMarking) || (ClientData.isChangedMemo() == true && isBackupMemo)) {

        if (isLogout) {
            lockLayout();
        }

        $().toastmessage({ position: 'middle-center' });
        $().toastmessage('showToast', {
            type: '',
            sticky: true,
            text: '',
            customMessages: 'divResultMessage'
        });

        // show item loading
        $('#divResultMessage').append("<div class='toast-item-loading'></div>");

        setTimeout(function () {

            // backup Marking
            var isBackupMarkingOK = true;
            var isBackupMemoOK = true;
            var isBackupBookmarkOK = true;

            if (isBackupMarking && ClientData.isChangedMarkingData() == true) {
                isBackupMarkingOK = sendSignalBackupStart(2); // start backup type marking
                if (isBackupMarkingOK) {
                    isBackupMarkingOK = backupFile(JSON.stringify({ "type": 2, "data": ClientData.MarkingData() }), 'Marking.json', 2);
                    if (isBackupMarkingOK) {
                        ClientData.isChangedMarkingData(false);
                        $('#divResultMessage').append("<div class='toast-item-image-success toast-item-message'>" + i18nText('txtBkMarking') + " " + i18nText('msgBackupSuccess') + "</div>");
                    }
                    // finish backup marking if start backup marking success
                    sendSignalBackupFinish(2);
                }
                if (!isBackupMarkingOK) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + i18nText('txtBkMarking') + " " + i18nText('msgBackupFailed') + "</div>");
                }
            }

            // Backup bookmark
            if (isBackupBookmark && ClientData.isChangedBookmark() == true) {
                isBackupBookmarkOK = sendSignalBackupStart(4); // start backup type bookmark
                if (isBackupBookmarkOK) {
                    isBackupBookmarkOK = backupFile(JSON.stringify({ "type": 3, "data": ClientData.BookMarkData() }), 'Bookmark.json', 4);
                    if (isBackupBookmarkOK) {
                        ClientData.isChangedBookmark(false);

                        $('#divResultMessage').append("<div class='toast-item-image-success toast-item-message'>" + i18nText('txtBkShiori') + " " + i18nText('msgBackupSuccess') + "</div>");
                    }
                    // finish backup bookmark if start backup bookmark ok
                    sendSignalBackupFinish(4);
                }
                if (!isBackupBookmarkOK) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + i18nText('txtBkShiori') + " " + i18nText('msgBackupFailed') + "</div>");
                }
            }

            // Backup Memo

            if (isBackupMemo && ClientData.isChangedMemo() == true) {
                isBackupMemoOK = sendSignalBackupStart(1); // start backup type memo
                if (isBackupMemoOK) {
                    isBackupMemoOK = backupFile(JSON.stringify({ "type": 1, "data": ClientData.MemoData() }), 'ContentMemo.json', 1);
                    if (isBackupMemoOK) {
                        ClientData.isChangedMemo(false);
                        $('#divResultMessage').append("<div class='toast-item-image-success toast-item-message'>" + i18nText('txtBkMemo') + " " + i18nText('msgBackupSuccess') + "</div>");
                    }
                    // finish backup memo if start backup memo ok
                    sendSignalBackupFinish(1);
                }
                if (!isBackupMemoOK) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + i18nText('txtBkMemo') + " " + i18nText('msgBackupFailed') + "</div>");
                }
            }

            // hide item loading
            $('#divResultMessage .toast-item-loading').hide();

            // active close toast button
            $('.toast-item-close').click(function () { $().toastmessage('removeToast', $('#divResultMessage'), null) });

            if (isLogout) {
                $('.toast-position-middle-center').css('width', '500px');
                $('.toast-position-middle-center').css('margin-left', '-250px');
                $('.toast-item-close').live('click', webLogoutEvent);
            }

            // check call back function
            if (funcCallback) {
                funcCallback();
            }

        }, 1000);
    }
    else 
    {
        if (isLogout) {
            webLogoutEvent();
        }
    }
};

function backupFile(data, file,type) {
    var result = false;
    var params = [
        { name: 'sid', content: ClientData.userInfo_sid() },
    //{ name: 'deviceType', content: '4' },
        //{name: 'fileType', content: type },
        { name: 'formFile', content: data, fileName: file, contentType: 'text-plain' }
    ];
    avwUploadBackupFile(ClientData.userInfo_accountPath(), params, false,
                function (data)
                {
                    if (JSON.parse(data).result == "success") 
                    {
                        result = true;
                    }
                }, function (a, b, c) { });
    return result;
};

// send signal backup start
function sendSignalBackupStart(typeBackup)
{
    var result = false;
    var params = { "sid": ClientData.userInfo_sid(), "fileType": typeBackup };
    avwCmsApiSync(ClientData.userInfo_accountPath(), "notifyBackupStart", "post", params,
                    function (data) {                        
                        if (data.result == "success") {
                            result = true;
                        }
                    },
                    function (xhr, b, c) { });
    return result;
};

// send signal backup finish
function sendSignalBackupFinish(typeBackup)
{
    var result = false;
    var params = { "sid": ClientData.userInfo_sid(), "fileType": typeBackup };
    avwCmsApiSync(ClientData.userInfo_accountPath(), "notifyBackupFinish", "post", params,
                    function (data) {
                        if (data.result == "success") {
                            result = true;
                        }
                    },
                    function (xhr, b, c) { });
    return result;
};

/* ------ */

function checkForceChangePassword(){
	if(ClientData.BookmarkScreen() != ScreenIds.Setting){
	   if(ClientData.requirePasswordChange() == 1){
	   		//alert(i18nText('msgPWDNeedChange'));
			showErrorScreenForceChangePassword();
	   }
	}
};

function showErrorScreenForceChangePassword(){
	var tags = '<div id="avw-auth-error">' +
				   '<div style="display:table; width:100%; height:100%;">' + 
				   '<div style="display:table-cell; text-align:center; vertical-align:middle;">' +
				   '<p>'+i18nText('msgPWDNeedChange')+'</p>' + 
				   '<div><button id="avw-unauth-ok">OK</button></div>' +
				   '</div></div></div>';
		$('body').prepend(tags);
		$('#avw-auth-error').css( {			
			'opacity': 1,
			'position': 'fixed',
			'top': '0',
			'left': '0',
			'width': $(window).width(),
			'height': $(window).height(),
			'zIndex': '10000'
		});
		// resize error page	
		$(window).resize(function() {
			$('#avw-auth-error').css( {
				'width': $(window).width(),
				'height': $(window).height()
			});			
		});
		
		$('#avw-unauth-ok').click(function() {
			ClientData.BookmarkScreen(ScreenIds.Setting);
			avwScreenMove(ScreenIds.Setting);		
		});	
};

/* region for Push message */

// init for push message
function initPushMessage() 
{
    $('#liPushMessage').click(
        function () {

            if ($(this).hasClass('show')) {
                $(this).removeClass('show').addClass('hide');
                $('#accordion').slideUp();
            }
            else {

                $('.notification-pushmessage').hide(); // hide notification
                $(this).removeClass('hide').addClass('show');

                currentPagePushMessage = 1;
                getPushMessageList();
            }
        }
    );

    // set default hide list message
    $('#liPushMessage').removeClass('show').addClass('hide');

        $('#prev-page-message').click(function (e) {
            previousPushMessageClick();
            e.stopPropagation();
            return false;
        });
        $('#next-page-message').click(function (e) {
            nextPushMessageClick();
            e.stopPropagation();
            return false;
        });

//        $('#list-push-message').click(
//            function (e) {

//                $('#liPushMessage').removeClass('show').addClass('hide');
//                $('#list-push-message').slideUp();

//                e.stopPropagation();
//                return false;
//            }
//        );

            $('.notification-pushmessage').click(
            function () {
                $(this).slideUp();
            }
        );

        // check new push message
            getPushMessageNew();
    };

// get time wait check new push message
function getTimeWaitCheckNewPushMessage() 
{    
    return avwSysSetting().pushTimePeriod * 1000;// time unit is seconds
}

// get message new
function getPushMessageNew() 
{
    //$('.notification-pushmessage').hide();
    var params = { "sid": ClientData.userInfo_sid()};
    avwCmsApi(ClientData.userInfo_accountPath(), "webPushMessageNew", "post", params,
        callbackGetPushMessageNewSuccess,
        function (xhr, b, c) { });
};

// callback get number new message success
function callbackGetPushMessageNewSuccess(data) {
    if (data) {        
        // get current number message in session
        var currentMessage = parseInt(ClientData.pushInfo_newMsgNumber());
        if (isNaN(currentMessage)) {
            currentMessage = 0;
        }
        var totalMessage = currentMessage + data.count;

        if ($('#liPushMessage').hasClass('hide')) {
            // update new number message to session
            ClientData.pushInfo_newMsgNumber(totalMessage);

            // only show number new message when total messages greater than 0
            if (totalMessage > 0) {
                // show current number message
                $('#numbermessage').html(totalMessage);
            }
            else $('#numbermessage').html('');
        }
        // show notification for new message
        if (data.count > 0)
        {
            $('.notification-pushmessage').html(i18nText("msgPushAlert")).slideDown();

            // auto off notification push message after timeWaitCloseNewInfoPushMessage
            setTimeout(function () {
                $('.notification-pushmessage').slideUp();

            }, timeWaitCloseNewInfoPushMessage);
        }
    }

    // continue check new push message
    setTimeout(getPushMessageNew, getTimeWaitCheckNewPushMessage());

};

// get message
function getPushMessageList() {

    var sysSettings = avwSysSetting();
    var pushPageCount=sysSettings.pushPageCount;

    var from = (currentPagePushMessage - 1) * pushPageCount + 1;
    var to = currentPagePushMessage * pushPageCount;

    var params = { "sid": ClientData.userInfo_sid(), "recordFrom": from, "recordTo": to };
    avwCmsApiSync(ClientData.userInfo_accountPath(), "webPushMessageList", "post", params,
                    function (data) {

                        // reset number message
                        ClientData.pushInfo_newMsgNumber(0);

                        // hide number new message
                        $('#numbermessage').html('');

                        showListPushMessage(data);
                    },
                    function (xhr, b, c) {
                        showSystemError();
                    });
};

// get string from date crate pushmessage

function getDateCreatePushMessage(data) {
    return (data.year + 1900) + "/" + (data.month + 1) + "/" + data.date + " " + data.hours + ":" + data.minutes;
}
// show push message list
function showListPushMessage(data)
{
    $('#show-push-message').html('');
    for (var i = 0; i < data.messageList.length && i <= (data.recordTo - data.recordFrom); i++) 
    {
        var titleMessage = truncate(data.messageList[i].messageDetail, 30).replace(/</g, '&lt;').replace(/>/g, '&gt;');
        var detailMessage = data.messageList[i].messageDetail.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
        var message = '<div class="newmsg">';
        message += '<h5 class="postItem"><a href="#">' + titleMessage + '</a></h5>';
        message += '<p>' + detailMessage + '<span class="date">' + getDateCreatePushMessage(data.messageList[i].messageSendDate) + '</span></p></div>';
        $('#show-push-message').append(message);
    }

    // hide all detail message
    $('#show-push-message .newmsg p').hide();

    // show list title message
    $('#accordion').slideDown();

    if (currentPagePushMessage > 1 || data.recordTo < data.totalRecord) {
        $('#accordion .pagechange').show();
    }
    else {
        $('#accordion .pagechange').hide();
    }

    // check show next button
    if (data.recordTo < data.totalRecord) {
        $('#next-page-message').show();
    }
    else {
        $('#next-page-message').hide();
    }

    // check show previous button 
    if (currentPagePushMessage > 1) {        
        $('#prev-page-message').css({ "visibility": "visible" });
    }
    else {
        $('#prev-page-message').css({ "visibility":"hidden"});
    }


    // show detail message when click at title
    $('#show-push-message .newmsg h5').click(
        function () {
            var isshow = !$(this).parent().find('p').is(':visible');
            $('#show-push-message .newmsg p').slideUp();
            if (isshow) {
                $(this).parent().find('p').slideDown();
            }
        }
    );
};

// load next page message
function nextPushMessageClick() {
    currentPagePushMessage++;
    getPushMessageList();
};

// load previous page message
function previousPushMessageClick() {
    if (currentPagePushMessage > 1)
        currentPagePushMessage--;
    else currentPagePushMessage = 1;
    getPushMessageList();
};

function truncate(strInput, length){
    if (strInput.length <= length)
    {
        return strInput;
    }
    else
    {
        return strInput.substring(0, length) + "...";
    }
};

function setStatusSort(currentid, isAsc) {
    $('#menu_sort li a').removeClass('descending_sort').removeClass('ascending_sort');
    
    if($('#menu_sort li a#off-default').size()){
        $('#menu_sort li a#off-default').addClass('descending_sort');
    }   
    
    $('#menu_sort li').removeClass('current');
    $(currentid).addClass(isAsc ? 'ascending_sort' : 'descending_sort').parent().addClass("current");
};

// get icon of content type
function getIconTypeContent(contentType) {

    var src = '';
    switch (contentType) {
        case ContentTypeKeys.Type_PDF:
            {
                src = 'img/bookshelf/icon_01.jpg';
                break;
            }
        case ContentTypeKeys.Type_Enquete:
            {
                src = 'img/bookshelf/icon_05.jpg';
                break;
            }
        case ContentTypeKeys.Type_Html:
            {
                src = 'img/bookshelf/icon_05.jpg';
                break;
            }
        case ContentTypeKeys.Type_Image:
            {
                src = 'img/bookshelf/icon_02.jpg';
                break;
            }
        case ContentTypeKeys.Type_Music:
            {
                src = 'img/bookshelf/icon_06.jpg';
                break;
            }
        case ContentTypeKeys.Type_NoFile:
            {
                src = 'img/bookshelf/icon_07.png';
                break;
            }
        case ContentTypeKeys.Type_Others:
            {
                src = 'img/bookshelf/icon_03.jpg';
                break;
            }
        case ContentTypeKeys.Type_Video:
            {
                src = 'img/bookshelf/icon_04.jpg';
                break;
            }
        default: break
    }
    return src;
};

// download resouce content id
function downloadResourceById(contentId){
    var params = {
        sid: ClientData.userInfo_sid(),
        contentId: contentId,
        getType: '2'
    };
    avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", "get", params,
            function (data) {
                //Get resourceurl
                var resourceUrl = getResourceByIdFromAPI(data.contentData.content.resourceId);

                // open url to download file
                if (isSafariNotOnIpad()) {
                    window.onbeforeunload = null;
                    window.open(resourceUrl, "_self"); // open url to download file on safari not for ipad
                    var toogleTime = setTimeout(function () { ToogleLogoutNortice() }, 200);
                }
                else {
                    window.open(resourceUrl); //open url to download file on orther browser
                }
            },
        function (xhr, b, c) { });
};

//Download resource
function getResourceByIdFromAPI(resourceId){
    return getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + resourceId + "&isDownload=true";
};

// check is browser safari on Mac and Window devide ( not Ipad )
function isSafariNotOnIpad() {
    if (!window.chrome) {
        var ua = navigator.userAgent.toLowerCase();
        if (!/ipad/.test(ua) && /safari/.test(ua)) {
            return true;
        }
    }
    return false;
};