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

/// <reference path="../common/js/common.js" />

/// <reference path="contentview_VarDef.js" />

/// <reference path="contentview_CallApi.js" />

/// <reference path="contentview_GetData.js" />

/// <reference path="contentview_InitObjects.js" />


/* add memo click */
function handleAddMemo(event) {
    
    if (ClientData.IsAddingMemo() == true) {
        ClientData.IsAddingMemo(false);
        isCopyMemo = false;

        /* draw memo */
        drawMemoOnScreen();
        
        //Start Function : No.4
        if(getContent().hasNextPage()){
            drawMemoOnScreen(1);
        }
        
        if(getContent().hasPreviousPage()){
            drawMemoOnScreen(2);
        }
        //End Function : No.4
        
        //Start Function : No.4
        if(getContent().hasNextPage()){
            drawMemoOnScreen(1);
        }
        
        if(getContent().hasPreviousPage()){
            drawMemoOnScreen(2);
        }
        //End Function : No.4
        //change class
        $('#imgaddmemo').removeClass();
        $('#imgaddmemo').addClass('memoAdd');

    } 
    else {

        ClientData.IsDisplayMemo(true);
        ClientData.IsAddingMemo(true);
        isCopyMemo = false;

        /* draw memo */
        drawMemoOnScreen();
        //Start Function : No.4
        if(getContent().hasNextPage()){
            drawMemoOnScreen(1);
        }
        
        if(getContent().hasPreviousPage()){
            drawMemoOnScreen(2);
        }
        //End Function : No.4
        //change class
        $('#imgmemo').removeClass();
        $('#imgmemo').addClass('memoDisplay_hover');

        $('#imgaddmemo').removeClass();
        $('#imgaddmemo').addClass('memoAdd_hover');

        if (ClientData.memo_copyText()) {
            $("#overlay").show();
            $('#boxAddMemo').css('z-index', '101');
            $('#boxAddMemo').css('display', 'block');
            $('#boxAddMemo').draggable({ handle: "h1" });
            $("#boxAddMemo").offset({ left: event.pageX, top: event.pageY });
            $("#divAddMemo").show();
            $("#divAddMemo").offset({ left: event.pageX, top: (event.pageY + $('#bookmarkBoxHdMemo').height() - 2) });
        }
    }
};

/* Marking toolbar*/
function imgmarking_click() {
    
    if (ClientData.IsDisplayMarking() == false) {
        ClientData.IsDisplayMarking(true);
        
        
        drawCanvas();
        
        //Start Function : No.4
        if(getContent().hasNextPage()){
             drawCanvas(1);
        }
        
        if(getContent().hasPreviousPage()){
             drawCanvas(2);
        }

        //End Function : No.4
        $("#dlgMarking").hide();

        // change class
        /*$('#imgmarking').removeClass();
        $('#imgmarking').addClass('marking_hover');*/
    } else {
        ClientData.IsDisplayMarking(false);
        ClientData.IsAddingMarking(false);
        $('#draw_canvas').css('display', 'none');

        /*// change class
        $('#imgmarking').removeClass();
        $('#imgmarking').addClass('marking');*/

        drawCanvas();
        
        //Start Function : No.4
        if(getContent().hasNextPage()){
             drawCanvas(1);
        }
        
        if(getContent().hasPreviousPage()){
             drawCanvas(2);
        }
    }
        //End Function : No.4

};


/* event for list bookmark: changePageNo */
function clickBookmark() {
    
    var targetPageIndex = $(this).attr('id');
    
    if(targetPageIndex != getPageIndex()){
        changePage(targetPageIndex);
    }
    
    /* close popup */
    // $('#divListBookmark').dialog("close");
    $("#overlay").hide();

    $('#listbookmark').removeClass();
    $('#listbookmark').addClass('bmList');

    $("#divListBookmark").hide();
    $('#boxBookMark').css('display', 'none');
};

/* event close list bookmark box */
function closeBookmarkBox() {
    $("#divListBookmark").hide();
    isSendingData = false;
    $('#boxBookMark').css('display', 'none');
    isDisplayBookMarkList = false;

    /* unlock dialog overlay */
    $("#overlay").hide();

    //change class
    $('#listbookmark').removeClass();
    if (isTouchDevice() == true) {
        $('#listbookmark').addClass('bmList_device');
    } else {
        $('#listbookmark').addClass('bmList');
    }

};


/*event click show dialog bookmark */
function showListBookMark(e) {
    var array = [e.pageX, e.pageY];
    isDisplayBookMarkList = true;

    //change class
    $('#listbookmark').removeClass();
    $('#listbookmark').addClass('bmList_hover');

    /* display dialog overlay */
    $("#overlay").show();

    getBookmarklist(array);
};

/*event click show dialog index*/
function showListPageIndex(e) {
    isDisplayListIndex = true;
    var array = [e.pageX, e.pageY];
    getPageIndexJson(array);

    //change class
    $('#listindex').removeClass();
    $('#listindex').addClass('index_hover');

    /* display dialog overlay */
    $("#overlay").show();
};

/* event close list bookmark box */
function closeIndexBox() {
    isDisplayListIndex = false;
    $("#divListIndex").hide();
    $('#boxIndex').css('display', 'none');

    //change class
    $('#listindex').removeClass();
    if (isTouchDevice() == true) {
        $('#listindex').addClass('index_device');
    } else {
        $('#listindex').addClass('index');
    }

    /* unlock dialog overlay */
    $("#overlay").hide();
};

/* event click on list index */
function listIndex_Callback(selectedNode) {
    var node = new TreeNode();
    node = selectedNode;

    // Hide dialog index
    $("#divListIndex").dialog('close');

    changePage(node.Value - 1);
};

/*event click show copy text */
function showCopyText(e) {
    /* display dialog overlay */
    if (avwUserEnvObj.os == "android") {
        copyText();
    } else {
        isDisplayCopyText = true;
        //change class
        $('#copytext').removeClass();
        $('#copytext').addClass('copy_hover');
        $("#overlay").show();
        var array = [e.pageX, e.pageY];
        var contentPage = dataWebContentPage.pages;
        handleCopyTextData(contentPage, array)
    }
};

/* event close copy text box */
function closeCopyTextBox() {
    isDisplayCopyText = false;
    $("#divCopyText").hide();
    $('#boxCopyText').css('display', 'none');

    //change class
    $('#copytext').removeClass();
    if (isTouchDevice() == true) {
        $('#copytext').addClass('copy_device');
    } else {
        $('#copytext').addClass('copy');
    }

    /* unlock dialog overlay */
    $("#overlay").hide();
};


/*event click show dialog search*/
function showListSearchResult() {
    $('#txtSearch').keydown(function (e) {
        if (e.keyCode == 13) {
            searchHandle();

            /* display dialog overlay */
            //$("#overlay").show();
            return false;
        }
    });
};

/* event close searching result box */
function closeSearchingBox() {
    isSendingData = false;
    $("#divSearchResult").hide();
    $('#boxSearching').css('display', 'none');

    /* unlock dialog overlay */
    //$("#overlay").hide();
};


/* event for list search results */
function clickSearchDetail() {
    // Hide dialog
    $("#divSearchResult").dialog('close');
    changePage($(this).attr('id'));
};

//Start: Function : No.4 - Editor : Long - Date : 08/09/2013 - Summary : 
/* event next page */
function nextPage_click() {
    
    if (getContent().hasNextPage()) {
        playBGMOfContent();
        playBGMOfPage(getPageIndex() + 1); 
           
        isLoadingObject = true;   
        cancelClick = true;
        
        disableAllControl();       
        $('#divImageLoading').css('display', 'block');
        
        var tran = new Transition();
        createLockLayout(true);
        tran.flipNextPage();

    }
};


/* event prev page */
function prevPage_click() {
    
    if (getContent().hasPreviousPage()) {
        playBGMOfContent();
        playBGMOfPage(getPageIndex() - 1);
        
        isLoadingObject = true;   
        cancelClick = true;
        
        disableAllControl();
        $('#divImageLoading').css('display', 'block');
        
        var tran = new Transition();
        createLockLayout(true);
        tran.flipPreviousPage();
        
    }
};
//End: Function : No.4 - Editor : Long - Date : 08/09/2013 - Summary : 
/* event first page */
function firstPage_click() {
    if (getContent().pageIndex != 0) {
        
        if(getContent().pageIndex == 1){
            prevPage_click();
        }
        else{
            playBGMOfContent();
            playBGMOfPage(0);
    
            disableAllControl();
    
            $('#divImageLoading').css('display', 'block');
    
            // Clear canvas offscreen
            clearCanvas(document.getElementById("offscreen"));
    
            if(contentType == ContentTypeKeys.Type_PDF){
                avwGrabContentPageImage(ClientData.userInfo_accountPath(),
                     { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: 1 , pid: pid},
                     function (data) {
                         pageImages = data;
        
                         /* get page Objects */
                         getPageObjectsByPageIndex(pageObjectsData, 0);
                         getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);
        
                         $('#divImageLoading').css('display', 'none');
                         //START TRB00097
                         //userScale = 1;
                         
                         //changeScale(userScale);
                         //END TRB00097
                         checkDisableButtonZoom();
                         var tran = new Transition();
                         tran.flipToPage(0);
        
                     },
                     function (xmlHttpRequest, txtStatus, errorThrown) {
                         showErrorScreen();
                     });
            }
            //START : TRB00032 - Editor : Long - Date: 09/10/2013 - Summary : type none process
            else if(contentType == ContentTypeKeys.Type_NoFile){
                getPageObjectsByPageIndex(pageObjectsData, 0);
                getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);

                $('#divImageLoading').css('display', 'none');
                 
                 //START TRB00097
                 //userScale = 1;
                 
                 //changeScale(userScale);
                 //END TRB00097
                checkDisableButtonZoom();
                var tran = new Transition();
                tran.flipToPage(0);
            }
            //END : TRB00032 - Editor : Long - Date: 09/10/2013 - Summary : type none process
            
        }                
    }
};

/* event last page */
function lastPage_click() {
    if (getContent().pageIndex != (totalPage - 1)) {
        
        if(getContent().pageIndex == totalPage - 2){
            nextPage_click();
        }
        else{
            playBGMOfContent();
            playBGMOfPage(totalPage - 1);
    
            disableAllControl();
    
            $('#divImageLoading').css('display', 'block');
    
            // Clear canvas offscreen
            clearCanvas(document.getElementById("offscreen"));
    
            //pageImages = getURLPageImage("webContentPageImage") + "?contentId=" + contentID + "&sid=" + ClientData.userInfo_sid() + "&pageNo=" + (totalPage - 1);
            
            if(contentType == ContentTypeKeys.Type_PDF){
                avwGrabContentPageImage(ClientData.userInfo_accountPath(),
                     { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: totalPage, pid: pid },
                     function (data) {
                         pageImages = data;
        
                         /* get page Objects */
                         getPageObjectsByPageIndex(pageObjectsData, totalPage - 1);
                         getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);
        
                         $('#divImageLoading').css('display', 'none');
                         
                         checkDisableButtonZoom();
                         var tran = new Transition();
                         tran.flipToPage(totalPage - 1);
        
                     },
                     function (xmlHttpRequest, txtStatus, errorThrown) {
                         showErrorScreen();
                     });
            }
            //START : TRB00032 - Editor : Long - Date: 09/10/2013 - Summary : type none process
            else if(contentType == ContentTypeKeys.Type_NoFile){
                 getPageObjectsByPageIndex(pageObjectsData, totalPage - 1);
                 getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);

                 $('#divImageLoading').css('display', 'none');
                 
                 checkDisableButtonZoom();
                 var tran = new Transition();
                 tran.flipToPage(totalPage - 1);
            }
            //END : TRB00032 - Editor : Long - Date: 09/10/2013 - Summary : type none process

        }        
    }

};

function createLockLayout(opt){
         
    if(opt == true){       
        if(!$('#locking').size()){
            var $html = $('<div id="locking" style="z-index: 100; position: absolute; height: 100%; width: 100%; background: white; opacity: 0 "></div>');        
              
            $('#wrapper').append($html);
            $html.show();
            
            $('#locking').live('click', function(event){ event.preventDefault(); });
        }
        else{
            $('#locking').show();
        }
               
    }
    else{
       //$('body').append($html);
       if($('#locking').size()){
            $('#locking').hide();
            $('#locking').remove();    
       }   
    }          
};

//START TRB00049 - Editor: Long - Date: 09/26/2013 - Summary : Add short key alt 
var altMode = false;

/* handle keydown */
$(document).keydown(function (e) {
    /* set fag true when click ctrl */
    if (e.ctrlKey) {
        ctrlMode = true;
    }
    
    if(e.altKey){
        altMode = true;
    }

    /* set hot key */
    if (ctrlMode == true && altMode == false) {
        if (ClientData.IsAddingMarking() == true || isLoadingObject == true) {
            /* do nothing*/
        } else {
            switch (e.keyCode) {
                /* move page */ 
                case ShortKeys.MovePrevious: /* move prev */
                    if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_NoFile){
                        if (getContent().hasPreviousPage()) {
                            prevPage_click();
                        }
                    }               
                    break;
                case ShortKeys.MoveNext: /* move next */
                    if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_NoFile){
                        if (getContent().hasNextPage()) {
                            nextPage_click();
                        }
                    }

                    break;

                /* zoom */ 
                case ShortKeys.ZoomIn: /* zoomIn */
                    if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                        || contentType == ContentTypeKeys.Type_NoFile){
                        zoomIn();
                    }
                    
                    break;
                case ShortKeys.ZoomOut: /* zoomOut */
                    if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                        || contentType == ContentTypeKeys.Type_NoFile){
                        zoomOut();
                    }
                    
                    break;
                case ShortKeys.ZoomFit: /* screenFit*/
                    if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                        || contentType == ContentTypeKeys.Type_NoFile){
                        screenFit();
                    }                   
                    break;

                /* marking && toolbar */ 
                case ShortKeys.ShowHideToolbar: /* handle toolbar */
                    if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                        || contentType == ContentTypeKeys.Type_NoFile){
                        handleDisplayToolbar();
                    }
                    else{
                        if(isZoomingContent){
                            originalScreenForNotPdfType();
                        }
                        else{
                            fullScreenForNotPdfType();
                        }
                    }
                    
                    break;
                case ShortKeys.ShowHideMarking: /* hide marking */
                   if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                            || contentType == ContentTypeKeys.Type_NoFile){
                            imgmarking_click();
                    }
                    
                    break;
            }
        }
    }
    
    if(altMode == true && ctrlMode == false){
        if (ClientData.IsAddingMarking() == true || isLoadingObject == true) {
            /* do nothing*/
        } 
        else {
            switch (e.keyCode) {
                /* zoom */ 
                case ShortKeys.ZoomInAlt: /* zoomIn */
                    if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                        || contentType == ContentTypeKeys.Type_NoFile){
                        zoomIn();
                    }                    
                    break;
                case ShortKeys.ZoomOutAlt: /* zoomOut */
                    if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                        || contentType == ContentTypeKeys.Type_NoFile){
                        zoomOut();
                    }                   
                    break;
                case ShortKeys.ZoominAlt_Firefox: /* zoomIn */
                    if(avwUserEnvObj.browser == 'firefox'){
                        if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                            || contentType == ContentTypeKeys.Type_NoFile){
                            zoomIn();
                        } 
                    }                   
                    break;
                case ShortKeys.ZoomOutAlt_Firefox: /* zoomOut */
                    if(avwUserEnvObj.browser == 'firefox'){
                        if(contentType == ContentTypeKeys.Type_PDF || contentType == ContentTypeKeys.Type_Image
                            || contentType == ContentTypeKeys.Type_NoFile){
                            zoomOut();
                        }       
                    }            
                    break;
            }
        }
    }
});

/* handle keydown */
$(document).keyup(function (e) {
    ctrlMode = false;
    altMode = false;
});
//END TRB00049 - Editor: Long - Date: 09/26/2013 - Summary : Add short key alt

//START TRB - Editor : Long -Date : 10/01/2013 - Summary : Re Assign sid for image 3d
function update3DImagesArr(){
    
    if(_object3DImageArr.length > 0){
        var temp3DArr = [];
        _object3DImageArr = [];
        for(var i = 0; i < _object3DImageArr; i++){
            var object3D = _object3DImageArr[i];
            var temp3dview = object3d["3dview"];
            var tempCurrX = object3d["_currFrameX"];
            var tempCurrY = object3d["_currFrameY"];
            var tempLastSelectedFrame = object3d["lastSelectedFrame"];
            var tempActionType = object3d["actionType"];
            var tempHeight = object3d["height"];
            var tempHorizonCnt = object3d["horizonCount"];
            var tempId = object3d["id"];
            var tempInitImage = object3d["initImage"];
            var tempMediaType = object3d["mediaType"];
            var tempVerticalCnt = object3d["verticalCount"];
            var tempVisible = object3d["visible"];
            var tempWidth = object3d["width"];
            var tempX = object3d["x"];
            var tempY = object3d["y"];
            
            tempInitImage = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + getUrlParams(tempInitImage, 'resourceId');
            for(var j = 0; j< temp3dview.length; j++){          
                var url = temp3dview[j];
                var id = getUrlParamByUrl(url, 'resourceId');            
                temp3dview[j] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + id;           
            }
            
            var arr3D = [];       
            arr3D["3dview"] = temp3dview;  
            arr3D["_currFrameX"] = tempCurrX;  
            arr3D["_currFrameY"] = tempCurrY;  
            arr3D["lastSelectedFrame"] = tempLastSelectedFrame;
            arr3D["actionType"] = tempActionType;  
            arr3D["height"] = tempHeight;  
            arr3D["horizonCount"] = tempHorizonCnt;  
            arr3D["id"] = tempId;  
            arr3D["initImage"] = tempInitImage;  
            arr3D["mediaType"] = tempMediaType;  
            arr3D["verticalCount"] = tempVerticalCnt;  
            arr3D["visible"] = tempVisible;
            arr3D["width"] = tempWidth;  
            arr3D["x"] = tempX;  
            arr3D["y"] = tempY;  
            
            temp3DArr.push(arr3D);
        }
        
        _object3DImageArr = temp3DArr;
    }       
};

//Get param url
function getUrlParamByUrl(url, name){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
    var regexS = "[\\?&]"+name+"=([^&#]*)";  
    var regex = new RegExp( regexS );  
    var results = regex.exec(url); 
    if( results == null ){
        return "";
    }      
    else{
        return results[1];
    }
};
//END TRB - Editor : Long -Date : 10/01/2013 - Summary : Re Assign sid for image 3d
function onUnlock() {
    removeObject();
    update3DImagesArr();
    getPageObjectsByPageIndex(pageObjectsData, 0);
    /* handle play BGM of content jump */
    for (var nIndex = 0; nIndex < pageObjects.length; nIndex++) {
        if (pageObjects[nIndex].mediaType == '3' && pageObjects[nIndex].playType == '1') {
            if (avwUserEnvObj.os == "ipad") {
                $('#play_audio_1').attr('src', pageObjects[nIndex].audioFile);
                //document.getElementById("play_audio_1").load();           
                document.getElementById("play_audio_1").play();
                isPlayBGMUnlock = true;
            } else {
                createAudio(pageObjects[nIndex].audioFile, pageObjects[nIndex].playType);
            }
        }
    }
    
    //Start Function: No.4 - Editor : Long - Date : 08/12/2013 - Summary : ReDraw canvas when has new sid
    getPageObjectsByPageIndex(pageObjectsData, getPageIndex());
    getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects).setUpPage(getPageIndex());
    //START : TRB00028 - Editor: Long - Date: 09/10/2013 - Summary : Fix For Page BGM
    createPageBGM();
    //END : TRB00028 - Editor: Long - Date: 09/10/2013 - Summary : Fix For Page BGM
    if(getPageIndex() < totalPage - 1){
        getNextPageObjectsByPageIndex(pageObjectsData, getPageIndex() + 1);
        renderNextPage();
    }
  
    if(getPageIndex() > 0){
        getPrevPageObjectsByPageIndex(pageObjectsData, getPageIndex() - 1);
        renderPrevPage();
    }  
    
    //End Function: No.4 - Editor : Long - Date : 08/12/2013 - Summary : ReDraw canvas when has new sid
};

function onClick_CanvasMain(event) {
     
    event.preventDefault(); 
    
    if(isLoadingObject){       
        return;
    }
    else{
        cancelClick = false;
    }    
    
    if (!cancelClick) {
        
        //change coordinates 
        var imagePt = screenToImage(event.pageX, event.pageY);
        var canvasWidth = $('#offscreen').width();
        posXPopupMemo = event.pageX;
        posYPopupMemo = event.pageY;

        if ((event.pageX - marginX) >= destRect.left && (event.pageX - marginX) <= destRect.right) {        
            /* click add memo */
            if (ClientData.IsAddingMemo() == true) {
                
                if (!ClientData.memo_copyText()) {
                    AddMemo(contentID, changePageIndex(getPageIndex()), $('#divDialogMemo'), event.pageX, event.pageY, function () {
                        //set flag change memo 
                        ClientData.isChangedMemo(true);
                        ClientData.IsAddingMemo(false);

                        /* refresh draw memo */
                        drawMemoOnScreen();

                        //change image	             							
                        $('#imgaddmemo').removeClass();
                        $('#imgaddmemo').addClass('memoAdd');
                    });
                } else {
                    if (typeSelectMemo == 1) { /* add new */
                        AddMemo(contentID, changePageIndex(getPageIndex()), $('#divDialogMemo'), posXPopupMemo, posYPopupMemo, function () {
                            //set flag change memo 
                            ClientData.isChangedMemo(true);
                            ClientData.IsAddingMemo(false);

                            /* refresh draw memo */
                            drawMemoOnScreen();

                            //change image	             							
                            $('#imgaddmemo').removeClass();
                            $('#imgaddmemo').addClass('memoAdd');
                        });

                    } else if (typeSelectMemo == 2) { /* copy */
                        CopyMemo(ClientData.memo_copyText(), contentID, changePageIndex(getPageIndex()), $('#divDialogMemo'), posXPopupMemo, posYPopupMemo, function () {
                            //set flag change memo 
                            ClientData.isChangedMemo(true);
                            ClientData.IsAddingMemo(false);

                            /* refresh draw memo */
                            drawMemoOnScreen();

                            //change image	             							
                            $('#imgaddmemo').removeClass();
                            $('#imgaddmemo').addClass('memoAdd');
                        });
                    }
                }

            } 
            else {

                var isClickMemo = false;

                if (isOpenPopUpText == true) {
                    isOpenPopUpText = false;
                    ClosePopupText();
                }

                if (isOpenPopUpMemo == true) {
                    isOpenPopUpMemo = false;
                    $("#pop_up_memo").hide();
                }

                /* click memo edit */
                if (ClientData.IsDisplayMemo() == true) {
                    getAllMemoOfPage();
                    /* check exist object memo in mouse position */
                    for (var nIndex = 0; nIndex < memoObjects.length; nIndex++) {
                        var hitPageObjMemo = memoObjects[nIndex];
                        if (hitPageObjMemo.hitTest(imagePt.x, imagePt.y)) {
                            //console.log("PageObject Hit!! Id: " + hitPageObjMemo.id);
                            //hitPageObjMemo.action();

                            /* save object memo */
                            objEditMemo = hitPageObjMemo;
                            var posMemoX = event.pageX;
                            var posMemoY = event.pageY;

                            if (imagePt.y > heightEachPage - $("#pop_up_memo").height()) {
                                posMemoY = posMemoY - $("#pop_up_memo").height();

                            }

                            if (imagePt.x > widthEachPage - $("#pop_up_memo").width()) {
                                posMemoX = posMemoX - $("#pop_up_memo").width();
                            }

                            /*display pop-up-memo */
                            $("#pop_up_memo").css('top', posMemoY).css('left', posMemoX);
                            $("#pop_up_memo").show();

                            /*set true for flag click memo */
                            isClickMemo = true;
                            isOpenPopUpMemo = true;

                        }
                    }
                }

                /* click pageObject */
                if (isClickMemo == false) {
                    var isClickLinkList = false;

                    /* check exist object in mouse position */
                    var hitPageObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);
                                                                               
                    if (hitPageObj) { 
                   
                        if(!is3DObject(hitPageObj)){
                            hitPageObj.action();    
                        }
                        else{
                            //event.preventDefault();
                        }                                                                  			                     
                    }
                    else {

                        /* check click link list */
                        for (var nIndex = 0; nIndex < webGetContentType4Objects.length; nIndex++) {
                            var hitPageObjLinkList = webGetContentType4Objects[nIndex];
                            if (hitPageObjLinkList.hitTest(imagePt.x, imagePt.y)) {
                                //console.log("PageObject Hit!! Id: " + hitPageObjLinkList.id);
                                if(hitPageObjLinkList.pageNo == changePageIndex(getPageIndex())){
                                    hitPageObjLinkList.action();

                                    /*set true for flag click memo */
                                    isClickLinkList = true;
                                }                               
                            }
                        }

                        if (isClickLinkList == false && ClientData.IsAddingMarking() == false) {
                            /* area next and prev page */
                            var cwMain = $('#main').width();
                            //Start : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013 - Summary : Prevent click when transit
                            if (event.pageX > 0 && event.pageX < 300) {
                                if(!isPreventClick){
                                    //START TRB00097
                                    if(userScale == 1){
                                       prevPage_click(); 
                                    }
                                    //END TRB00097
                                }
                                else{
                                    isPreventClick = false;
                                }                                                                  
                            } else if (event.pageX > (cwMain - 300) && event.pageX < cwMain) {
                                if(!isPreventClick){
                                    //START TRB00097
                                    if(userScale == 1){
                                       nextPage_click(); 
                                    } 
                                    //END TRB00097  
                                }
                                else{
                                    isPreventClick = false;
                                }       
                            }
                            //End : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013 - Summary : Prevent click when transit
                        }
                    }
                }
            }
        } 
        else {          
            if (ClientData.IsAddingMarking() == false && isCopyMemo == false) {
                var cwMain = $('#main').width();
                //Start : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013 - Summary : Prevent click when transit
                if (event.pageX > 0 && event.pageX < 300) {
                    if(!isPreventClick){                              
                        //START TRB00097
                        if(userScale == 1){
                           prevPage_click(); 
                        }
                        //END TRB00097
                        //isPreventClick = true;                        
                    }
                    else{
                        isPreventClick = false;
                    }
                    
                                                         
                } else if (event.pageX > (cwMain - 300) && event.pageX < cwMain) { 
                    if(!isPreventClick){      
                        if(userScale == 1){
                           nextPage_click(); 
                        } 
                    }
                    else{
                        isPreventClick = false;
                    }
                }
                //End : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013 - Summary : Prevent click when transit
            }          
        }
    }
    cancelClick = false;
};

function mouseMove_canvasMain(event) {
             
    //Start Function : No.20 - Editor : Long
    if(_isTouching){            
       //_isTouching = false;
       return; 
    }
    
    if(ClientData.IsAddingMarking() == true){
        return;  
    }
    
    if(isLoadingObject){
        moveFlag = false;    
    }

    //End Function : No.20 - Editor : Long
    event.preventDefault(); 
    
    /* base image move when userScale over 1 */
    if (moveFlag && userScale != 1) {
        $('#main').css('cursor', 'pointer');
        //START TRB00097
        cancelClick = true;
        //END TRB00097
        var mx;
        var my;
        // calc mouse moving distance
        if (avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android") {
            mx = event.pageX - px;
            my = event.pageY - py;
        } else {
            mx = event.targetTouches[0].pageX - px;
            my = event.targetTouches[0].pageY - py;
        }

        var sx = 1 / userScale;
        var sy = 1 / userScale;

        // calc scaling moving distance
        moveX = Math.round(-mx * sx);
        moveY = Math.round(-my * sy);


        // store current mouse point
        if (avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android") {
            px = event.pageX;
            py = event.pageY;
        } else {
            //event.preventDefault();
            px = event.targetTouches[0].pageX;
            py = event.targetTouches[0].pageY;
        }

        // redraw
        flip();

        zoomVideo();

        closeDialogPopUpText();
    }
    //Start Function : No.20
    else if(moveFlag && userScale == 1){

        //Prevent 3d animate when moving
        isPageTransition = true;
        
        //Start : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013 - Summary : Prevent click when transit
        isPreventClick = true;
        //End : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013 - Summary : Prevent click when transit
        
        var x = event.pageX;
        var y = event.pageY;
        var deltaX = x - px;
        var deltaY= y - py;
        px = x;
        py = y;
        currPos = {x:event.pageX,y:event.pageY};
        // pevious page not exist -> do not move
        if(!getContent().hasPreviousPage()){
            if(currPos.x >= _clickFirstPos.x){
                return;
            }                
        }
        
        // next page not exist -> do not move
        if(!getContent().hasNextPage()){
            if(currPos.x <= _clickFirstPos.x)
                return;
        }
        
        //examinate direction 
        if(_moveNum==0 &&  deltaX < 0){
            _moveNum = 2; // go from right to left => next page
        }
        if(_moveNum==2 &&  deltaX > 0){
            _moveNum = 1; // go from right to left and back to right => no move
        }
        if(_moveNum==1 &&  deltaX < 0){
            _moveNum = 2; // go from right to left + back to right + go to left  => next page
        }

        if(_moveNum==0 &&  deltaX > 0){
            _moveNum = -2; // go from  left to right=> priveous page
        }
        if(_moveNum==-2 &&  deltaX < 0){
            _moveNum = -1; // go from  left to right and back to left => no move
        }
        if(_moveNum==0 &&  deltaX > 0){
            _moveNum = -2; // go from  left to right + back to left + go to right=> priveous page
        }
        
        if(animateType == animateTypeKeys.Type_Slide){
            var left = $('#canvasWrapper').css('left').replace("px","");
            left  =  parseInt(left) + deltaX;
    
            $('#canvasWrapper').css('left', left + "px");
        }        
    }
    
    if(moveFlag == false && _3dAnimate == true){  
        var imagePt = screenToImage(event.pageX, event.pageY);
        var hitObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);
        if(hitObj){
           if(is3DObject(hitObj)){
                _3dAction = _3dActionType.TouchMove_MouseMove;            
                hitObj.action(imagePt);  
           }                 
        }
        else{
            _3dAnimate = false;
        }      
    }
       
    //End Function : No.20
    var cwMain = $('#main').width();
    var chMain = $('#main').height();
    /* handle image prev on canvas */
    if (getContent().hasPreviousPage()) {
        $('#button_pre_canvas').mousemove(function () {
            if (getContent().hasPreviousPage()) {

                $(this).css('opacity', '1');
            } else {
                $(this).css('opacity', '0');
            }
        });

        if (event.pageX > 0 && event.pageX < 300) {
            $('#button_pre_canvas').css('opacity', '0.25');
        } else {
            $('#button_pre_canvas').css('opacity', '0');
        }
    } 
    else {
        $('#button_pre_canvas').css('opacity', '0');
    }

    /* handle image next on canvas */
    if (getContent().hasNextPage()) {
        $('#button_next_canvas').mousemove(function () {
            if (getContent().hasNextPage()) {
                $(this).css('opacity', '1');
            } else {
                $(this).css('opacity', '0');
            }
        });

        if (event.pageX > (cwMain - 300) && event.pageX < cwMain) {
            $('#button_next_canvas').css('opacity', '0.25');
        } else {
            $('#button_next_canvas').css('opacity', '0');
        }
    } else {
        $('#button_next_canvas').css('opacity', '0');
    }
    
};

function mouseDown_CanvasMain(event) {
   
    //Start Function : No.20 - Editor : Long - Date: 08/17/2013 - Summary : 
    if(_isTouching){       
       //_isTouching = false;
       return; 
    }
    
    if(ClientData.IsAddingMarking() == true){
        return;  
    }
    
    //End Function : No.20 - Editor : Long - Date: 08/17/2013 - Summary : 
  
    if(!isLoadingObject){
        moveFlag = true;
    }
    else{
        moveFlag = false;
    }
    
    event.preventDefault(); 
       
    $('#main').css('cursor', 'default');
       
    if (avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android") {
        px = event.pageX;
        py = event.pageY;      
                
        //Start Function : No.20
        _clickFirstPos = {x:event.pageX, y: event.pageY};
        _clickLastPos = {x:event.pageX, y: event.pageY};
        
        _moveNum = 0; 
        
        if(animateType == animateTypeKeys.Type_Slide){
            $('#mainPre').css("display",'block');
            $('#mainNext').css("display",'block');
        }             
       
         //End Function : No.20                    
        
        //Start Function : No.9 - Editor : Long - Date : 08/16/2013 - Summary : 
        var imagePt = screenToImage(px, py);
        var hitPageObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);
             
        moveFlag = true;
        _3dAnimate = false;
        
        if(is3DObject(hitPageObj)){            
            
            //START TRB00090 - Editor: Long - Date : 09/26/2013 - Summary : remove time to detect 3d animate       
            if(!isPageTransition){
                   _3dAnimate = true;
                   _3dAction = _3dActionType.TouchStart_MouseDown;
                   _curr3dObject = hitPageObj;
                   hitPageObj.action(imagePt); 
                   moveFlag = false;                                   
            }
            else{
                _3dAnimate = false;
                moveFlag = true;  
            }  
            //END TRB00090 - Editor: Long - Date : 09/26/2013 - Summary : remove time to detect 3d animate                                 
        }                                                   
        else{
            _3dAnimate = false;
        }
                                                                                                                                                                   
        //End Function : No.9 - Editor : Long - Date : 08/16/2013 - Summary:    
    }
    else {
        
        //event.preventDefault();
        
        px = event.targetTouches[0].pageX;
        py = event.targetTouches[0].pageY;               
    }    
};

function mouseUp_CanvasMain(event) {
    //Start Function : No.20
     
    event.preventDefault();
    
    if(ClientData.IsAddingMarking() == true){
        return;  
    }
    
    if(moveFlag) {
        moveFlag = false;
        $('#main').css('cursor', 'default');
        // navigate page
        if(_moveNum == 2){
            nextPage_click();
        }else if (_moveNum == -2){
            prevPage_click();
        }else {
            correctCanvasPosition();
        }
        
        //Check if mouse move is fired to prevent click next/ prev page
        //isInMouseMove = false;
        
    }
    
    if(_3dAnimate == true){
        _3dAnimate = false;

        _3dAction = _3dActionType.TouchEnd_MouseUp;

        _curr3dObject.action(); 
    }
    
    if(isPageTransition){
        isPageTransition = false;
    }
    
    //End Function : No.20
};

function imgBack_click() {
    /* set end log */
    SetEndLog(contentID);
    RegisterLog();

    window.onbeforeunload = null;

    if (ClientData.JumpQueue()) {
        var oldDataBack = ClientData.JumpQueue();
        if (oldDataBack.length > 0) {
            avwScreenMove(ScreenIds.ContentView);
            ClientData.IsJumpBack(true);
        } else {
            /*check back */
            if (ClientData.BookmarkScreen()) {
                avwScreenMove(ClientData.BookmarkScreen());
            } else {
                window.history.back();
            }
        }
    } else {
        /*check back */
        if (ClientData.BookmarkScreen()) {
            avwScreenMove(ClientData.BookmarkScreen());
        } else {
            window.history.back();
        }
    }

};

function imgHome_click(e) {
    e.preventDefault();

    /* set end log */
    SetEndLog(contentID);
    RegisterLog();

    //window.location.href = ScreenIds.Home;
    avwScreenMove(ScreenIds.Home);
};

function closePopUpCopyMemo() {
    $('#boxAddMemo').hide();
    //ClientData.memo_copyText(null);
    ClientData.IsAddingMemo(false);

    /* unlock dialog overlay */
    $("#overlay").hide();

    //change class
    $('#imgaddmemo').removeClass();
    $('#imgaddmemo').addClass('memoAdd');
};

function click_liAddMemo(event) {
    typeSelectMemo = 1;

    $('#boxAddMemo').hide();
    /* unlock dialog overlay */
    $("#overlay").hide();

    //ClientData.memo_copyText(null);
    //ClientData.IsAddingMemo(false); 
};

function click_liCopyMemo() {
    typeSelectMemo = 2;

    $('#boxAddMemo').hide();
    /* unlock dialog overlay */
    $("#overlay").hide();

    //ClientData.memo_copyText(null);  
    //ClientData.IsAddingMemo(false); 
};

function click_liDeleteMemo() {
    $('#boxAddMemo').hide();
    ClientData.memo_copyText(null);
    ClientData.IsAddingMemo(false);

    /* unlock dialog overlay */
    $("#overlay").hide();

    //change class
    $('#imgaddmemo').removeClass();
    $('#imgaddmemo').addClass('memoAdd');
};

//Start Funcion : No.20 - Editor : Long - Date : 08/13/2013 - Summary : Win 8 touch handle

/*
 * reset navi action as point session increase
 */
function resetNaviAction(){
    _isPageNaviTouch = true;
    _moveNum = 0;       
    touchStartedTime = new Date();
    $('#mainPre').css("display",'none');
    $('#mainNext').css("display",'none');
    _touchFirstPos = null;
    _touchLastPos=null;
    //console.log("================correctCanvasPosition==============="); 
    correctCanvasPosition();

};

function onTouchstart(evt){

    if(ClientData.IsAddingMarking() == true){
        return;  
    } 
     
    var bContinue = true;

    if (avwUserEnvObj.os == "ipad" || avwUserEnvObj.os == "android") {
        evt.preventDefault();        
    }    
    
    if(isLoadingObject){
        bContinue = false;
    }          
    
    switch (evt.pointerType) {
        case evt.MSPOINTER_TYPE_TOUCH:
            _isTouching = true;
            break;          
        case evt.MSPOINTER_TYPE_PEN:
            bContinue = false;
            break;
        case evt.MSPOINTER_TYPE_MOUSE:
            _isTouching = false;
            bContinue = false;
            break;
    }
    
    
    if(!bContinue){
        return;  
    }

    _isPageNaviTouch = false;
    _isPageZoomTouch = false;
    
    var touch1 = null;
    var touch2 = null;      
    _touchLastPos = null;
    _touchFirstPos = null;
    
    if(_bWin8TouchEnabled){       
        _bufferPoints = [];
        if(_startPoints.length == 0){
            // start navi page case
            touch1 = {clientX: evt.clientX, clientY: evt.clientY,pointerId: evt.pointerId};
            _startPoints.push(touch1);
            if(userScale != 1){
                px = evt.pageX;
                py = evt.pageY;    
            }
            else{
                touchDownFirstPosX = evt.clientX;
                touchDownFirstPosY = evt.clientY;
                
                //Start Function : No.9 - Editor : Long - Date : 08/16/2013 - Summary : 
                var imagePt = screenToImage(evt.pageX, evt.pageY);
                var hitPageObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);
               _3dAnimate = false;
               
                if (hitPageObj) {
                     //START TRB00090 - Editor: Long - Date : 09/26/2013 - Summary : remove time to detect 3d animate                               
                    if(is3DObject(hitPageObj)){                                    
                        if(isPageTransition){                           
                            _3dAnimate = false;
                        }
                        else{
                            _3dAction = _3dActionType.TouchStart_MouseDown;
                            _curr3dObject = hitPageObj;
                            hitPageObj.action(imagePt);
                            _3dAnimate = true;
                        }
                    }
                    else{
                        _3dAnimate = false;
                    } 
                     //END TRB00090 - Editor: Long - Date : 09/26/2013 - Summary : remove time to detect 3d animate                                                                                                                                                    
                }
                //End Function : No.9 - Editor : Long - Date : 08/16/2013 - Summary:        
            }                                                          
        } 
        else if(_startPoints.length == 1){
            // start zoom page action
            if(_isPageNaviTouch){
                // reset navi page action if exists
                resetNaviAction();  
            }  
            
            touch1 = _startPoints[0];
            touch2 = {clientX: evt.clientX, clientY: evt.clientY,pointerId: evt.pointerId};
            _startPoints.push(touch2);
            
            //set last dist
            _lastDist = getDistance({
                    x: touch1.clientX,
                    y: touch1.clientY
                }, {
                    x: touch2.clientX,
                    y: touch2.clientY
                });
            
                px = touch1.clientX+touch2.clientX/2;
                py = touch1.clientY+touch2.clientY/2;
                                  
        } 
        else {
            //when _startPoints.length > 1
            touch1 = {clientX: evt.clientX, clientY: evt.clientY,pointerId: evt.pointerId};
            _startPoints.push(touch1);
            if(_isPageNaviTouch){
                resetNaviAction();
            }   
            
            if(_isPageZoomTouch){
                resetZoomAction();
            }
        }        
    }
    else{              
        
        // not is win 8 touch event 
        touch1 = evt.touches[0];
        touch2 = evt.touches[1];        
        if(touch2 == null){            
            _isClick = true;
            _touchPageX = evt.touches[0].pageX;
            _touchPageY = evt.touches[0].pageY;
            //set touch to move page flag
            if(touch2 == null && userScale == 1){
                
                if(animateType == animateTypeKeys.Type_Slide){
                    $('#mainPre').css("display",'block');
                    $('#mainNext').css("display",'block');
                }

    
                _isPageNaviTouch = true;
                _moveNum = 0;
                touchStartedTime = new Date();
                
                // set first and last Pos
                _touchFirstPos = {x:touch1.clientX, y: touch1.clientX};
                _touchLastPos = {x:touch1.clientX, y: touch1.clientX};
                
                //Start Function : No.9 - Editor : Long - Date : 08/16/2013 - Summary : 
                var imagePt = screenToImage(touch1.pageX, touch1.pageY);
                var hitPageObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);
                
                if (hitPageObj) {
                                                          
                    if(is3DObject(hitPageObj)){                       
                        //START TRB00090 - Editor: Long - Date : 09/26/2013 - Summary : remove time to detect 3d animate  
                        if(isPageTransition){
                            _3dAnimate = false;
                            _isClick = true;
                        }
                        else{
                            _3dAction = _3dActionType.TouchStart_MouseDown;
                            _curr3dObject = hitPageObj;
                            hitPageObj.action(imagePt);
                            _3dAnimate = true;
                            _isClick = false;
                        }   
                        //END TRB00090 - Editor: Long - Date : 09/26/2013 - Summary : remove time to detect 3d animate                  
                    }
                    else{                       
                        _3dAnimate = false;
                        _isClick = true;
                    }                                                                                                                                                    
                }
                else{                 
                    _3dAnimate = false;
                    _isClick = true;
                }
                //End Function : No.9 - Editor : Long - Date : 08/16/2013 - Summary:                                
            }
            else if(touch2 == null && userScale != 1){
                _isPageNaviTouch = false;
                px = evt.pageX;
                py = evt.pageY;               
            }
            else {              
                _isPageNaviTouch = false;
            }   
                                
        }
               
        //set begin value for zoom
        if(touch1 && touch2) {
            _lastDist = getDistance({
                    x: touch1.clientX,
                    y: touch1.clientY
                }, {
                    x: touch2.clientX,
                    y: touch2.clientY
                });
                    px = touch1.clientX+touch2.clientX/2;
                    py = touch1.clientY+touch1.clientY/2;
      
            _isPageNaviTouch = false;
        }           
    }
};

//limit area to detech if it is click(on win8)
var clickLimitArea = 20;
//touch position 
var touchDownFirstPosX = 0;
var touchDownFirstPosY = 0;
//position for click event on touch device
var _touchPageX = 0;
var _touchPageY = 0;
//Detect touch
var _isTouching = false;
//Detect click on touch device
var _isClick = false;
//Detech if page is being transition
var isPageTransition = false;
//Is 3d animating
var _3dAnimate = false;
//Start : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013
//is prevent click event
var isPreventClick = false;
//End : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013
function onTouchmove(evt){

    if(ClientData.IsAddingMarking() == true){
        return;  
    }
    
    var bContinue = true;
    if(isLoadingObject){
        bContinue = false;
    }
         
    switch (evt.pointerType) {
        case evt.MSPOINTER_TYPE_TOUCH:
            _isTouching = true;
            break;          
        case evt.MSPOINTER_TYPE_PEN:
            bContinue = false;
            break;
        case evt.MSPOINTER_TYPE_MOUSE:
            _isTouching = false;
            bContinue = false;
            break;
    }
    
    if(!bContinue){
        return;  
    }   

    if (avwUserEnvObj.os == "ipad" || avwUserEnvObj.os == "android") {
        evt.preventDefault();        
    }
    
    var touch1 = null;
    var touch2 = null;      
    if(_bWin8TouchEnabled){ 
       
        if(_startPoints.length == 1){
            //move page case          
            //when change from zoom mode
            if(userScale != 1){
                _isPageNaviTouch = false;
                //START TRB00097
                cancelClick = true;
                //END TRB00097
                $('#main').css('cursor', 'pointer');        

                var mx;
                var my;
                // calc mouse moving distance
                if (avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android") {
                    mx = evt.pageX - px;
                    my = evt.pageY - py;

                } else {
                    mx = evt.targetTouches[0].pageX - px;
                    my = evt.targetTouches[0].pageY - py;
                }
               
                var sx = 1 / userScale;
                var sy = 1 / userScale;
                               
                // calc scaling moving distance
                moveX = Math.round(-mx * sx);
                moveY = Math.round(-my * sy);
                
                // store current mouse point
                if (avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android") {
                    px = evt.pageX;
                    py = evt.pageY;
                } else {
                    px = evt.targetTouches[0].pageX;
                    py = evt.targetTouches[0].pageY;
                }
        
                // redraw
                flip();
        
                zoomVideo();
        
                closeDialogPopUpText();                              
            }
            else{
                if(_3dAnimate){
                    _isPageNaviTouch = false;   
                    var imagePt = screenToImage(evt.pageX, evt.pageY);
                    var hitObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);
                    
                    if(hitObj){            
                        _3dAction = _3dActionType.TouchMove_MouseMove;
                        hitObj.action(imagePt);                     
                    }
                    else{
                        _3dAnimate = false;
                    }    
                }
                else{
                    _isPageNaviTouch = true;
                    
                    //Detect is page transition to prevent 3d object animate
                    var posDiffX = evt.clientX - touchDownFirstPosX ;
                    var posDiffY = evt.clientY - touchDownFirstPosY ;
                    
                    if(Math.abs(posDiffX) < clickLimitArea && Math.abs(posDiffY) < clickLimitArea){
                        isPageTransition = false;
                        isPreventClick = false; 
                    }        
                    else{
                        isPageTransition = true;
                        
                        //Start : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013
                        //Prevent CLick when page is being transit
                        isPreventClick = true;  
                        //End : TRB00005, TRB00006 - Editor : Long - Date: 08/28/2013   
                    }                          
                                  
                    
                    touch1 = {clientX: evt.clientX, clientY: evt.clientY, pointerId: evt.pointerId};
                    _bufferPoints.push(touch1);  // add to buffer to use for another action if occur. ex: zoom page
                    
                    if(animateType == animateTypeKeys.Type_Slide){
                        $('#mainPre').css("display",'block');
                        $('#mainNext').css("display",'block');
                    }
        
                    touchStartedTime = new Date();
                    
                    var temp = _startPoints[0];
                    // set first and last Pos
                    if(_touchFirstPos == null){
                        _touchFirstPos = {x:temp.clientX, y: temp.clientX};
                        _moveNum = 0;
                    } 
                    if(_touchLastPos==null){
                         _touchLastPos = {x:temp.clientX, y: temp.clientX};
                    }
                }                                 
            }                                     
        }
        else if(_startPoints.length == 2){

            //zoom page case
            _isPageZoomTouch = true;
            //rest navi touch if active
            if(_isPageNaviTouch){
                resetNaviAction();
            }   
            
            //console.log("zoom page case");
            if(_bufferPoints.length == 0) {
                //first point so that wait to next point
                touch1 = {clientX: evt.clientX, clientY: evt.clientY, pointerId: evt.pointerId};
                _bufferPoints.push(touch1);
                return;
            }else if(_bufferPoints.length == 1) {
                // second point so that get first point and process zoom page
                touch1 = _bufferPoints[0];
                
                // check pointer id
                if(touch1.pointerId == evt.pointerId){
                    // one touch session is identify by one pointerId
                    // in this case do nothing and go to get next pointerId  
                    return;
                }else if(touch1.pointerId > evt.pointerId){
                    _bufferPoints = [];  // reset buffer to get pointerId with correct order from begin
                    return; 
                }
                touch2 = {clientX: evt.clientX, clientY: evt.clientY, pointerId: evt.pointerId};
                
                //console.log("_bufferPoints.length:" + _bufferPoints.length);
                _bufferPoints = [];
            }
        }
        else {
            //reset navi touch if active
            if(_isPageNaviTouch){
                resetNaviAction();
            }   

            if(_isPageZoomTouch){
                resetZoomAction();
            }
            return;
        }

       //process  
        if(_isPageNaviTouch){
            
            currPos = {x:touch1.clientX, y: touch1.clientY};
            if(!processNaviPage(currPos)){
                
                // can not move to previous or next page
                return; 
            }
        }
                
        // zoom page case
        if(_isPageZoomTouch) {
            processZoomPage(touch1, touch2);
        }       
        

    }
    else{
        _isClick = false; 
        // for android or ipad
        touch1 = evt.touches[0];
        touch2 = evt.touches[1];
        
        if(_3dAnimate){
                           
            var imagePt = screenToImage(touch1.pageX, touch1.pageY);
            var hitObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);
            //START TRB00090 - Editor: Long - Date 09/30/2013 - Summary: Fix animate 3d object in ipad
            if(hitObj){
                if(is3DObject(hitObj)){
                    _isPageNaviTouch = false;
                    _3dAction = _3dActionType.TouchMove_MouseMove;
                    hitObj.action(imagePt);   
                }               
            }
            else{
                _3dAnimate = false;
                //_isPageNaviTouch = true;
            } 
            //END TRB00090 - Editor: Long - Date 09/30/2013 - Summary: Fix animate 3d object in ipad 
        }
        else{
            //update last touch position 
            if(touch2 == null && _isPageNaviTouch){
                isPageTransition = true;
                currPos = {x:touch1.clientX, y: touch1.clientY};
                
                if(! _transitionObject.processNaviPage(currPos)){
                    // can not move to previous or next page
                    return; 
                }
            }
            else{
                //when change from zoom mode
                if(userScale != 1){
    
                    $('#main').css('cursor', 'pointer');        
    
                    var mx;
                    var my;
                  
                    mx = evt.targetTouches[0].pageX - px;
                    my = evt.targetTouches[0].pageY - py;
                           
                    var sx = 1 / userScale;
                    var sy = 1 / userScale;
                                   
                    // calc scaling moving distance
                    moveX = Math.round(-mx * sx);
                    moveY = Math.round(-my * sy);
                    
                    px = evt.targetTouches[0].pageX;
                    py = evt.targetTouches[0].pageY;
                           
                    // redraw
                    flip();
            
                    zoomVideo();
            
                    closeDialogPopUpText();                              
                }
            }
                        
            // zoom page case
            if(touch1 && touch2) {
                processZoomPage(touch1, touch2);
            } 
        }                     
    }
};

function onTouchend(evt){
    
    if(ClientData.IsAddingMarking() == true){
        return;  
    }
    
    var bContinue = true;
   
    if(isLoadingObject){
        bContinue = false;
    }
    
    switch (evt.pointerType) {
        case evt.MSPOINTER_TYPE_TOUCH:
            _isTouching = true;
            break;          
        case evt.MSPOINTER_TYPE_PEN:
            _isTouching = false;
            bContinue = false;
            break;
        case evt.MSPOINTER_TYPE_MOUSE:
            _isTouching = false;
            bContinue = false;
            break;
    }
    
    if(!bContinue){
        return;  
    } 
    
    if (avwUserEnvObj.os == "ipad" || avwUserEnvObj.os == "android") {
        evt.preventDefault();
    }
    _lastScaleDelta = userScale -1;

    if(_bWin8TouchEnabled){
        
        // reset all flag
        _startPoints = [];
        _bufferPoints = [];
        
        if(_3dAnimate == true){
            _3dAnimate = false;
            _3dAction = _3dActionType.TouchEnd_MouseUp;
            _curr3dObject.action(); 
        }
        
        if(isPageTransition){
            isPageTransition = false;
            touchDownFirstPosX = 0;
            touchDownFirstPosY = 0;
        }    
                  
    }
    
    //move page if enough condition 
    if(_bTransitionEnable){
        if(_isPageNaviTouch){
            _isPageNaviTouch = false;
            //calculate time period from last time of touchstart event
            var currDate = new Date();
            var period = currDate - touchStartedTime;

            if(period >= _touchMoveTimePeriod && period < _touchMoveTimePeriodInvalid){
                touchStartedTime= 0;
                if(_moveNum == 2){
                    nextPage_click();
                }else if (_moveNum == -2){
                    prevPage_click();
                }else {
                    correctCanvasPosition();
                }
           }
        }
    }

    //Check if click event on ipad
    if(_isClick == true){

        if(isLoadingObject){ 
            _isClick = false;      
            return;
        }
        else{
            cancelClick = false;
        }
        
        if (!cancelClick) {

            var imagePt = screenToImage(_touchPageX, _touchPageY);        
            var canvasWidth = $('#offscreen').width();
            posXPopupMemo = _touchPageX;
            posYPopupMemo = _touchPageY;
            
            if ((_touchPageX - marginX) >= destRect.left && (_touchPageX - marginX) <= destRect.right) {
                if (ClientData.IsAddingMemo() == true) {
                    if (!ClientData.memo_copyText()) {
                            AddMemo(contentID, changePageIndex(getPageIndex()), $('#divDialogMemo'), _touchPageX, _touchPageY, function () {
                                //set flag change memo 
                                ClientData.isChangedMemo(true);
                                ClientData.IsAddingMemo(false);
        
                                /* refresh draw memo */
                                drawMemoOnScreen();
        
                                //change image                                          
                                $('#imgaddmemo').removeClass();
                                $('#imgaddmemo').addClass('memoAdd');
                            });
                    }
                    else {
                        if (typeSelectMemo == 1) { /* add new */
                            AddMemo(contentID, changePageIndex(getPageIndex()), $('#divDialogMemo'), posXPopupMemo, posYPopupMemo, function () {
                                //set flag change memo 
                                ClientData.isChangedMemo(true);
                                ClientData.IsAddingMemo(false);
    
                                /* refresh draw memo */
                                drawMemoOnScreen();
    
                                //change image                                          
                                $('#imgaddmemo').removeClass();
                                $('#imgaddmemo').addClass('memoAdd');
                            });
    
                        } else if (typeSelectMemo == 2) { /* copy */
                            CopyMemo(ClientData.memo_copyText(), contentID, changePageIndex(getPageIndex()), $('#divDialogMemo'), posXPopupMemo, posYPopupMemo, function () {
                                //set flag change memo 
                                ClientData.isChangedMemo(true);
                                ClientData.IsAddingMemo(false);
    
                                /* refresh draw memo */
                                drawMemoOnScreen();
    
                                //change image                                          
                                $('#imgaddmemo').removeClass();
                                $('#imgaddmemo').addClass('memoAdd');
                            });
                        }
                    }
                }
                else{
                    var isClickMemo = false;
    
                    if (isOpenPopUpText == true) {
                        isOpenPopUpText = false;
                        ClosePopupText();
                    }
    
                    if (isOpenPopUpMemo == true) {
                        isOpenPopUpMemo = false;
                        $("#pop_up_memo").hide();
                    }
                    
                    /* click memo edit */
                    if (ClientData.IsDisplayMemo() == true) {
                        getAllMemoOfPage();
                        /* check exist object memo in mouse position */
                        for (var nIndex = 0; nIndex < memoObjects.length; nIndex++) {
                            var hitPageObjMemo = memoObjects[nIndex];
                            if (hitPageObjMemo.hitTest(imagePt.x, imagePt.y)) {
                                //console.log("PageObject Hit!! Id: " + hitPageObjMemo.id);
                                //hitPageObjMemo.action();
    
                                /* save object memo */
                                objEditMemo = hitPageObjMemo;
                                var posMemoX = _touchPageX;
                                var posMemoY = _touchPageY;
    
                                if (imagePt.y > heightEachPage - $("#pop_up_memo").height()) {
                                    posMemoY = posMemoY - $("#pop_up_memo").height();
    
                                }
    
                                if (imagePt.x > widthEachPage - $("#pop_up_memo").width()) {
                                    posMemoX = posMemoX - $("#pop_up_memo").width();
                                }
    
                                /*display pop-up-memo */
                                $("#pop_up_memo").css('top', posMemoY).css('left', posMemoX);
                                $("#pop_up_memo").show();
    
                                /*set true for flag click memo */
                                isClickMemo = true;
                                isOpenPopUpMemo = true;
    
                            }
                        }
                    }
                    
                    /* click pageObject */
                    if (isClickMemo == false) {
                        var isClickLinkList = false;
    
                        /* check exist object in mouse position */
                        var hitPageObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);
                                                                                   
                        if (hitPageObj) { 
                          
                            if(!is3DObject(hitPageObj)){
                                hitPageObj.action();    
                            }
                            else{
                                //event.preventDefault();
                            }                                                                                                
                        }
                        else {
    
                            /* check click link list */
                            for (var nIndex = 0; nIndex < webGetContentType4Objects.length; nIndex++) {
                                var hitPageObjLinkList = webGetContentType4Objects[nIndex];
                                if (hitPageObjLinkList.hitTest(imagePt.x, imagePt.y)) {
    
                                    if(hitPageObjLinkList.pageNo == changePageIndex(getPageIndex())){
                                        hitPageObjLinkList.action();
    
                                        /*set true for flag click memo */
                                        isClickLinkList = true;
                                    }                                
                                }
                            }
    
                            if (isClickLinkList == false && ClientData.IsAddingMarking() == false) {
                                /* area next and prev page */
                                var cwMain = $('#main').width();
                                if (_touchPageX > 0 && _touchPageX < 300) {
                                    prevPage_click();
                                } else if (_touchPageX > (cwMain - 300) && _touchPageX < cwMain) {
                                    nextPage_click();
                                }
                            }
                        }
                    }
                }       
            }
            else {
                if (ClientData.IsAddingMarking() == false && isCopyMemo == false) {
                    var cwMain = $('#main').width();
                    if (_touchPageX > 0 && _touchPageX < 300) {
                        prevPage_click();
                    } else if (_touchPageX > (cwMain - 300) && _touchPageX < cwMain) {
                        nextPage_click();
                    }
                }
            }
        }
       cancelClick = false;
        _isClick = false;
    }
    else{
        //Do nothing
        if(_3dAnimate == true){
            _3dAnimate = false;
            _3dAction = _3dActionType.TouchEnd_MouseUp;
            _curr3dObject.action(); 
        }
        
        if(isPageTransition){
            isPageTransition = false;
        }  
    }
};

function processZoomPage(touch1, touch2){
    
    var dist = getDistance({
            x: touch1.clientX,
            y: touch1.clientY
        }, {
            x: touch2.clientX,
            y: touch2.clientY
        });
    
    
    if(_lastDist != dist) {
        if(dist > _lastDist){               
            userScale += 0.05;
             if (userScale > 4) {
                userScale = 4;
                changeScale(userScale);
             }else {
                changeScale(userScale);
                
                flip();
                //Start Function : No.4 - Editor : Long - Date : 08/13/2013 - Summary : Fix for zooming
                
                if(getPageIndex() < totalPage - 1){
                    //START TRB00097
                    //flip(1);
                    //END TRB00097
                }
                
                if(getPageIndex() > 0){
                    //START TRB00097
                    //flip(2);
                    //END TRB00097
                }
                //End Function : No.4 - Editor : Long - Date : 08/13/2013 - Summary : Fix for zooming
                
                 /* zoom video */
                zoomVideo();
             }
             _lastDist = dist;
        }
        else if (dist < _lastDist)
        {
            userScale -= 0.05;
             if (userScale < 1) {
                userScale = 1;
                changeScale(userScale);
             }else{
                changeScale(userScale);
                flip();
                //Start Function : No.4 - Editor : Long - Date : 08/13/2013 - Summary : Fix for zooming
                if(getPageIndex() < totalPage - 1){
                    //START TRB00097
                    //flip(1);
                    //END TRB00097
                }
                
                if(getPageIndex() > 0){
                    //START TRB00097
                    //flip(2);
                    //END TRB00097
                }
                //End Function : No.4 - Editor : Long - Date : 08/13/2013 - Summary : Fix for zooming
                /* zoom video */
                zoomVideo();
             }
        }
    }
    
    checkDisableButtonZoom();    
};

/*
 * Process navi page after touch event
 */
function processNaviPage(currPos){
    if(!_bTransitionEnable){
        
        return;
    }
        
    // get moved delta period
    var lMoveX = currPos.x - _touchLastPos.x;
    
    // pevious page not exist -> do not move
    if(!getContent().hasPreviousPage()){
        if(currPos.x >= _touchFirstPos.x){
            return false;
        }           
    }

    // next page not exist -> do not move
    if(!getContent().hasNextPage()){
        if(currPos.x <= _touchFirstPos.x){
           return false; 
        }           
    }
    
    //examinate direction 
    if(_moveNum==0 &&  lMoveX  < 0){
        _moveNum = 2; // go from right to left => next page
    }
    if(_moveNum==2 &&  lMoveX  > 0){
        _moveNum = 1; // go from right to left and back to right => no move
    }
    if(_moveNum==1 &&  lMoveX  < 0){
        _moveNum = 2; // go from right to left + back to right + go to left  => next page
    }

    if(_moveNum==0 &&  lMoveX  > 0){
        _moveNum = -2; // go from  left to right=> priveous page
    }
    if(_moveNum==-2 &&  lMoveX  < 0){
        _moveNum = -1; // go from  left to right and back to left => no move
    }
    if(_moveNum==0 &&  lMoveX  > 0){
        _moveNum = -2; // go from  left to right + back to left + go to right=> priveous page
    }
    //console.log("_moveNum:" +_moveNum);
    
    if(animateType == animateTypeKeys.Type_Slide){
        var left = $('#canvasWrapper').css('left').replace("px","");
        left  =  parseInt(left) + lMoveX ;
        $('#canvasWrapper').css('left', left + "px");
    }
    _touchLastPos = {x:currPos.x, y: currPos.y};
    
    return true;
}; 

/*
 * reset zoom  action as point session increase
 */
function resetZoomAction(){
    //_isPageZoomTouch = false;
};

function getDistance(p1, p2) {

    return Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow((p2.y - p1.y), 2));
};
var TransitionObject = function () {
};
var _transitionObject = new TransitionObject();

TransitionObject.prototype.processNaviPage = function (currPos) {
    if(!_bTransitionEnable)
        return;
    // get moved delta period
    var lMoveX = currPos.x - _touchLastPos.x;
    
    // pevious page not exist -> do not move
    if(!getContent().hasPreviousPage()){
        if(currPos.x >= _touchFirstPos.x)
            return false;
    }

    // next page not exist -> do not move
    if(!getContent().hasNextPage()){
        if(currPos.x <= _touchFirstPos.x)
            return false;
    }
    //examinate direction 
    if(_moveNum==0 &&  lMoveX  < 0){
        _moveNum = 2; // go from right to left => next page
    }
    if(_moveNum==2 &&  lMoveX  > 0){
        _moveNum = 1; // go from right to left and back to right => no move
    }
    if(_moveNum==1 &&  lMoveX  < 0){
        _moveNum = 2; // go from right to left + back to right + go to left  => next page
    }

    if(_moveNum==0 &&  lMoveX  > 0){
        _moveNum = -2; // go from  left to right=> priveous page
    }
    if(_moveNum==-2 &&  lMoveX  < 0){
        _moveNum = -1; // go from  left to right and back to left => no move
    }
    if(_moveNum==0 &&  lMoveX  > 0){
        _moveNum = -2; // go from  left to right + back to left + go to right=> priveous page
    }
    //console.log("_moveNum:" +_moveNum);
    
    if(animateType == animateTypeKeys.Type_Slide){
        var left = $('#canvasWrapper').css('left').replace("px","");
        left  =  parseInt(left) + lMoveX ;
        $('#canvasWrapper').css('left', left + "px");
    }
    _touchLastPos = {x:currPos.x, y: currPos.y};
    
    return true;    
};


//End Funcion : No.20 - Editor : Long - Date : 08/13/2013 - Summary : Win 8 touch handle