
//名前空間用のオブジェクトを用意する
var HEADER = {};

HEADER.timeWaitCloseNewInfoPushMessage = 5000; // time wait close info new push message 5 seconds
HEADER.currentPagePushMessage = 1;
HEADER.isHoverOn = false;
HEADER.click = true;

$(document).ready(function () {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    //ログアウト時バックアップ確認パーツ読み込み
    $("#inc_backup").load("./inc_backup.html", function (myData, myStatus, xhr){
    	I18N.i18nReplaceText();
        $('#dlgConfirmBackup-backup').click(HEADER.confirmWithBackupFunction);
        $('#dlgConfirmBackup-withoutbackup').click(HEADER.confirmWithoutBackupFunction);
        $('#dlgConfirmBackup1').hide();
    });

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

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

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

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

    //init push message
    HEADER.initPushMessage();

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

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

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

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

});

HEADER.searchBoxHoverFunction = function(){
	HEADER.isHoverOn = true;
};

HEADER.searchBoxHoverOffFunction = function() {
	HEADER.isHoverOn = false;
};

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

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


HEADER.bodyClickFunction = function(event) {
    if (COMMON.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) {
                HEADER.isHoverOn = true;
            }
            else {
                HEADER.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())) {

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

HEADER.headerSearchBodyClickFunction = function() {

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

HEADER.headerSearchTagClickFunction = function() {

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

HEADER.headerSearchContentClickFunction = function() {

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


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

//Toggle Search Panel Click function
HEADER.toggleSearchPanel = function(){
    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();
	}
};

HEADER.overClick = function() {
	if (HEADER.click) {
        HEADER.click = !HEADER.click;
	   
	   // prevent clicking for 2 sec 
	   setTimeout(function () {
		HEADER.click = true;
	   }, 1000);
	   return false;

	} else {
	   return true;
	}
};

//Button Search Event function
HEADER.searchHeaderButtonFunction = function(){
	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();
    var count = 0;

    if(searchText.length > 200){
		alert('200字以下のテキストを入力してください');
		return;
    }

    if ($('#searchbox-key').val() != '　' && $('#searchbox-key').val() != '"or"' && $('#searchbox-key').val() != '"OR"' && $('#searchbox-key').val() != '"Or"'&& $('#searchbox-key').val() != '"oR"') {
		try{
			//seperate string 
			var myRegexp = /[^\s"]+|"([^"]*)"/gi;
			var myArray = [];
			var myQuery;
			//var myRegExpArr = [];
            var textReg = $('#searchbox-key').val().replace(/\(/g," ( ").replace(/\)/g," ) ");
            var dummyArray = [];
            var dummytextReg = $('#searchbox-key').val().replace(/\"/g,"'\"'");
            
            do {
				var match = myRegexp.exec(dummytextReg);
				if (match != null)
				{
					dummyArray.push(match[1] ? match[1] : match[0]);
				}
			} while (match != null);

			do {
				var match = myRegexp.exec(textReg);
				if (match != null)
				{
					myArray.push(match[1] ? match[1] : match[0]);
				}
			} while (match != null);

			for(var i = 0; i < myArray.length; i++){
				if(myArray[i] != "OR" && myArray[i] != "or" && myArray[i] != "Or" && myArray[i] != "oR" && myArray[i] != "(" && myArray[i] != ")"){
					count++;
				}
			}

            if(count > 5){
				alert('語句数は最大5つです');
				return;        
			}
			if(myArray[0].charAt(0) == "("){
				if(myArray[0]  == "("){
					//myRegExpArr[1] = new RegExp(myArray[1]);
					myQuery = '(';
				}else{
					//myRegExpArr[0] = new RegExp(myArray[0].slice(1));
					myQuery = '(';
				}
			}else{
				//myRegExpArr[0] = new RegExp(myArray[0]);
                myQuery = 'true';
                if(myArray[0] == "OR" || myArray[0] == "or" || myArray[0] == "Or" || myArray[0] == "oR"){
					myQuery = ' || ';
				}
			}
			for (var i = 1; i < myArray.length; i++){
				if(myArray[i] == "OR" || myArray[i] == "or" || myArray[i] == "Or" || myArray[i] == "oR"){
					//myRegExpArr[i] = new RegExp(myArray[i]);
				}else if(myArray[i].charAt(0) == "(" || myArray[i] == "("){
					if(myArray[i]  == "("){
						if(myArray[i - 1] == "OR" || myArray[i - 1] == "or" || myArray[i - 1] == "Or" || myArray[i - 1] == "oR"){
							myQuery += ' || (';
						}else if(myArray[i - 1] != "("){
							myQuery += ' && (';
						}else{
							myQuery += ' (';
						}
					}else{
						if(myArray[i - 1] == "OR" || myArray[i - 1] == "or" || myArray[i - 1] == "Or" || myArray[i - 1] == "oR"){
							//myRegExpArr[i] = new RegExp(myArray[i].slice(1));
							myQuery += ' || ( true';
						}else if(myArray[i - 1] != "("){
							//myRegExpArr[i] = new RegExp(myArray[i].slice(1));
							myQuery += ' && ( true';
						}else{
							myQuery += ' ( true';
						}
					}
				}else if(myArray[i].charAt(myArray[i].length - 1) == ")" || myArray[i]  == ")"){
					if(myArray[i]  == ")"){
						myQuery += ' )';
					}else{
						if(myArray[i - 1] == "OR" || myArray[i - 1] == "or" || myArray[i - 1] == "Or" || myArray[i - 1] == "oR"){
							//myRegExpArr[i] = new RegExp(myArray[i].slice(0, -1));
							myQuery += ' || true )';
						}else{
							//myRegExpArr[i] = new RegExp(myArray[i].slice(0, -1));
							myQuery += ' && true )';
						}
					}
				}else{
					if(myArray[i - 1] == "OR" || myArray[i - 1] == "or" || myArray[i - 1] == "Or" || myArray[i - 1] == "oR"){
						//myRegExpArr[i] = new RegExp(myArray[i]);
						myQuery += ' || true';   
					}else{
						if(myArray[i - 1] == "("){
							//myRegExpArr[i] = new RegExp(myArray[i]);
							myQuery += ' true';    
						}else{
							//myRegExpArr[i] = new RegExp(myArray[i]);
							myQuery += ' && true';    
						}
					}
				}
			}
            if(searchText == ")"){
                myQuery += ' &&';
            }

            for(var i = 0; i < dummyArray.length; i++){
				if(dummyArray[i].indexOf(")(") > 0 && dummyArray[i].charAt(0) != "'" && dummyArray[i].charAt(dummyArray.length - 1) != "'"){
					myQuery += ' &&';
				}
			}

            if (eval(myQuery)) {
				//is not correct query
			}

        }catch(error){
            if(content == 'checked')
            {
                searchDivision = $('#searchbox-content').val();
            }
            if(tag == 'checked')
            {
                searchDivision = $('#searchbox-tag').val();
            }
            if(body == 'checked')
            {
                searchDivision = $('#searchbox-body').val();
            }
            if(count > 5){
				alert('語句数は最大5つです');
				return;        
            }		

            ClientData.searchCond_searchText("invaildsearchtextzeroresultfound");
            ClientData.searchCond_searchDivision(searchDivision);
            ClientData.searchCond_searchText_Dummy(searchText);
            //window.location = COMMON.ScreenIds.ContentSearch;
            AVWEB.avwScreenMove(COMMON.ScreenIds.ContentSearch);
            return;
        }
    }

    if(count > 5){
        alert('語句数は最大5つです');
        return;        
    }

    if(HEADER.overClick()){
		return;
	}
    
	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_searchText_Dummy(searchText);
	ClientData.searchCond_searchDivision(searchDivision);
	//window.location = COMMON.ScreenIds.ContentSearch;
	AVWEB.avwScreenMove(COMMON.ScreenIds.ContentSearch);
};

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

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

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

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

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

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

//Logout function
HEADER.logoutFunction = function() {

    // 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 });
                COMMON.lockLayout();
                $('#dlgConfirmBackup1').show();
                $('#dlgConfirmBackup1').center();

                // check disabled button backup
                HEADER.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 });
                    COMMON.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;

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

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

//Web Logout Event
HEADER.webLogoutEvent = function(){

    var isExisted = false;

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

    AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webLogout", "GET", params,
                    function (data) {
                        isExisted = true;
                        SessionStorageUtils.clear();
                        AVWEB.avwUserSetting().remove(COMMON.Keys.userInfo_sid);
                        AVWEB.avwUserSetting().remove(COMMON.Keys.userInfo_sid_bak);
                        // Move to login screen
                        //window.location = COMMON.ScreenIds.Login;
                        AVWEB.avwScreenMove(COMMON.ScreenIds.Login);
                    },
                    function (xmlHttpRequest, txtStatus, errorThrown) {
                        if (xmlHttpRequest.status == 403) {
                            isExisted = false;
                        }
                        else {
                            // Show system error
                            isExisted = true;
                        }
                    });

    return isExisted;
};

//Logout Without Backup function
HEADER.confirmWithoutBackupFunction = function(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 = COMMON.ScreenIds.Login;
	HEADER.webLogoutEvent();
};

//Logout With Backup function
HEADER.confirmWithBackupFunction = function(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');
	COMMON.unlockLayout();
	$('#dlgConfirmBackup1').css('z-index', '99');
	COMMON.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);

        HEADER.DoBackup(isBackupMarking, isBackupMemo, isBackupBookmark, true);
	}
	else{
		ClientData.userOpt_bkConfirmFlg(1);  // Show dialog in next time
		HEADER.DoBackup(isBackupMarking, isBackupMemo, isBackupBookmark, true);
	}

	ClientData.userOpt_logoutMode(0);  // In next time, if choose: [do not show dialog], will backup and logout
	//HEADER.webLogoutEvent();
};
//Confirm Back Up Ok
HEADER.DoBackup = function(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' }
//    ];
//        AVWEB.avwUploadBackupFile(ClientData.userInfo_accountPath(), params, false,
//                        function (data) {
//                            if (JSON.parse(data).result == "success") {
//                                ClientData.isChangedBookmark(false);
//                                ClientData.isChangedMarkingData(false);
//                                ClientData.isChangedMemo(false);
//                                //alert(I18N.i18nText('msgBackupSuccess'));
//
//                               // Show message: msgBackupSuccess
//                               $().toastmessage({ position: 'middle-center' });
//                               $().toastmessage('showToast', {
//                                   type: 'success',
//                                   sticky: true,
//                                   text: I18N.i18nText('msgBackupSuccess'),
//                               });
//                               $('.toast-position-middle-center').css('width', '500px');
//                               $('.toast-position-middle-center').css('margin-left', '-250px');
//                               $('.toast-item-close').live('click', HEADER.webLogoutEvent);
//                            }
//                            else {
//                                //alert(I18N.i18nText('msgBackupFailed'));
//                               // Show error message: msgBackupFailed
//                               $().toastmessage({ position: 'middle-center' });
//                               $().toastmessage('showToast', {
//                                   type: 'error',
//                                   sticky: true,
//                                   text: I18N.i18nText('msgBackupFailed')
//                               });
//                               $('.toast-position-middle-center').css('width', '500px');
//                               $('.toast-position-middle-center').css('margin-left', '-250px');
//                               $('.toast-item-close').live('click', HEADER.webLogoutEvent);
//                            }
//                        },
//                        function (a, b, c) {
//                            //alert(I18N.i18nText('msgBackupFailed'));
//                           // Show error message: msgBackupFailed
//                           $().toastmessage({ position: 'middle-center' });
//                           $().toastmessage('showToast', {
//                               type: 'error',
//                               sticky: true,
//                               text: I18N.i18nText('msgBackupFailed')
//                           });
//                           $('.toast-position-middle-center').css('width', '500px');
//                           $('.toast-position-middle-center').css('margin-left', '-250px');
//                           $('.toast-item-close').live('click', HEADER.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) {
            COMMON.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 = HEADER.sendSignalBackupStart(2); // start backup type marking
                if (isBackupMarkingOK) {
                    isBackupMarkingOK = HEADER.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'>" + I18N.i18nText('txtBkMarking') + " " + I18N.i18nText('msgBackupSuccess') + "</div>");
                    }
                    // finish backup marking if start backup marking success
                    HEADER.sendSignalBackupFinish(2);
                }
                if (!isBackupMarkingOK) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + I18N.i18nText('txtBkMarking') + " " + I18N.i18nText('msgBackupFailed') + "</div>");
                }
            }

            // Backup bookmark
            if (isBackupBookmark && ClientData.isChangedBookmark() == true) {
                isBackupBookmarkOK = HEADER.sendSignalBackupStart(4); // start backup type bookmark
                if (isBackupBookmarkOK) {
                    isBackupBookmarkOK = HEADER.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'>" + I18N.i18nText('txtBkShiori') + " " + I18N.i18nText('msgBackupSuccess') + "</div>");
                    }
                    // finish backup bookmark if start backup bookmark ok
                    HEADER.sendSignalBackupFinish(4);
                }
                if (!isBackupBookmarkOK) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + I18N.i18nText('txtBkShiori') + " " + I18N.i18nText('msgBackupFailed') + "</div>");
                }
            }

            // Backup Memo

            if (isBackupMemo && ClientData.isChangedMemo() == true) {
                isBackupMemoOK = HEADER.sendSignalBackupStart(1); // start backup type memo
                if (isBackupMemoOK) {
                    isBackupMemoOK = HEADER.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'>" + I18N.i18nText('txtBkMemo') + " " + I18N.i18nText('msgBackupSuccess') + "</div>");
                    }
                    // finish backup memo if start backup memo ok
                    HEADER.sendSignalBackupFinish(1);
                }
                if (!isBackupMemoOK) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + I18N.i18nText('txtBkMemo') + " " + I18N.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', HEADER.webLogoutEvent);
            }

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

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

HEADER.backupFile = function(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' }
    ];
    AVWEB.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
HEADER.sendSignalBackupStart = function(typeBackup)
{
    var result = false;
    var params = { "sid": ClientData.userInfo_sid(), "fileType": typeBackup };
    AVWEB.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
HEADER.sendSignalBackupFinish = function(typeBackup)
{
    var result = false;
    var params = { "sid": ClientData.userInfo_sid(), "fileType": typeBackup };
    AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "notifyBackupFinish", "post", params,
                    function (data) {
                        if (data.result == "success") {
                            result = true;
                        }
                    },
                    function (xhr, b, c) { });
    return result;
};

/* ------ */

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

HEADER.showErrorScreenForceChangePassword = function(){
	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>'+I18N.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(COMMON.ScreenIds.Setting);
			AVWEB.avwScreenMove(COMMON.ScreenIds.Setting);
		});
};

/* region for Push message */

// init for push message
HEADER.initPushMessage = function()
{
    $('#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');

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

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

        $('#prev-page-message').click(function (e) {
            HEADER.previousPushMessageClick();
            e.stopPropagation();
            return false;
        });
        $('#next-page-message').click(function (e) {
            HEADER.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
        if (COMMON.isAnonymousLogin() == false ) {
        	if((ClientData.serviceOpt_apns() == 'Y') || (ClientData.serviceOpt_usable_push_message() == 'Y')) {
        		 HEADER.getPushMessageNew();
            }

        }
    };

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

// get message new
HEADER.getPushMessageNew = function()
{
	//ロック中かビューア画面ならチェックしない
	if ($("#viewer").length) {
		//表示状態か
		if( $('#viewer').is(':visible')){
			return;
		}
	}
	//$('.notification-pushmessage').hide();
	var params = {
			"sid": ClientData.userInfo_sid()
	};
	AVWEB.avwCmsApi(
			ClientData.userInfo_accountPath(),
			"webPushMessageNew",
			"post",
			params,
			HEADER.callbackGetPushMessageNewSuccess,
			function (xhr, b, c) { }
	);
};

// callback get number new message success
HEADER.callbackGetPushMessageNewSuccess = function(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(I18N.i18nText("msgPushAlert")).slideDown();

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

            }, HEADER.timeWaitCloseNewInfoPushMessage);
        }
    }

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

};

// get message
HEADER.getPushMessageList = function() {

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

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

    var params = {
    		"sid": ClientData.userInfo_sid(),
    		"recordFrom": from,
    		"recordTo": to
    };
    AVWEB.avwCmsApiSync(
    		ClientData.userInfo_accountPath(),
    		"webPushMessageList",
    		"post",
    		params,
    		function (data) {
    			// reset number message
    			ClientData.pushInfo_newMsgNumber(0);
    			// hide number new message
    			$('#numbermessage').html('');
    			HEADER.showListPushMessage(data);
    		},
    		function (xhr, b, c) {
    			AVWEB.showSystemError();
    		}
    );
};

// get string from date crate pushmessage

HEADER.getDateCreatePushMessage = function(data) {
	var flagMonth = "";
	var flagDate = "";
	var flagHours = "";
	var flagMinutes = "";
	if((data.month >=1) && (data.month <= 9)) {
		flagMonth = "0";
	}
	if((data.date >=1) && (data.date <= 9)) {
		flagDate = "0";
	}
	if((data.hours >=1) && (data.hours <= 9)) {
		flagHours = "0";
	}
	if((data.minutes >=1) && (data.minutes <= 9)) {
		flagMinutes = "0";
	}

    return (data.year + 1900) + "/" + flagMonth +(data.month + 1) + "/" + flagDate + data.date + " " + flagHours + data.hours + ":" + flagMinutes + data.minutes;
};
// show push message list
HEADER.showListPushMessage = function(data)
{
    $('#show-push-message').html('');
    for (var i = 0; i < data.messageList.length && i <= (data.recordTo - data.recordFrom); i++)
    {
        var titleMessage = COMMON.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">' + HEADER.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 (HEADER.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 (HEADER.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
HEADER.nextPushMessageClick = function() {
    HEADER.currentPagePushMessage++;
    HEADER.getPushMessageList();
};

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

HEADER.setStatusSort = function(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
HEADER.getIconTypeContent = function(contentType) {

    var src = '';
    switch (contentType) {
        case COMMON.ContentTypeKeys.Type_PDF:
            {
                src = 'img/bookshelf/icon_01.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_Enquete:
            {
                src = 'img/bookshelf/icon_09.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_Exam:
        	{
	            src = 'img/bookshelf/icon_10.png';
	            break;
        	}
        case COMMON.ContentTypeKeys.Type_Html:
            {
                src = 'img/bookshelf/icon_05.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_Image:
            {
                src = 'img/bookshelf/icon_02.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_Music:
            {
                src = 'img/bookshelf/icon_06.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_NoFile:
            {
                src = 'img/bookshelf/icon_07.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_Others:
            {
                src = 'img/bookshelf/icon_03.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_Video:
            {
                src = 'img/bookshelf/icon_04.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_Link:
            {
                src = 'img/bookshelf/icon_08.png';
                break;
            }
        case COMMON.ContentTypeKeys.Type_PanoMovie:
	        {
	            src = 'img/bookshelf/icon_11.png';
	            break;
	        }
        case COMMON.ContentTypeKeys.Type_PanoImage:
		    {
		        src = 'img/bookshelf/icon_12.png';
		        break;
		    }
        case COMMON.ContentTypeKeys.Type_ObjectVR:
		    {
		        src = 'img/bookshelf/icon_13.png';
		        break;
		    }
        default: break;
    }
    return src;
};

// download resouce content id
HEADER.downloadResourceById = function(contentId){
    var params = {
        sid: ClientData.userInfo_sid(),
        contentId: contentId,
        getType: '2'
    };
    AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", "get", params,
    		function (data) {
    			//Get resourceurl
    			if( data.contentData.content ){
    				var resourceUrl = HEADER.getResourceByIdFromAPI(data.contentData.content.resourceId, contentId);
    				// open url to download file
    				if (HEADER.isSafariNotOnIpad()) {
    					window.onbeforeunload = null;
    					window.open(resourceUrl, "_self"); // open url to download file on safari not for ipad
    					var toogleTime = setTimeout(function () { COMMON.ToogleLogoutNortice(); }, 200);
    				}
    				else {
    					window.open(resourceUrl); //open url to download file on orther browser
    				}
    			} else {
    				alert("ダウンロード出来ません。");
    			}
    		},
    		function (xhr, b, c) { }
    );
};

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

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

//link content
HEADER.viewLinkContentById = function(contentId){
    var params = {
        sid: ClientData.userInfo_sid(),
        contentId: contentId,
        getType: '2'
    };
    AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", "get", params,
            function (data) {
                //Get linkUrl
                var linkUrl = data.contentData.content.url;
                if( !linkUrl ){
                    return;
                }

                window.open(linkUrl, "_blank", "new window, scrollbars=yes");

                /*
                //httpで始まる場合は別ウィンドウで開く
                if (linkUrl.toLowerCase().indexOf('http') === 0) {
                    window.open(linkUrl, "_blank", "new window, scrollbars=yes");
                }
                else if( linkUrl.toLowerCase().indexOf('mailto') === 0 ){
                    //window.open(linkUrl, "_self");
                    location.href=linkUrl;
                }
                else {
                    // open url to download file
                    if (HEADER.isSafariNotOnIpad()) {
                        window.onbeforeunload = null;
                        window.open(linkUrl, "_self"); // open url to download file on safari not for ipad
                        var toogleTime = setTimeout(function () { COMMON.ToogleLogoutNortice() }, 200);
                    }
                    else {
                        window.open(linkUrl); //open url to download file on orther browser
                    }
                }
                */
            },
        function (xhr, b, c) { });
};

// get ThumbnailForOtherType
HEADER.getThumbnailForOtherType = function(contentType){

    var src = '';
    if(contentType == COMMON.ContentTypeKeys.Type_Image){
        src = COMMON.ThumbnailForOtherType.Thumbnail_ImageType;
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Music){
        src = COMMON.ThumbnailForOtherType.Thumbnail_MusicType;
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Video){
        src = COMMON.ThumbnailForOtherType.Thumbnail_VideoType;
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_NoFile){
        src = COMMON.ThumbnailForOtherType.Thumbnail_NoFileType;
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Others){
        src = COMMON.ThumbnailForOtherType.Thumbnail_OthersType;
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Html){
        src = COMMON.ThumbnailForOtherType.Thumbnail_HtmlType;
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Link){
        src = COMMON.ThumbnailForOtherType.Thumbnail_LinkType;
    }

    return src;
};

