/// <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 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);

    //Go To Login Page
    $('#dspLogout').click(logoutFunction);

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

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

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

    //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);

    //$('*').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;
};

function bodyClickFunction(event) {
    if (isTouchDevice()) {
        
        // Check mouse is in rectangle of searching panel
        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;
            }
            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;
                $('#header-searchbox').hide();
            }
        }
        
    }
    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")) {
			$('div#header-searchbox').slideDown('slow');
	} 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() {

    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();
            }
            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
                    	lockLayout();
                        DoBackup();
                    }
                    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();
	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
		DoBackup();
	}
	else{
		ClientData.userOpt_bkConfirmFlg(1);  // Show dialog in next time
		DoBackup();
	}
	
	ClientData.userOpt_logoutMode(0);  // In next time, if choose: [do not show dialog], will backup and logout
	//webLogoutEvent();
};

//Confirm Back Up Ok
function DoBackup() {
    // ----------------------------
    // 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);
                        });
};



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( {
			'color': '#fff',
			'opacity': 1,
			'position': 'fixed',
			'top': '0',
			'left': '0',
			'width': $(window).width(),
			'height': $(window).height(),
			'background': '#ccc',
			'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);		
		});	
};
