
/* change size */
function sizingScreen() {
    var w, h;

    w = $(window).width();
    h = $(window).height();

    if (COMMON.isTouchDevice() == true) {
        if (avwUserEnvObj.os == "android") {
            var tempRatio = document.documentElement.clientWidth / window.innerWidth;
            if (tempRatio <= 1) {
                w = window.innerWidth;
                h = window.innerHeight;
            }
            else {
                w = $(window).width();
                h = $(window).height();
            }
        }
    }

    // Adjust the size of the View
    if (isFullScreen == true) {
        sizingFullSize(w, h);
    } else {
        sizingNotFull(w, h);
    }

};

/* memo */
function handleMemo() {
    $('#pop_up_memo').hide();

    if (ClientData.IsDisplayMemo() == true) {
        ClientData.IsDisplayMemo(false);
        isCopyMemo = false;
        
        drawCanvas();
        
        //Start Function : No.4
        if(getContent().hasNextPage()){
            drawCanvas(1);
        }
        
        if(getContent().hasPreviousPage()){
            drawCanvas(2);
        }        
        //End Function : No.4

        //change class
        $('#imgmemo').removeClass();
        if (COMMON.isTouchDevice() == true) {
            $('#imgmemo').addClass('memoDisplay_device');
        } else {
            $('#imgmemo').addClass('memoDisplay');
        }

        /*handle image add memo */
        ClientData.IsAddingMemo(false);

        //change class
        $('#imgaddmemo').removeClass();
        if (COMMON.isTouchDevice() == true) {
            $('#imgaddmemo').addClass('memoAdd_device');
        } else {
            $('#imgaddmemo').addClass('memoAdd');
        }

    } 
    else {
        ClientData.IsDisplayMemo(true);
        isCopyMemo = false;

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

    }
};


/* display canvas draw*/
function displayCanvasDraw() {
    /*set flag no image */
    isDrawing = false;

    /* clear canvas */
    context_draw.clearRect(0, 0, canvas_draw.width, canvas_draw.height);

    context_draw.save();

    /* set draw image if exist */
    var dataMarking = ClientData.MarkingData();

    for (var nIndex = 0; nIndex < dataMarking.length; nIndex++) {
        if (dataMarking[nIndex].contentid == contentID
        && dataMarking[nIndex].pageNo == changePageIndex(getPageIndex())) {
            var img = new Image();
            img.onload = function () {

                context_draw.drawImage(img, 0, 0, canvas_draw.width, canvas_draw.height);

                /*set flag has image */
                isDrawing = true;
            };
            img.src = dataMarking[nIndex].content;
        }
    }

    context_draw.restore();

    /* visible canvas using for draw */
    $('#draw_canvas').css('display', 'block');
};


/* handle draw canvas */
function handleDrawCanvas() {
    disableButtonMarking();
    if (ClientData.IsAddingMarking() == true) {
        if (ClientData.IsHideToolbar() == true) {
            ClientData.IsAddingMarking(true);
            ClientData.IsDisplayMarking(true);
            ClientData.IsHideToolbar(false);
            ShowMarking();

            $('#imgmarking').removeClass();
            $('#imgmarking').addClass('marking_off');
        }
    }
    else {
        ClientData.IsAddingMarking(true);
        ClientData.IsDisplayMarking(true);
        ClientData.IsHideToolbar(false);

        /* fit page */
        screenFit();

        /* show marking */
        ShowMarking();

        /* display fullscreen */
        handleDisplayToolbar();

        /* invisible button fullscreen */
        $('#footer_toolbar_2').hide();
        $('#control_screen_2').hide();
        
        
        //START TRB00032 - EDITOR : Long - DATE: 09/10/2013 - Summary : For Content Type None
        /* draw again */
        //drawCanvas();
        //END TRB00032 - EDITOR : Long - DATE: 09/10/2013 - Summary : For Content Type None
        
        displayCanvasDraw();
        disableAllControl();  
    }

    /* get data from local */
    getDataClientStorage();

};

/* bookmark page */
function bookmarkPage() {
    ClientData.isChangedBookmark(true);
    var nBookmarkId = isExistBookmark();
    if (nBookmarkId == -1) {
        //case not exist
        var enBookmark = new BookMarkEntity();
        enBookmark.contentid = contentID;
        enBookmark.pageNo = changePageIndex(getPageIndex());
        if(contentType == COMMON.ContentTypeKeys.Type_Image){
            enBookmark.contentTitle = imageTypeData.contentName;
            enBookmark.contentTitleKana = imageTypeData.contentNameKana;
        }
        else{
            enBookmark.contentTitle = dataWebContentPage.contentTitle;
            enBookmark.contentTitleKana = dataWebContentPage.contentTitleKana;
        }
        
        //=== Start Function : No.17    Editor : Long   Date: 07/30/2013   Summary : Set UTC time and UUID when create new bookmark.
        enBookmark.bookmarkid = COMMON.getUUID();
        enBookmark.registerDate = new Date();
        //=== Start Function : No.17    Editor : Long   Date: 07/30/2013   Summary : Set UTC time and UUID when create new bookmark.
        var listBM = [];

        if (ClientData.BookMarkData().length > 0) {
            listBM = ClientData.BookMarkData();
        }
        listBM.push(enBookmark);
        ClientData.BookMarkData(listBM);

        //change class
        $('#imgbookmark').removeClass();
        $('#imgbookmark').addClass('bmAdd_hover');

    } else {
        //delete bookmark page
        var listBM = [];
        listBM = ClientData.BookMarkData();
        listBM.splice(nBookmarkId, 1);
        ClientData.BookMarkData(listBM);

        //change class
        $('#imgbookmark').removeClass();
        if (COMMON.isTouchDevice() == true) {
            $('#imgbookmark').addClass('bmAdd_device');
        } else {
            $('#imgbookmark').addClass('bmAdd');
        }

    }
};

/* function changePage Index->pageno */
function changePageIndex(page_index) {
    //Start: Function No.12
    if(contentType == COMMON.ContentTypeKeys.Type_Image){
        return 1;
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_NoFile){
        return page_index + 1;
    }
    //End: Function No.12
    else{
        return dataWebContentPage.pages[page_index].pageNo;
    }
};

/* function change PageNo -> pageIndex */
function changePageNo(page_no) {
    
    if(contentType == COMMON.ContentTypeKeys.Type_PDF){
        var dataContent = dataWebContentPage.pages;
        for (var nIndex = 0; nIndex < dataContent.length; nIndex++) {
            if (dataContent[nIndex].pageNo == page_no) {
                return nIndex;
            }
        }
    }
    //START : TRB00032 - Editor : Long - Date : 09/10/2013 - Summary : Process Type None
    else if(contentType == COMMON.ContentTypeKeys.Type_NoFile){
        page_no = page_no - 1;
        return page_no;
    }
   //END : TRB00032 - Editor : Long - Date : 09/10/2013 - Summary : Process Type None
    return -1;
        
};

/* check page had bookmark */
function isExistBookmark() {
    var nIndexBookmark = -1;
    var listBM = [];
    if (ClientData.BookMarkData().length > 0) {
        //get list bookmark
        listBM = ClientData.BookMarkData();

        for (var nIndex = 0; nIndex < listBM.length; nIndex++) {
            //check bookmark belong contentID                               
            if (listBM[nIndex].contentid == contentID && listBM[nIndex].pageNo == changePageIndex(getPageIndex())) {
                return nIndex;
            }
        }
    }
    return nIndexBookmark;
};

/*get API WebContentPage */
function handleAPIWebContentPage(dataJson, pos) {
    var bmList = [];
    bmList = getBookMarkListByContentID();
    var dataStored = arrThumbnailsLoaded;

    var sPageNo = [];
    var nIndexBookMark = -1;
    var lstPageNoBookMark = [];

    $('#bookmarkBoxHdBM').children().remove();
    $('#bookmarkBoxHdBM').html('<a id="bookmarkClosing" class="delete" > </a>');
    $("#bookmarkClosing").click(closeBookmarkBox);
    $('#bookmarkBoxHdBM').append(I18N.i18nText('txtShioriCtnLs'));

    $('#boxBookMark').css('z-index', '101');
    $('#boxBookMark').css('display', 'block');
    $('#boxBookMark').draggable({ handle: "h1" });
    $("#boxBookMark").offset({ left: pos[0], top: pos[1] });
    $("#divListBookmark").show();
    $("#divListBookmark").offset({ left: pos[0], top: (pos[1] + $('#bookmarkBoxHdBM').height()) });
    $('#divListBookmark').children().remove();


    //Start Function : No.4 - Editor : Long - Date : 08/20/2013
    if(contentType == COMMON.ContentTypeKeys.Type_PDF){
        for (var nIndex = 0; nIndex < bmList.length; nIndex++) {
            nIndexBookMark = -1;
            var contentPage = dataJson.pages;
    
            for (var nIndexJson = 0; nIndexJson < contentPage.length; nIndexJson++) {
                if (contentPage[nIndexJson].pageNo == bmList[nIndex].pageNo) {
                    nIndexBookMark = nIndexJson;
                    break;
                }
            }
    
            if (nIndexBookMark != -1) { /* page exist */
                var nStored = checkDataLoaded(bmList[nIndex].pageNo, dataStored);
                if (nStored != -1) { /* data loaded */
                    $('#divListBookmark').append(
                        '   <li id="' + changePageNo(bmList[nIndex].pageNo) + '">' +
                        '       <img id="img_bookmark_' + bmList[nIndex].pageNo + '" class="imgbox" src="' + formatStringBase64(dataStored[nStored].pageThumbnail) + '"/>' +
                        '       <span class="mdltext">' +
                                    I18N.i18nText('txtPage') + (changePageNo(bmList[nIndex].pageNo) + 1) + '<br /> ' +
                                    COMMON.truncate(COMMON.htmlEncode(contentPage[nIndexBookMark].pageText), 20) +
                        '       </span>' +
                        '   </li>'
                        );
    
                    //Resize Image
                    var imgTemp = new Image();
    
                    imgTemp.onload = function () {
    
                        if (imgTemp.width > imgTemp.height) {
    
                            $("img.imgbox").attr('height', '');
                            $("img.imgbox").removeAttr('height');
                            $("img.imgbox").attr('width', '43');
                        }
                        else {
                            $("img.imgbox").attr('width', '');
                            $("img.imgbox").removeAttr('width');
                            $("img.imgbox").attr('height', '43');
                        }
                    };
    
                    imgTemp.src = formatStringBase64(dataStored[nStored].pageThumbnail);
    
                } 
                else { /* data not loaded*/
                    $('#divListBookmark').append(
                        '   <li id="' + changePageNo(bmList[nIndex].pageNo) + '">' +
                        '       <img id="img_bookmark_' + bmList[nIndex].pageNo + '" class="imgbox" src="img/view_loading.gif" />' +
                        '       <span class="mdltext">' +
                                    I18N.i18nText('txtPage') + (changePageNo(bmList[nIndex].pageNo) + 1) + '<br /> ' +
                                    COMMON.truncate(COMMON.htmlEncode(contentPage[nIndexBookMark].pageText), 20) +
                        '       </span>' +
                        '   </li>'
                        );
    
                    //Resize Image
                    var imgTemp = new Image();
    
                    imgTemp.onload = function () {
    
                        if (imgTemp.width > imgTemp.height) {
    
                            $("img.imgbox").attr('height', '');
                            $("img.imgbox").removeAttr('height');
                            $("img.imgbox").attr('width', '43');
                        }
                        else {
                            $("img.imgbox").attr('width', '');
                            $("img.imgbox").removeAttr('width');
                            $("img.imgbox").attr('height', '43');
                        }
                    };
    
                    imgTemp.src = "img/view_loading.gif";
                  
                    lstPageNoBookMark.push(bmList[nIndex].pageNo);
                }
    
    
            } 
            else { /* page deleted */
                $('#divListBookmark').append(
                        '   <li id="' + changePageNo(bmList[nIndex].pageNo) + '">' +
                        '       <span class="mdltext">' +
    
                        '           <span>' + I18N.i18nText('txtPage') + bmList[nIndex].pageNo + '</span> <br /> ' +
                        '       </span>' +
                        '   </li>' +
                        '   <li>' +
                        '       <span class="mdltext">' +
                        '           <span class="error">' + I18N.i18nText('msgShioriDeleted') + '</span>' +
                        '       </span>' +
                        '   </li>'
                    );
            }
        }
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Image ){
        
        for (var nIndex = 0; nIndex < bmList.length; nIndex++) {
            nIndexBookMark = -1;
            var contentPage = imageTypeData;
    

            if (contentPage.pageNo == bmList[nIndex].pageNo) {
                nIndexBookMark = nIndexJson;
            }

            if (nIndexBookMark != -1) { /* page exist */

                    $('#divListBookmark').append(
                        '   <li id="' + 0 + '">' +
                        '       <img id="img_bookmark_' + bmList[nIndex].pageNo + '" class="imgbox" src="img/view_loading.gif" />' +
                        '       <span class="mdltext">' +
                                    I18N.i18nText('txtPage') + 1 + '<br /> ' +
                                    COMMON.truncate(COMMON.htmlEncode(contentPage.contentName), 20) +
                        '       </span>' +
                        '   </li>'
                        );
    
                    //Resize Image
                    var imgTemp = new Image();
                    var imageContent = new Image();
                    var imageUrl = downloadResourceById(contentID);
                    
                    imgTemp.onload = function () {
    
                        if (imgTemp.width > imgTemp.height) {
    
                            $("img.imgbox").attr('height', '');
                            $("img.imgbox").removeAttr('height');
                            $("img.imgbox").attr('width', '43');
                        }
                        else {
                            $("img.imgbox").attr('width', '');
                            $("img.imgbox").removeAttr('width');
                            $("img.imgbox").attr('height', '43');
                        }
                        
                        imageContent.onload = function(){
                            $("img.imgbox").attr('src', imageUrl);
                        };
                        
                        imageContent.src = imageUrl;
                    };
    
                    imgTemp.src = "img/view_loading.gif";
                  
                    lstPageNoBookMark.push(bmList[nIndex].pageNo);                    
    
            } 
            else { /* page deleted */
                $('#divListBookmark').append(
                        '   <li id="' + 0 + '">' +
                        '       <span class="mdltext">' +
    
                        '           <span>' + I18N.i18nText('txtPage') + bmList[nIndex].pageNo + '</span> <br /> ' +
                        '       </span>' +
                        '   </li>' +
                        '   <li>' +
                        '       <span class="mdltext">' +
                        '           <span class="error">' + I18N.i18nText('msgShioriDeleted') + '</span>' +
                        '       </span>' +
                        '   </li>'
                    );
            }
        }
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_NoFile){
        for (var nIndex = 0; nIndex < bmList.length; nIndex++) {
            
            $('#divListBookmark').append(
                '   <li id="' + changePageNo(bmList[nIndex].pageNo) + '">' +
                '       <img id="img_bookmark_' + bmList[nIndex].pageNo + '" class="imgbox" src="img/view_loading.gif" />' +
                '       <span class="mdltext">' +
                            I18N.i18nText('txtPage') + bmList[nIndex].pageNo + '<br /> ' +
                            //COMMON.truncate(COMMON.htmlEncode(contentPage.contentName), 20) +
                '       </span>' +
                '   </li>'
            );
            
            //Resize Image
            var imgTemp = new Image();
            var imageContent = new Image();
            var imageUrl = pageImages;
            imgTemp.onload = function () {

                if (imgTemp.width > imgTemp.height) {

                    $("img.imgbox").attr('height', '');
                    $("img.imgbox").removeAttr('height');
                    $("img.imgbox").attr('width', '43');
                }
                else {
                    $("img.imgbox").attr('width', '');
                    $("img.imgbox").removeAttr('width');
                    $("img.imgbox").attr('height', '43');
                }
                
                imageContent.onload = function(){
                    $("img.imgbox").attr('src', imageUrl);
                };
                
                imageContent.src = imageUrl;
            };

            imgTemp.src = "img/view_loading.gif";
          
            lstPageNoBookMark.push(bmList[nIndex].pageNo);
            
        }
    }
    
           
    //End Function : No.4 - Editor : Long - Date : 08/20/2013
    if(contentType == COMMON.ContentTypeKeys.Type_PDF){
        if (lstPageNoBookMark.length > 0) {
            isSendingData = true;
            loadDataBookmark(lstPageNoBookMark);
        }
    }
};

/* check data has load */
function checkDataLoaded(nPageNo, arrData) {
    var nIndex = -1;
    for (var n = 0; n < arrData.length; n++) {
        if (arrData[n].pageNo == nPageNo) {
            nIndex = n;
            break;
        }
    }
    return nIndex;
};

/* sort list bookmark */
function sortBookmarkList() {
    var bmList = [];
    bmList = ClientData.BookMarkData();
    bmList.sort(function (a, b) {
        var a1 = a.pageNo, b1 = b.pageNo;
        if (a1 == b1) return 0;
        return a1 > b1 ? 1 : -1;
    });
    ClientData.BookMarkData(bmList);
};

/* create child node for list page index */
function AddChidrenNode(nodeParent, data) {
    var dataChild = [];
    $.each(data, function (index, value) {
        if (data[index].parentID == nodeParent.id) {
            dataChild.push(data[index]);
        }
    });

    $.each(dataChild, function (i, value) {
        //add child node
        var item = new TreeNode();
        item.IsCategory = false;
        //item.Text = COMMON.htmlEncode(COMMON.truncateByBytes(dataChild[i].title,30));
        /* check data text */
        if (COMMON.getBytes(dataChild[i].title) > 30) {
            item.Text = COMMON.htmlEncode(COMMON.truncateByBytes(dataChild[i].title, 30)) + '...';
        } else {
            item.Text = COMMON.htmlEncode(dataChild[i].title);
        }
        item.id = dataChild[i].ID;
        item.Value = dataChild[i].destPageNumber;

        for (var nIndex = 0; nIndex < data.length; nIndex++) {
            if (data[nIndex].parentID == item.id) {
                item.IsCategory = true;
                break;
            }
        }

        AddChidrenNode(item, data);
        nodeParent.ChildNodes.push(item);

    });
};

function copyText() {
    var w = window.open('contentview_textcopy.html');
};

/* handle data copy text */
function handleCopyTextData(data, pos) {
    /* init var page text */
    var sPageText = '';
    var w = $("#wrapper").width() / 2 - $('#boxCopyText').width() / 2;
    var h = $("#wrapper").height() / 2 - $('#boxCopyText').height() / 2;

    for (var nIndex = 0; nIndex < data.length; nIndex++) {
        /* get text of current page */
        if (data[nIndex].pageNo == changePageIndex(getPageIndex())) {
            sPageText = COMMON.htmlEncode(data[nIndex].pageText);
            break;
        }
    }

    if (sPageText == '') {
        /* create data on dialog */
        $('#divCopyText').children().remove();
        $('#divCopyText').append('<li class="last">' + I18N.i18nText('txtNoTextCopy') + '</li>');

        // $("#divCopyText").dialog({               
        // show: "blind",
        // modal: true,
        // resizable:false,
        // width: WIDTH_DIALOG_COPYTEXT,
        // height: HEIGHT_DIALOG_COPYTEXT_NO_COPYTEXT,
        // title: I18N.i18nText('txtTextCopy'),
        // position: pos});

        //title start
        $('#bookmarkBoxHdCT').children().remove();
        $('#bookmarkBoxHdCT').html('<a id="copyTextClosing" class="delete" style="padding-top:0px;"> </a>');
        $("#copyTextClosing").click(closeCopyTextBox);
        $('#bookmarkBoxHdCT').append(I18N.i18nText('txtTextCopy'));
        //title end

        //COMMON.lockLayout();
        $('#boxCopyText').css('z-index', '101');
        $('#boxCopyText').css('display', 'block');
        $('#boxCopyText').draggable({ handle: "h1" });
        $("#boxCopyText").offset({ left: w, top: h });
        $("#divCopyText").show();
        //$("#divCopyText").offset({left:"45%",top:(45% + $('#bookmarkBoxHdCT').height())});
        //$("#boxCopyText").offset({left:"45%",top:"45%"}); 

    } else {
        /* create data on dialog */
        $('#divCopyText').children().remove();
        //$('#divCopyText').append('<li class="last">' + sPageText + '</li>');

        var strPattern = "\n";
        var strTemp = sPageText;
        strTemp = strTemp.replaceAll(strPattern, "<br/>");
        strTemp += "<br/>";

        $('#divCopyText').append('<div class="last" id="txtTextCopy" style="word-wrap:break-word;line-height: 20px">' + strTemp + '</div>');

        /* display dialog */
        // $("#divCopyText").dialog({               
        // show: "blind",
        // modal: true,
        // width: WIDTH_DIALOG_COPYTEXT,
        // height:HEIGHT_DIALOG_COPYTEXT,
        // resizable: false,
        // title: I18N.i18nText('txtTextCopy'),
        // position: pos});                      

        //title start
        $('#bookmarkBoxHdCT').children().remove();
        $('#bookmarkBoxHdCT').html('<a id="copyTextClosing" class="delete" style="padding-top:0px;"> </a>');
        $("#copyTextClosing").click(closeCopyTextBox);
        $('#bookmarkBoxHdCT').append(I18N.i18nText('txtTextCopy'));

        //title end

        //COMMON.lockLayout();
        $('#boxCopyText').css('z-index', '101');
        $('#boxCopyText').css('display', 'block');
        //$('#boxCopyText').draggable({ handle: "h1" });    
        $("#boxCopyText").offset({ left: w, top: h });
        $("#divCopyText").show();
        //$("#divCopyText").offset({left:w,top:(h + $('#bookmarkBoxHdCT').height())});
        //$("#boxCopyText").offset({left:"45%",top:"45%"}); 

        /*$('#bookmarkBoxHdCT').mousedown(function(){                   
        $('#boxCopyText').draggable({ handle: "h1" });  
        });   
        $('#bookmarkBoxHdCT').mouseup(function(){
        $('#boxCopyText').unbind('draggable');  
        });*/

        if (COMMON.isTouchDevice() == true) {
            document.getElementById('bookmarkBoxHdCT').addEventListener('touchstart', eventStart_CopyText, false);
            document.getElementById('bookmarkBoxHdCT').addEventListener('touchend', eventEnd_CopyText, false);
        } else {
            document.getElementById('bookmarkBoxHdCT').addEventListener('mousedown', eventStart_CopyText, false);
            document.getElementById('bookmarkBoxHdCT').addEventListener('mouseup', eventEnd_CopyText, false);
        }
        /*$('#boxCopyText h1').touchstart(function(e){
            
        });   
        $('#boxCopyText h1').touchend(function(e){
            
        });*/
    }
};

/* event touch start header copytext */
function eventStart_CopyText(e) {
    e.preventDefault();
    $('#boxCopyText').draggable({ handle: "h1" });
};

/* event touch end header copytext */
function eventEnd_CopyText(e) {
    e.preventDefault();
    $("#boxCopyText").draggable("destroy");

};

/*format Image string */
function formatStringBase64(imgStr) {
    var outputString = 'data:image/jpeg;base64,' + imgStr;

    return outputString;
};

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

/* search content */
function searchHandle() {
    var w = $("#main").width() - $(".hdRcolumn").width();

    var pos = [w, marginY];
    if ($('#txtSearch').val() != '') {
        var dataStored = arrThumbnailsLoaded;
        var contentPage = dataWebContentPage.pages;
        var myRegExp = new RegExp($('#txtSearch').val());
        var sPageNo = [];
        var lstPageNo = [];
        var isExistData = false;

        for (var nIndex = 0; nIndex < contentPage.length; nIndex++) {
            if (myRegExp.test(contentPage[nIndex].pageText)) {
                //searchResult.push(contentPage[nIndex]);
                sPageNo.push(contentPage[nIndex]);
            }
        }

        if (sPageNo.length > 0) {
            //title start
            $('#bookmarkBoxHdSearching').children().remove();
            $('#bookmarkBoxHdSearching').html('<a id="searchingResultClosing" class="delete" > </a>');
            $("#searchingResultClosing").click(closeSearchingBox);
            $('#bookmarkBoxHdSearching').append(I18N.i18nText('txtSearchResult'));
            //title end

            //COMMON.lockLayout();
            $('#boxSearching').css('z-index', '101');
            $('#boxSearching').css('display', 'block');
            $('#boxSearching').draggable({ handle: "h1" });
            $("#boxSearching").offset({ left: pos[0], top: pos[1] });
            $("#divSearchResult").show();
            $("#divSearchResult").offset({ left: pos[0], top: (pos[1] + $('#bookmarkBoxHdSearching').height() - 2) });

            $('#divSearchResult').children().remove();

            for (var i = 0; i < sPageNo.length; i++) {
                var nStored = checkDataLoaded(sPageNo[i].pageNo, dataStored);
                if (nStored != -1) { /* data loaded */
                    $('#divSearchResult').append(
                        '   <li id="' + changePageNo(sPageNo[i].pageNo) + '">' +
                        '       <img id="img_search_' + sPageNo[i].pageNo + '" class="imgbox" src="' + formatStringBase64(dataStored[nStored].pageThumbnail) + '"/>' +
                        '       <span class="mdltext">' +
                                    I18N.i18nText('txtPage') + (changePageNo(sPageNo[i].pageNo) + 1) + '<br /> ' +
                                    COMMON.htmlEncode(COMMON.truncate(sPageNo[i].pageText, 20)) +
                        '       </span>' +
                        '   </li>'
                    );

                    //Resize Image
                    var imgTemp = new Image();

                    imgTemp.onload = function () {

                        if (imgTemp.width > imgTemp.height) {

                            $("img.imgbox").attr('height', '');
                            $("img.imgbox").removeAttr('height');
                            $("img.imgbox").attr('width', '43');
                        }
                        else {
                            $("img.imgbox").attr('width', '');
                            $("img.imgbox").removeAttr('width');
                            $("img.imgbox").attr('height', '43');
                        }
                    };

                    imgTemp.src = formatStringBase64(dataStored[nStored].pageThumbnail);
                } else {
                    $('#divSearchResult').append(
                        '   <li id="' + changePageNo(sPageNo[i].pageNo) + '">' +
                        '       <img id="img_search_' + sPageNo[i].pageNo + '" class="imgbox" src="img/view_loading.gif"/>' +
                        '       <span class="mdltext">' +
                                    I18N.i18nText('txtPage') + (changePageNo(sPageNo[i].pageNo) + 1) + '<br /> ' +
                                    COMMON.htmlEncode(COMMON.truncate(sPageNo[i].pageText, 20)) +
                        '       </span>' +
                        '   </li>'
                    );

                    //Resize Image
                    var imgTemp = new Image();

                    imgTemp.onload = function () {

                        if (imgTemp.width > imgTemp.height) {

                            $("img.imgbox").attr('height', '');
                            $("img.imgbox").removeAttr('height');
                            $("img.imgbox").attr('width', '43');
                        }
                        else {
                            $("img.imgbox").attr('width', '');
                            $("img.imgbox").removeAttr('width');
                            $("img.imgbox").attr('height', '43');
                        }
                    };

                    imgTemp.src = "img/view_loading.gif";

                    lstPageNo.push(sPageNo[i].pageNo);                  
                }
            }

            if (lstPageNo.length > 0) {
                isSendingData = true;
                loadDataSearch(lstPageNo);
            }
        } else {
            $('#divSearchResult').children().remove();
            $('#divSearchResult').append('<span class="last">' + I18N.i18nText('txtNoSearchResult') + '</span>');

            //title start
            $('#bookmarkBoxHdSearching').children().remove();
            $('#bookmarkBoxHdSearching').html('<a id="searchingResultClosing" class="delete" > </a>');
            $("#searchingResultClosing").click(closeSearchingBox);
            $('#bookmarkBoxHdSearching').append(I18N.i18nText('txtSearchResult'));
            //title end

            //COMMON.lockLayout();
            $('#boxSearching').css('z-index', '101');
            $('#boxSearching').css('display', 'block');
            $('#boxSearching').draggable({ handle: "h1" });
            $("#boxSearching").offset({ left: pos[0], top: pos[1] });
            $("#divSearchResult").show();
            $("#divSearchResult").offset({ left: pos[0], top: (pos[1] + $('#bookmarkBoxHdSearching').height() - 2) });
        }
    }
};

/* load data to dialog search */
function loadDataToDialogSearch(searchResultTemp) {

    var contentPage = dataWebContentPage.pages;
    var myRegExp = new RegExp($('#txtSearch').val());
    var searchResult = [];

    //search content        
    for (var nIndex = 0; nIndex < contentPage.length; nIndex++) {
        if (myRegExp.test(contentPage[nIndex].pageText)) {
            //var n = jQuery.inArray(contentPage[nIndex].pageNo,searchResultTemp);
            for (var n = 0; n < searchResultTemp.length; n++) {
                if (searchResultTemp[n].pageNo == contentPage[nIndex].pageNo) {
                    searchResult.push(searchResultTemp[n]);
                    break;
                }
            }

        }
    }

    /* create data on dialog */
    $('#divSearchResult').children().remove();
    for (var nIndex = 0; nIndex < searchResult.length; nIndex++) {
        $('#divSearchResult').append(
                    '   <li id="' + changePageNo(searchResult[nIndex].pageNo) + '">' +
                    '       <img class="imgbox" src="' + formatStringBase64(searchResult[nIndex].pageThumbnail) + '"/>' +
                    '       <span class="mdltext">' +
                                I18N.i18nText('txtPage') + (changePageNo(searchResult[nIndex].pageNo) + 1) + '<br /> ' +
                                COMMON.htmlEncode(COMMON.truncate(searchResult[nIndex].pageText, 20)) +
                    '       </span>' +
                    '   </li>'
                );

        //Resize Image
        var imgTemp = new Image();

        imgTemp.onload = function () {

            if (imgTemp.width > imgTemp.height) {

                $("img.imgbox").attr('height', '');
                $("img.imgbox").removeAttr('height');
                $("img.imgbox").attr('width', '43');
            }
            else {
                $("img.imgbox").attr('width', '');
                $("img.imgbox").removeAttr('width');
                $("img.imgbox").attr('height', '43');
            }
        };

        imgTemp.src = formatStringBase64(searchResult[nIndex].pageThumbnail);
    }
};

function playBGMOfPage(page_index_bg) {
    if (avwUserEnvObj.os == "ipad") {
        if ($('#playaudiopage').children().length > 0) {
            $('#playaudiopage').children().remove();
        }
        getPageObjectsByPageIndex(pageObjectsData, page_index_bg);
        for (var nIndex = 0; nIndex < pageObjects.length; nIndex++) {
            if (pageObjects[nIndex].mediaType == '3' && pageObjects[nIndex].playType == '2') {
                stopAllAudio();
                TypeAudio2 = pageObjects[nIndex].playType;
                srcAudioType2 = pageObjects[nIndex].audioFile;

                if (ClientData.userOpt_musicMode() == "1") {
                    $('#playaudiopage').html(
                             '  <audio  id="play_audio_2" loop="loop" >' +
                             '       <source src="' + srcAudioType2 + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
                             '  </audio>'
                         );
                } else {

                    $('#playaudiopage').html(
                         '  <audio  id="play_audio_2"  >' +
                         '       <source src="' + srcAudioType2 + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
                         '  </audio>'
                     );
                }
                document.getElementById('play_audio_2').load();
                document.getElementById('play_audio_2').play();
                document.getElementById("play_audio_2").pause();
            }
        }
    }
};

function playBGMOfContent() {
    if (avwUserEnvObj.os == "ipad" && isJumpNotFromFirstPage == true) {
        isJumpNotFromFirstPage = false;
        getPageObjectsByPageIndex(pageObjectsData, 0);
        for (var nIndex = 0; nIndex < pageObjects.length; nIndex++) {
            if (pageObjects[nIndex].mediaType == '3' && pageObjects[nIndex].playType == '1') {
                stopAllAudio();
                TypeAudio1 = pageObjects[nIndex].playType;
                srcAudioType1 = pageObjects[nIndex].audioFile;

                if (ClientData.userOpt_musicMode() == "1") {
                    $('#playaudioallpage').html(
                         '  <audio  id="play_audio_1" loop="loop"   >' +
                         '       <source src="' + srcAudioType1 + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
                         '  </audio>'
                     );
                } else {

                    $('#playaudioallpage').html(
                     '  <audio  id="play_audio_1" >' +
                     '       <source src="' + srcAudioType1 + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
                     '  </audio>'
                 );
                }
                document.getElementById('play_audio_1').load();
                document.getElementById('play_audio_1').play();
                document.getElementById("play_audio_1").pause();
            }
        }
    }
};

/* display error screen*/
function showErrorScreen() {

    // エラーメッセージの表示
    var errMes = I18N.i18nText('msgPageImgErr');
    //if( errMsg == undefined || errMsg == "" ){
    //    errMes = I18N.i18nText('msgPageImgErr');
    //}
    $('#divImageLoading').css('display', 'none');
    COMMON.lockLayout();
    /* show error messages */
    $().toastmessage({ position: 'middle-center' });
    $().toastmessage('showToast', {
        type: 'error',
        sticky: true,
        text: errMes,
        close: function () { isShowErrorMessage = false; }
    });
    $('.toast-type-error').css('height', '100px');
    $('.toast-type-error > p').css('padding-top', '35px');
    $('.toast-item-close').live('click', imgBack_click);
};

/* display alert screen*/
function showAlertScreen(errMes) {

    // アラートメッセージの表示
    if( errMes == undefined || errMes == "" ){
        errMes = "message."; //I18N.i18nText('msgPageImgErr');
    }
    $('#divImageLoading').css('display', 'none');
    COMMON.lockLayout();
    /* show error messages */
    $().toastmessage({ position: 'middle-center' });
    $().toastmessage('showToast', {
        type: 'error',
        sticky: true,
        text: errMes,
        close: function () {}
    });
    $('.toast-type-error').css('height', '100px');
    $('.toast-type-error > p').css('padding-top', '35px');
    $('.toast-item-close').live('click',
        function () {
            COMMON.unlockLayout();
        }
    );
};



/* move to page ?? */
function changePage(page_index) {

    //abe スライダーのページ移動
    //alert("changePage:" + page_index);

    // Make sure page_index is number
    page_index = Number(page_index);

    if (page_index != getContent().pageIndex) {
        
        playBGMOfContent();
        playBGMOfPage(page_index);

        disableAllControl();

        $('#divImageLoading').css('display', 'block');
        //Start Function : No.4 - Editor : Long - Date : 08/19/2013
        if(page_index == getContent().pageIndex + 1){
            nextPage_click();
        }
        else if(page_index == getContent().pageIndex - 1){
            prevPage_click();
        }
        //End Function : No.4 - Editor : Long - Date : 08/19/2013
        else{
        
            //ページ閲覧ログセット
            COMMON.SetPageLog( contentID, page_index);
        
            // Clear canvas offscreen
            clearCanvas(document.getElementById("offscreen"));
            
            if(contentType == COMMON.ContentTypeKeys.Type_PDF){
                avwGrabContentPageImage(ClientData.userInfo_accountPath(),
                     { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: page_index + 1 },
                     function (data) {
                         pageImages = data;
        
                         /* get page Objects */
                         getPageObjectsByPageIndex(pageObjectsData, page_index);
                         getContent().setPageImages(totalPage, pageImages)
                                     .setPageObjects(pageObjects);
         
        
                         //$('#divImageLoading').css('display', 'none');
                                                                   
                         var tran = new Transition();
                         tran.flipToPage(page_index);
        
                     },
                     function (xmlHttpRequest, txtStatus, errorThrown) {
                         showErrorScreen();
                     });               
           }
           //START : TRB00032 - Editor : Long - Date: 09/10/2013 - Summary : type none process
           else if(contentType == COMMON.ContentTypeKeys.Type_NoFile){
                 /* get page Objects */
                 getPageObjectsByPageIndex(pageObjectsData, page_index);
                 getContent().setPageImages(totalPage, pageImages)
                             .setPageObjects(pageObjects);
 

                 $('#divImageLoading').css('display', 'none');
                                                       
                var tran = new Transition();
                tran.flipToPage(page_index);
            }
            //END : TRB00032 - Editor : Long - Date: 09/10/2013 - Summary : type none process
        }        
    } else if (ClientData.IsJumpBack() == true
       || ClientData.common_prePageNo()) {
        getContent().setPageImages(totalPage, pageImages)
                                    .setPageObjects(pageObjects)
                                    .setUpPage(0);
       //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                              
    }
};

/* add event draw on canvas */
function drawOnCanvas() {
    tool = new tool_drawing();
    if (COMMON.isTouchDevice() == true) {
        initializeCanvas(document.getElementById('draw_canvas'));
        initializeCanvas(document.getElementById('marker_canvas'));
        
        //iOSかAndroid以外ならmarkerではmouseも発火させる
        if(avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android"){
            //draw_canvas
            canvas_draw.addEventListener('mousedown', ev_canvas, false);
            canvas_draw.addEventListener('mousemove', ev_canvas, false);
            canvas_draw.addEventListener('mouseup', ev_canvas, false);
            canvas_draw.addEventListener('mouseout', ev_canvas, false);
            //marker_canvas
            canvas_marker.addEventListener('mousedown', ev_canvas, false);
            canvas_marker.addEventListener('mousemove', ev_canvas, false);
            canvas_marker.addEventListener('mouseup', ev_canvas, false);
            canvas_marker.addEventListener('mouseout', ev_canvas, false);
        }
        
    }
    else {
        // Attach the mousedown, mousemove and mouseup event listeners.
        canvas_draw.addEventListener('mousedown', ev_canvas, false);
        canvas_draw.addEventListener('mousemove', ev_canvas, false);
        canvas_draw.addEventListener('mouseup', ev_canvas, false);
        canvas_draw.addEventListener('mouseout', ev_canvas, false);
        canvas_draw.addEventListener('touchstart', ev_canvas, false);
        canvas_draw.addEventListener('touchmove', ev_canvas, false);
        canvas_draw.addEventListener('touchend', ev_canvas, false);

        canvas_marker.addEventListener('mousedown', ev_canvas, false);
        canvas_marker.addEventListener('mousemove', ev_canvas, false);
        canvas_marker.addEventListener('mouseup', ev_canvas, false);
        canvas_marker.addEventListener('mouseout', ev_canvas, false);

    }
};

function drawMouseMove(contextDraw, ev) {
    if (tool.started && isPressLeftMouse == true) {

        if (isMoveOutDrawCanvas == true) {
            contextDraw.moveTo(ev._x, ev._y);
            sx = ev._x;
            sy = ev._y;
            isMoveOutDrawCanvas = false;
        }

        if (markingType == 'eraser') {
            //context.clearRect(ev._x, ev._y, ClientData.erase_size(), ClientData.erase_size());
            contextDraw.globalCompositeOperation = 'destination-out';
            contextDraw.lineWidth = eraseSize;
            contextDraw.lineJoin = 'round';
            contextDraw.lineCap = 'round';
            contextDraw.lineTo(sx, sy);
            contextDraw.stroke();
            contextDraw.globalCompositeOperation = 'source-over';
        }
        else if (markingType == 'pen') {
            contextDraw.lineCap = "round";
            contextDraw.lineJoin = "bevel";
            contextDraw.lineWidth = penSize;
            contextDraw.strokeStyle = "#" + penColor;
            contextDraw.lineTo(ev._x, ev._y);
            contextDraw.stroke();
        }
        else if (markingType == 'maker') {

            contextDraw.beginPath();

            var halfSize = makerSize / 2;
            var quotSize = makerSize / 4;

            var ptStart = [
                        { x: sx - quotSize, y: sy - halfSize },
                        { x: sx + quotSize, y: sy - halfSize },
                        { x: sx + quotSize, y: sy + halfSize },
                        { x: sx - quotSize, y: sy + halfSize }
                  ];
            var ptEnd = [
                                { x: ev._x - quotSize, y: ev._y - halfSize },
                                { x: ev._x + quotSize, y: ev._y - halfSize },
                                { x: ev._x + quotSize, y: ev._y + halfSize },
                                { x: ev._x - quotSize, y: ev._y + halfSize }
                ];
            if (sx > ev._x) {
                if (sy > ev._y) {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();
                    // 蟾ｦ荳翫↓謠冗判縺吶ｋ蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.closePath();
                } else if (sy < ev._y) {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();

                    // 蟾ｦ荳九↓謠冗判縺吶ｋ蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.closePath();
                } else {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();

                    // 蟾ｦ縺ｫ謠冗判縺吶ｋ蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.closePath();
                }
            } else if (sx < ev._x) {
                if (sy > ev._y) {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();

                    // 蜿ｳ荳翫↓謠冗判縺吶ｋ蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.closePath();
                } else if (sy < ev._y) {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();

                    // 蜿ｳ荳九↓謠冗判縺吶ｋ蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.closePath();
                } else {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();

                    // 蜿ｳ縺ｫ謠冗判縺吶ｋ蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.closePath();
                }
            } else {
                if (sy > ev._y) {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();

                    // 荳翫↓謠冗判縺吶ｋ蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineTo(ptEnd[0].x, ptEnd[0].y);
                    contextDraw.lineTo(ptEnd[1].x, ptEnd[1].y);
                    contextDraw.closePath();
                } else if (sy < ev._y) {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();

                    // 荳九↓謠冗判縺吶ｋ蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptEnd[2].x, ptEnd[2].y);
                    contextDraw.lineTo(ptEnd[3].x, ptEnd[3].y);
                    contextDraw.closePath();
                } else {
                    contextDraw.beginPath();
                    contextDraw.globalCompositeOperation = 'destination-out';
                    contextDraw.moveTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.lineJoin = 'bevel';
                    contextDraw.lineCap = 'butt';
                    contextDraw.fillStyle = "#" + makerColor;
                    contextDraw.fill();
                    contextDraw.globalCompositeOperation = 'lighter';
                    contextDraw.closePath();
                    contextDraw.beginPath();

                    // 遘ｻ蜍輔↑縺励・蝣ｴ蜷・
                    contextDraw.moveTo(ptStart[0].x, ptStart[0].y);
                    contextDraw.lineTo(ptStart[1].x, ptStart[1].y);
                    contextDraw.lineTo(ptStart[2].x, ptStart[2].y);
                    contextDraw.lineTo(ptStart[3].x, ptStart[3].y);
                    contextDraw.closePath();
                }
            }
            contextDraw.lineJoin = 'bevel';
            contextDraw.lineCap = 'butt';
            contextDraw.globalAlpha = 0.4;   // Opacity 20%
            contextDraw.fillStyle = "#" + makerColor;
            contextDraw.fill();

            contextDraw.globalAlpha = 1;   // Opacity 100%
        }


        /*
        * 謠冗判繝｢繝ｼ繝峨ｒ謌ｻ縺・
        */
        contextDraw.globalCompositeOperation = 'source-over';

        // 邨らせ繧剃ｿ晏ｭ・
        sx = ev._x;
        sy = ev._y;


    }
};


/* event mouse using for canvas */
function tool_drawing() {
    var tool = this;
    this.started = false;

    this.mousedown = function (ev) {
        ev.preventDefault();

        /* set value sx,sy */
        sx = ev._x;
        sy = ev._y;

        if ($("#marker_canvas").is(":hidden")) {
            context_draw.beginPath();
            context_draw.moveTo(ev._x, ev._y);
        } else {
            context_marker.beginPath();
            context_marker.moveTo(ev._x, ev._y);
        }

        if (isAddingMarking == true) {
            /* begin draw*/
            isClearDrawing = false;

            if ($("#marker_canvas").is(":hidden")) {
                if (markingType == 'eraser') {
                    context_draw.globalCompositeOperation = 'destination-out';
                    context_draw.lineWidth = eraseSize;
                    context_draw.lineJoin = 'round';
                    context_draw.lineCap = 'round';
                    context_draw.lineTo(ev._x + 0.001, ev._y + 0.001);
                    context_draw.stroke();
                    context_draw.globalCompositeOperation = 'source-over';
                }
                else if (markingType == 'pen') {
                    /* set flag */
                    isDrawing = true;

                    context_draw.lineCap = "round";
                    context_draw.lineWidth = penSize;
                    context_draw.strokeStyle = "#" + penColor;
                    context_draw.lineTo(ev._x + 0.001, ev._y + 0.001);
                    context_draw.stroke();
                }
                else if (markingType == 'maker') {
                    /* set flag */
                    isDrawing = true;

                    context_draw.globalCompositeOperation = 'destination-out';
                    context_draw.lineWidth = makerSize;
                    context_draw.lineHeight = makerSize;
                    context_draw.lineTo(ev._x, ev._y + 0.001);
                    context_draw.lineCap = 'square';
                    context_draw.strokeStyle = "#" + makerColor;
                    context_draw.stroke();
                    context_draw.globalCompositeOperation = 'lighter';

                    context_draw.lineCap = "square";
                    context_draw.lineWidth = makerSize;
                    context_draw.lineHeight = makerSize;
                    context_draw.globalAlpha = 0.4;
                    context_draw.strokeStyle = "#" + makerColor;
                    context_draw.lineTo(ev._x, ev._y + 0.001);
                    context_draw.stroke();
                    context_draw.globalAlpha = 1;
                }
            } else {
                if (markingType == 'eraser') {
                    context_marker.globalCompositeOperation = 'destination-out';
                    context_marker.lineWidth = eraseSize;
                    context_marker.lineJoin = 'round';
                    context_marker.lineCap = 'round';
                    context_marker.lineTo(ev._x + 0.001, ev._y + 0.001);
                    context_marker.stroke();
                    context_marker.globalCompositeOperation = 'source-over';
                }
                else if (markingType == 'pen') {
                    /* set flag */
                    isDrawing = true;

                    context_marker.lineCap = "round";
                    context_marker.lineWidth = penSize;
                    context_marker.strokeStyle = "#" + penColor;
                    context_marker.lineTo(ev._x + 0.001, ev._y + 0.001);
                    context_marker.stroke();
                }
                else if (markingType == 'maker') {
                    /* set flag */
                    isDrawing = true;

                    context_marker.globalCompositeOperation = 'destination-out';
                    context_marker.lineWidth = makerSize;
                    context_marker.lineHeight = makerSize;
                    context_marker.lineTo(ev._x, ev._y + 0.001);
                    context_marker.lineCap = 'square';
                    context_marker.strokeStyle = "#" + makerColor;
                    context_marker.stroke();
                    context_marker.globalCompositeOperation = 'lighter';

                    context_marker.lineCap = "square";
                    context_marker.lineWidth = makerSize;
                    context_marker.lineHeight = makerSize;
                    context_marker.globalAlpha = 0.4;
                    context_marker.strokeStyle = "#" + makerColor;
                    context_marker.lineTo(ev._x, ev._y + 0.001);
                    context_marker.stroke();
                    context_marker.globalAlpha = 1;
                }
            }
            tool.started = true;

            if (ev.which == 1) { isPressLeftMouse = true; }
        }

        //context_draw.closePath(); 
    };

    this.mousemove = function (ev) {
        ev.preventDefault();
        if (isAddingMarking == true) {
            if ($("#marker_canvas").is(":hidden")) {
                drawMouseMove(context_draw, ev);
            } else {
                drawMouseMove(context_marker, ev);
            }

        }
    };


    this.mouseup = function (ev) {
        if (tool.started) {
            //tool.mousemove(ev);
            tool.started = false;
            //context_draw.closePath();        
            //isPressLeftMouse = false;
        }
    };

    this.mouseout = function (ev) {

        if (tool.started) {
            //tool.mousemove(ev);
            //tool.started = false;
            //context_draw.closePath();
            isMoveOutDrawCanvas = true;
        }

        /*if(isPressLeftMouse == true){
        isMoveOutDrawCanvas = true;     
        }else{
        tool.started = false;           
        }*/
    };

    /*tablet [start]*/
    this.touchstart = function (ev) {
        /*ev.preventDefault();
        tool.mousedown(ev);*/
        var touches = ev.changedTouches, first = touches[0], type = "";

        switch (ev.type) {
            case "touchstart": type = "mousedown"; break;
            case "touchmove": type = "mousemove"; break;
            case "touchend": type = "mouseup"; break;
            default: return;
        }

        var simulatedEvent = document.createEvent("MouseEvent");

        simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null);
        first.target.dispatchEvent(simulatedEvent);

        ev.preventDefault();


    };

    this.touchmove = function (ev) {
        /*ev.preventDefault();
        tool.mousemove(ev);*/
        var touches = ev.changedTouches, first = touches[0], type = "";

        switch (ev.type) {
            case "touchstart": type = "mousedown"; break;
            case "touchmove": type = "mousemove"; break;
            case "touchend": type = "mouseup"; break;
            default: return;
        }

        var simulatedEvent = document.createEvent("MouseEvent");

        simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null);
        first.target.dispatchEvent(simulatedEvent);

        ev.preventDefault();


    };

    this.touchend = function (ev) {
        /*ev.preventDefault();
        tool.mouseup(ev);*/
        var touches = ev.changedTouches, first = touches[0], type = "";

        switch (ev.type) {
            case "touchstart": type = "mousedown"; break;
            case "touchmove": type = "mousemove"; break;
            case "touchend": type = "mouseup"; break;
            default: return;
        }

        var simulatedEvent = document.createEvent("MouseEvent");

        simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null);
        first.target.dispatchEvent(simulatedEvent);
        ev.preventDefault();


    };
    /* tablet [end]*/

}

function ev_canvas(ev) {
    if (ev.offsetX || ev.offsetX == 0) { // Opera
        ev._x = ev.offsetX;
        ev._y = ev.offsetY;
    } else if (ev.layerX || ev.layerX == 0) { // Firefox
        ev._x = ev.layerX;
        ev._y = ev.layerY;
    }

    // Call the event handler of the tool.
    var func = tool[ev.type];
    if (func) {
        func(ev);
    }
};

$(document).mouseup(function (e) {
    if (e.which == 1) isPressLeftMouse = false
});

/* handle display page from book mark page */
function handleFromBookMarkPage() {

    isJumpNotFromFirstPage = true;

    /* check exist pageno */
    if (ClientData.bookmark_pageNo()) {
        changePageWithoutSlide(changePageNo(ClientData.bookmark_pageNo()));
        ClientData.bookmark_pageNo(null)
    }
};

/* handle display page from actiontype=10 mediaType =1 :jump to content */
function handleFromJumpContent() {

    isJumpNotFromFirstPage = true;

    /* check exist pageno */
    if (ClientData.common_prePageNo()) {
        //changePage(changePageNo(ClientData.common_prePageNo()));
        changePageWithoutSlide(changePageNo(ClientData.common_prePageNo()));
        //LocalStorageUtils.remove(COMMON.Keys.common_prePageNo);
        ClientData.common_prePageNo(null)
    }
};

/* handle button back */
function oldContent_Back() {
                    
    isJumpNotFromFirstPage = true;

    var oldDataBack = ClientData.JumpQueue();
    var oldContent = oldDataBack[oldDataBack.length - 1];

    /*move to page */
    //changePage(oldContent.oldPageIndex);
    changePageWithoutSlide(oldContent.oldPageIndex);

    /*remove*/
    oldDataBack.splice(oldDataBack.length - 1, 1);
    ClientData.JumpQueue(oldDataBack);
    ClientData.IsJumpBack(false);


};

/* handle display or hide toolbar */
function handleDisplayToolbar() {
    if (isLoadingObject == false) {
        /* save marking */
        var canvas = document.getElementById('draw_canvas');
        var context = canvas.getContext('2d');

        if (ClientData.IsAddingMarking() == true) {
            imgDrawingTemp = canvas.toDataURL("image/png");
            imgMarkerTemp = canvas_marker.toDataURL("image/png;")
        }

        var w = $("#wrapper").width();
        var h = $("#wrapper").height();

        if ($("#header_toolbar").is(":hidden")) {
            isFullScreen = false;

            $('#footer_toolbar_1').show();
            $('#footer_toolbar_2').hide();
            $('#control_screen_2').hide();
            $('#header_toolbar').show();
            sizingNotFull(w, h);
            drawCanvas();
            
            //edit
            if(getPageIndex() > 0){
                drawCanvas(2);
            }
            
            if(getPageIndex() < totalPage - 1){
                drawCanvas(1);
            }

        } 
        else {
            isFullScreen = true;

            $('#header_toolbar').hide();
            //START TRB00097
            //$('#footer_toolbar_2').show();
            //END TRB00097
            $('#control_screen_2').show();
            $('#footer_toolbar_1').hide();
            sizingFullSize(w, h);
            
            drawCanvas();
            
            if(getPageIndex() > 0){
                drawCanvas(2);
            }
            
            if(getPageIndex() < totalPage - 1){
                drawCanvas(1);
            }

        }
        /* init image had draw */
        //initDisplayMarking();
        resizeCanvasDraw();

        if (ClientData.IsAddingMarking() == true) {
            var img = new Image();
            img.onload = function () {
                context.drawImage(img, 0, 0, canvas.width, canvas.height);
            };
            img.src = imgDrawingTemp;

            var imgMarker = new Image();
            imgMarker.onload = function () {
                context_marker.drawImage(imgMarker, 0, 0, canvas_marker.width, canvas_marker.height);
            };
            img.src = imgMarkerTemp;

        }
    }

    closeDialogPopUpText();
};

/* resizing canvas draw */
function resizeCanvasDraw() {
    flip();
    if (isFullScreen == true) {
        $("#draw_canvas").attr('height', destRect.bottom - destRect.top)
              .attr('width', destRect.right - destRect.left)
               .css('top', destRect.top)
               .css('left', destRect.left + marginX);

        $("#marker_canvas").attr('height', destRect.bottom - destRect.top)
              .attr('width', destRect.right - destRect.left)
               .css('top', destRect.top)
               .css('left', destRect.left + marginX);

    } else {
        $("#draw_canvas").attr('height', destRect.bottom - destRect.top)
              .attr('width', destRect.right - destRect.left)
               .css('top', destRect.top + marginY)
               .css('left', destRect.left + marginX);
        $("#marker_canvas").attr('height', destRect.bottom - destRect.top)
              .attr('width', destRect.right - destRect.left)
               .css('top', destRect.top + marginY)
               .css('left', destRect.left + marginX);

    }
};

/* handle slider bar */
function handleSliderBar() {
 
    $("#slider_page").slider({
        range: "max",
        min: 1,
        max: totalPage,
        value: getPageIndex() + 1,
        slide: function (event, ui) {
            $("#txtSlider").val(ui.value);
            //changePage(ui.value - 1);
        },
        stop: function (event, ui) {
            changePage(ui.value - 1);
        }
        
    });


    $("#txtSlider").val($("#slider_page").slider("value"));

    /* event change txtProcess */
    $('#txtSlider').keydown(function (event) {
        if (event.keyCode == 13) {
            if (parseInt($('#txtSlider').val()) <= 0) {
                $('#txtSlider').val('1');
            } else if (parseInt($('#txtSlider').val()) > totalPage) {
                $('#txtSlider').val(totalPage);
            } else if (/\D/g.test($('#txtSlider').val())) {
                $('#txtSlider').val('1');
            }

            if (parseInt($('#txtSlider').val()) - 1 != getPageIndex()) {

                $("#slider_page").slider("value", $('#txtSlider').val());
                changePage($('#txtSlider').val() - 1);
            }
        }
        else {

        }
    });
};

/* event when change page */
function changeSlider(page_index) {
    $("#slider_page").slider("value", page_index + 1);
    $("#txtSlider").val(page_index + 1);
};

/* handle display value tooltip */
function handleTooltip() {
    /*$('#imgHome').attr('title', I18N.i18nText('dspHome'));
    $('#imgBack').attr('title', I18N.i18nText('txtTooltipBack'));
    $('#listbookmark').attr('title', I18N.i18nText('txtShioriCtnLs'));
    $('#imgbookmark').attr('title', I18N.i18nText('txtTooltipBookmark'));
    $('#listindex').attr('title', I18N.i18nText('txtIndex'));
    $('#copytext').attr('title', I18N.i18nText('txtTextCopy'));
    $('#imgmemo').attr('title', I18N.i18nText('txtTooltipShowMemo'));
    $('#imgaddmemo').attr('title', I18N.i18nText('txtTooltipAddMemo'));
    $('#imgmarking').attr('title', I18N.i18nText('txtTooltipShowMarking'));
    $('#imgmarkingtoolbar').attr('title', I18N.i18nText('txtTooltipShowMarkingTool'));       */
};

function StartTimerUpdateLog() {
    /* set end log */
    COMMON.SetEndLog(contentID);
    setTimeout("StartTimerUpdateLog();", 1000);
};

/* check status image show toolbar marking */
function checkStatusImageMarking() {
    if (ClientData.serviceOpt_marking() == 'Y') {
        $('#imgmarkingtoolbar').bind('click', handleDrawCanvas);
    } else {
        $('#imgmarkingtoolbar').unbind('click');
    }
};

function resizeScreen() {
    /* save marking */
    var canvas = document.getElementById('draw_canvas');
    var context = canvas.getContext('2d');

    if (ClientData.IsAddingMarking() == true) {
        imgDrawingTemp = canvas.toDataURL("image/png");
        imgMarkerTemp = canvas_marker.toDataURL("image/png"); ;
    }

    sizingScreen();
    resizeCanvasDraw();
    drawCanvas();
    
    if(getPageIndex() > 0){
        drawCanvas(2);
    }
    
    if(getPageIndex() < totalPage - 1){
        drawCanvas(1);
    }
        
    if (ClientData.IsAddingMarking() == true) {
        var img = new Image();
        img.onload = function () {
            context.drawImage(img, 0, 0, canvas.width, canvas.height);
        };
        img.src = imgDrawingTemp;

        var imgMarker = new Image();
        imgMarker.onload = function () {
            context_marker.drawImage(imgMarker, 0, 0, canvas_marker.width, canvas_marker.height);
        };
        imgMarker.src = imgMarkerTemp;

    }
    
    // resize anket
    resizeAnket();
};

var isPendingContentBGM = false;

function changePageWithoutSlide(pageMove) {

    //abe コンテンツリンクで移動時
    //alert("changePageWithoutSlide:" + pageMove);
    //ページ閲覧ログセット
    COMMON.SetPageLog( contentID, pageMove);

    disableAllControl();
    var isExistBGMPageContent = false;
    getPageObjectsByPageIndex(pageObjectsData, pageMove);
    for (var nIndex = 0; nIndex < pageObjects.length; nIndex++) {
        if (pageObjects[nIndex].mediaType == '3' && pageObjects[nIndex].playType == '2') {
            isExistBGMPageContent = true;
        }
    }

    if (isExistBGMPageContent == false) {
        getPageObjectsByPageIndex(pageObjectsData, 0);
        for (var nIndex = 0; nIndex < pageObjects.length; nIndex++) {
            if (pageObjects[nIndex].mediaType == '3' && pageObjects[nIndex].playType == '1') {
                createAudio(pageObjects[nIndex].audioFile, pageObjects[nIndex].playType);
            }
        }
    }
    //START TRB00069
    else{
        getPageObjectsByPageIndex(pageObjectsData, 0);
        for (var nIndex = 0; nIndex < pageObjects.length; nIndex++) {
            if (pageObjects[nIndex].mediaType == '3' && pageObjects[nIndex].playType == '1') {                                                             
                isPendingContentBGM = true;                
                if(pageMove > 0){
                    createAudio(pageObjects[nIndex].audioFile, pageObjects[nIndex].playType);
                }                                         
            }
        }
    }
    //END TRB00069

    $('#divImageLoading').css('display', 'block');

    // Clear canvas offscreen
    clearCanvas(document.getElementById("offscreen"));

    if(contentType == COMMON.ContentTypeKeys.Type_PDF){
        avwGrabContentPageImage(ClientData.userInfo_accountPath(),
             { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: pageMove + 1 },
             function (data) {
                 pageImages = data;
    
                 /* get page Objects */
                 getPageObjectsByPageIndex(pageObjectsData, pageMove);
                 getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);
    
                 $('#divImageLoading').css('display', 'none');
    
                 isFirstLoad = true;
                 // screenFit(); 
    
                 getContent().toPage(pageMove);
                 
                 //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
                 
                 //Start FUnciton: No.4 - Editor : Long - Date : 08/12/2013 - Summary : Handle jump from bookmark page
                 if(pageMove > 0){    
                     //START TRB00056 - Editor: Long - Date: 09/19/2013 - Summary : 
                     prevContent.pageIndex = getPageIndex();
                     //END TRB00056 - Editor: Long - Date: 09/19/2013 - Summary : 
                     getPrevPageObjectsByPageIndex(pageObjectsData, pageMove - 1);
                     renderPrevPage();
                 }
                 
                 if(pageMove < totalPage - 1){
                     //START TRB00056
                     nextContent.pageIndex = getPageIndex();
                     //END TRB00056
                     getNextPageObjectsByPageIndex(pageObjectsData, pageMove + 1);
                     renderNextPage();
                 }
                 
                 //End Function : No.4 - Editor : Long - Date: 08/12/2013 - Summary : Handle jump form bookmark page            
                
                 /* handle slider bar */
                 handleSliderBar();
    
                 if (dataPageTitle[pageMove]) {
                     if (dataPageTitle[pageMove] != '') {
                         document.title = contentName + '_' + dataPageTitle[pageMove] + ' | ' + I18N.i18nText('sysAppTitle');
                     } else {
                         document.title = contentName + ' | ' + I18N.i18nText('sysAppTitle');
                     }
                 } else {
                     document.title = contentName + ' | ' + I18N.i18nText('sysAppTitle');
                 }
    
             },
             function (xmlHttpRequest, txtStatus, errorThrown) {
                 showErrorScreen();
             });
     }
    //START : TRB00032 - Editor : Long - Date: 09/10/2013 - Summary : type none process
    else if(contentType == COMMON.ContentTypeKeys.Type_NoFile){
        /* get page Objects */
         getPageObjectsByPageIndex(pageObjectsData, pageMove);
         getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);
    
         $('#divImageLoading').css('display', 'none');
    
         isFirstLoad = true;
         // screenFit(); 
    
         getContent().toPage(pageMove);
         //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
         
         //Start FUnciton: No.4 - Editor : Long - Date : 08/12/2013 - Summary : Handle jump from bookmark page
         if(pageMove > 0){    
             
             //START TRB00056 - Editor: Long - Date: 09/19/2013 - Summary : 
             prevContent.pageIndex = getPageIndex();
             //END TRB00056 - Editor: Long - Date: 09/19/2013 - Summary : 
             getPrevPageObjectsByPageIndex(pageObjectsData, pageMove - 1);
             renderPrevPage();
         }
         
         if(pageMove < totalPage - 1){
             
             //START TRB00056
             nextContent.pageIndex = getPageIndex();
             //END TRB00056
             
             getNextPageObjectsByPageIndex(pageObjectsData, pageMove + 1);
             renderNextPage();
         }
         
         //End Function : No.4 - Editor : Long - Date: 08/12/2013 - Summary : Handle jump form bookmark page            
        
         /* handle slider bar */
         handleSliderBar();
    
         if (dataPageTitle[pageMove]) {
             if (dataPageTitle[pageMove] != '') {
                 document.title = contentName + '_' + dataPageTitle[pageMove] + ' | ' + I18N.i18nText('sysAppTitle');
             } else {
                 document.title = contentName + ' | ' + I18N.i18nText('sysAppTitle');
             }
         } else {
             document.title = contentName + ' | ' + I18N.i18nText('sysAppTitle');
         }
    }
    //END : TRB00032 - Editor : Long - Date: 09/10/2013 - Summary : type none process
};

/* set position model when resize*/
function changePosDialog() {
    $("#divDialogMemo").center();
    /*$("#divDialogMemo").css('position', 'absolute');*/
    $("#boxBookMark").center();
    $("#boxIndex").center();
    $("#boxCopyText").center();
    $("#boxSearching").center();
    $("#boxAddMemo").center();
    $('#dlgPen').center();
    $('#dlgMaker').center();
    $('#dlgGomu').center();
    $('#dlgMarking').center();
    $('#bgmConfirm').center();
    $("#bgmConfirm_page").center();
};

function closeDialogResize() {
    closeDialogPopUpText();

    $('#pop_up_memo').hide();
};

//Start Function : No.12

var isZoomingContent = false;
//START TRB00075 - Editor: Long - Date - 24/09/2013 - Summary : Fix for prevent moving page when display dialog
function displayOverlayForHtmlAndMediaType(){
    var $overlay = $('#overlay');
    var $header = $('header');
    var $footer = $('footer');
    
    $header.css('position', 'absolute');
    $header.css('width', '100%');
    $header.css('z-index', '102');
    $footer.css('z-index', '102');
    $overlay.show();
    
    //START TRB00075 - Editor: Long - Date - 24/09/2013 - Summary : Fix for prevent moving page when display dialog
    document.getElementById('overlay').addEventListener('touchstart', function(event){event.preventDefault(); return false;}, false);
    document.getElementById('overlay').addEventListener('touchmove', function(event){event.preventDefault(); return false;}, false);
    document.getElementById('overlay').addEventListener('touchend', function(event){event.preventDefault(); return false;}, false); 
    //END TRB00075 - Editor: Long - Date - 24/09/2013 - Summary : Fix for prevent moving page when display dialog
    
};
//END TRB00075 - Editor: Long - Date - 24/09/2013 - Summary : Fix for prevent moving page when display dialog

//Display overlay dialog for specify content type
function displayOverlayForSpecifyContentType(){
    
    var contentId = ClientData.contentInfo_contentId();
    var resourceUrl = downloadResourceById(contentId);         
    
    //contentType = COMMON.ContentTypeKeys.Type_Html;
    if(contentType == COMMON.ContentTypeKeys.Type_Music){                  
        handleForContentTypeMusic(resourceUrl);
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Video){
        handleForContentTypeVideo(resourceUrl);
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Html){
    
        //DHカスタム
        var linkUrlTmp = resourceUrl;
        //DHカスタム
        if( ClientData.serviceOpt_daihatsu() == 'Y'){
            var apiUrl = AVWEB.getApiUrl(ClientData.userInfo_accountPath());
            linkUrlTmp = linkUrlTmp + "?sid=" + ClientData.userInfo_sid() + "&apiurl=" + apiUrl ;
        }
        handleForContentTypeHTML(linkUrlTmp);
    }
    
    if (COMMON.isTouchDevice() == true) {
        if (avwUserEnvObj.os == "android") {
            standardRatio = document.documentElement.clientWidth / window.innerWidth;
            ZOOM_DETECTOR.startDetectZoom({ time: 500,
                callbackFunction: function (oldRatio, newRatio, oldW, oldH, newW, newH) {
                    currentRatio = newRatio;

                }
            });
            var top = window.innerHeight - $("#footer_toolbar_1").height();
            $("#wrapper").css("width", window.innerWidth);
            $("#wrapper").css("height", window.innerHeight);
            $("#footer_toolbar_1").css("top", top + "px");
            $("#footer_toolbar_2").css("top", top + "px");
            sizingScreen();
        }
       
    }

    //Start : TRB00082 - Editor : Long - Date : 09/25/2013 - Summary : For win 8 rotate handling.
    setViewportForWin8();
    //End : TRB00082 - Editor : Long - Date : 09/25/2013 - Summary : For win 8 rotate handling.
    
    //Start : TRB00075 - Editor : Long - Date : 09/25/2013 - Summary : prevent moving page
    if (avwUserEnvObj.os == "ipad") {
        displayOverlayForHtmlAndMediaType();
        
    }
    //End : TRB00075 - Editor : Long - Date : 09/25/2013 - Summary : prevent moving page
    /* window resize event */
    $(window).resize(function () {
        
        //sizingScreen();    
        //START : TRB00034 - DATE : 09/11/2013 - Editor : Long  - Summary : Fix for center loading image           
        setLoadingSize();
        //END : TRB00034 - DATE : 09/11/2013 - Editor : Long  - Summary : Fix for center loading image
        if (COMMON.isTouchDevice() == true) {
            if (avwUserEnvObj.os == "android") {
                var tempRatio = document.documentElement.clientWidth / window.innerWidth;
                if (tempRatio <= 1) {
                    // Adjust position for toolbar and footer bar
                    var top = window.innerHeight - $("#footer_toolbar_1").height();
                    $("#wrapper").css("width", window.innerWidth);
                    $("#wrapper").css("height", window.innerHeight);
                    $("#footer_toolbar_1").css("top", top + "px");
                    $("#footer_toolbar_2").css("top", top + "px");
                }
                else {
                    var top = $(window).height() - $("#footer_toolbar_1").height();
                    $("#wrapper").css("width", $(window).width());
                    $("#wrapper").css("height", $(window).height());
                    $("#footer_toolbar_1").css("top", top + "px");
                    $("#footer_toolbar_2").css("top", top + "px");
                }
            }
        }
        sizingScreen();
        
        //Start : TRB00082 - Editor : Long - Date : 09/25/2013 - Summary : For win 8 rotate handling.
        setViewportForWin8();
        //End : TRB00082 - Editor : Long - Date : 09/25/2013 - Summary : For win 8 rotate handling.

        isChangeSizeScreen = false;

        /* change position dialog */
        changePosDialog();

        /* close dialog popuptext */
        closeDialogResize();
        
        //START TRB00091 - Editor : LOng - Date : 09/26/2013 - Summary : Dialog at center when rotate
        $("#contentVideoConfirm").center();
        $("#contentAudioConfirm").center();
        //END TRB00091 - Editor : LOng - Date : 09/26/2013 - Summary : Dialog at center when rotate                
        
    });     
};

//handle for content type = video
function handleForContentTypeVideo(resourceUrl){
    
    //Create Dialog overlay
    var $container = $('#dialog');
    
    $container.html('');      
        
    if (ClientData.userOpt_musicMode() == "1") {
            $container.html('<video id="content_video" autoplay="true" loop="true" controls="controls" style="position: absolute; width: 100%; height: 100%;">'
            + '     <source src="' + resourceUrl + '" type="video/mp4"> '
            + '</video>'
            );             
    } 
    else {      
        $container.html('<video id="content_video" autoplay="true" controls="controls" style="position: absolute; width: 100%; height: 100%;">'
        + '     <source src="' + resourceUrl + '" type="video/mp4"> '
        + '</video>'
        );
    }  
          
    //START TRB00068
    // Check to play Video on ipad
    if (avwUserEnvObj.os == "ipad") {       
        // Show confim message to play background music
        $("#contentVideoConfirm").css('z-index', 999);
        $("#contentVideoConfirm_OK").unbind('click');
        $("#contentVideoConfirm_OK").click(function () {
  
            var myVideo=document.getElementById("content_video"); 
            if (myVideo.paused)
            {
                myVideo.play();   
            }                                    
              
            $container.show();
            $("#contentVideoConfirm").hide();
            isShowVideoContent = true;                           
        });
        $("#contentVideoConfirm").show();
        $("#contentVideoConfirm").center();
    }
    else if (avwUserEnvObj.os == "android") { 
        // Show confim message to play background music
        $("#contentVideoConfirm").css('z-index', 999);
        $("#contentVideoConfirm_OK").unbind('click');
        $container.show();
        $("#contentVideoConfirm_OK").click(function () {
            
            var myVideo=document.getElementById("content_video"); 
            if (myVideo.paused)
            {
             myVideo.play();   
            }                                    
                         
            $("#contentVideoConfirm").hide();
            isShowVideoContent = true;                           
        });
        $("#contentVideoConfirm").show();
        $("#contentVideoConfirm").center();
    }
    else{
        $container.show();
    }   
    //END TRB00068           
};
var isShowVideoContent = false;

//handle for content type = music
function handleForContentTypeMusic(resourceUrl){
    
    //Create Dialog overlay
    var $container = $('#dialog');
    $container.html('');
    
    //START FIX CSS
    //$container.css('background', 'url(./img/iPad_music.png) center center no-repeat');
    //$container.css('background-color', 'white');
    $container.addClass('dialog-content-music');
    //END FIX CSS 
    
    if (ClientData.userOpt_musicMode() == "1") {       
        $container.html('<audio autoplay="true" loop="true" controls="controls" style="position: absolute; width: 100%; bottom: 1%;">'
        + '     <source src="' + resourceUrl + '" type="audio/mpeg"> '
        + '</audio>'
        );
    } 
    else {
        $container.html('<audio autoplay="true" controls="controls" style="position: absolute; width: 100%; bottom: 1%;">'
        + '     <source src="' + resourceUrl + '" type="audio/mpeg"> '
        + '</audio>'
        );
    }  
                                
    if(avwUserEnvObj.browser == 'firefox'){
        $container.find('audio').css('height', '30px');
    }
    
    $container.show();
    
    //START TRB00068
    // Check to play BGM on ipad
    if (avwUserEnvObj.os == "ipad") {
        // Show confim message to play background music
        $("#contentAudioConfirm").css('z-index', 999);
        $("#contentAudioConfirm_OK").unbind('click');
        $("#contentAudioConfirm_OK").click(function () {

            $("#contentAudioConfirm").hide();
            $("#dialog").find('audio').load();
            $("#dialog").find('audio').play();           
        });
        $("#contentAudioConfirm").show();
        $("#contentAudioConfirm").center();
    }
    //END TRB00068
};

//handle for content type = html
function handleForContentTypeHTML(resourceUrl){
     //Create Dialog overlay
    var $container = $('#dialog');
    
    $container.html('');
    $container.css('left','0%');
    $container.css('width','100%');
    $container.css('background-color','white');
    
    //START TRB00076 - EDITOR : Long - Date : 09/24/2013 - Summary : Fix for scrolling on ipad
    if(avwUserEnvObj.os == "ipad"){
       $container.html('<iframe src="'+ resourceUrl +'" style="position: absolute; width: 100%;"></iframe>'); 
        
       $container.css('overflow', 'scroll');
       $container.css('-webkit-overflow-scrolling', 'touch');
    }
    else{
        $container.html('<iframe src="'+ resourceUrl +'" style="position: absolute; width: 100%; height: 100%; "> </iframe>');
         $container.css('overflow', 'hidden');
    }
    //END TRB00076 - EDITOR : Long - Date : 09/24/2013 - Summary : Fix for scrolling on ipad
    $container.show(); 
};

//Check type of content
function isMediaAndHTMLContent(){
    if(contentType == COMMON.ContentTypeKeys.Type_Music || contentType == COMMON.ContentTypeKeys.Type_Video ||
    contentType == COMMON.ContentTypeKeys.Type_Html){
        return true; 
    }
    else{
        return false;
    }
};

//Enable Specify Control
function enableSpecifyControl(){
    
    //Disable All control
    disableAllControl();  
    
    if(contentType == COMMON.ContentTypeKeys.Type_Html || contentType == COMMON.ContentTypeKeys.Type_Music ||
    contentType == COMMON.ContentTypeKeys.Type_Video){
            
        enableControlForMediaAndHtmlType();
    }   
};

//Enable Control for video, audio, html type.
function enableControlForMediaAndHtmlType(){
    /* set cursor pointer*/
    $("#imgHome").css('cursor', 'pointer');
    $("#imgBack").css('cursor', 'pointer');
    
    $("#control_screen").removeClass();
    $("#control_screen_2").removeClass();
    
    $('#imgHome').bind('click', imgHome_click);
    $('#imgHome').removeClass();
    
    $('#imgBack').bind('click', imgBack_click);
    $('#imgBack').removeClass();
    
    $("#control_screen").bind('click', fullScreenForNotPdfType);
    $("#control_screen_2").bind('click', originalScreenForNotPdfType);
    
    if (COMMON.isTouchDevice() == true) {/* set css for device */
        $('#imgHome').addClass('home_device');
        $('#imgBack').addClass('back_device');
    
        $("#control_screen").addClass('toolbar_device');
        //$("#control_screen_2").addClass('toolbar_device'); 
        $("#control_screen_2").addClass('toolbar_close_device');
              
    } else { /* set css for PC */
        $('#imgHome').addClass('home');
        $('#imgBack').addClass('back');
        
        $("#control_screen").addClass('toolbar');
        $("#control_screen_2").addClass('toolbar_close');    
    }
    
    //getits対応
    if( ClientData.isGetitsMode() == true ){
        $('#imgHome').unbind('click');
        $('#imgHome').removeClass();
        $('#imgHome').addClass('home_off');

        /* back button */
        $('#imgBack').unbind('click');
        $('#imgBack').removeClass();
        $('#imgBack').addClass('back_off');
    }
    
};

//Enable control for type image and none
//function enableControlForImageAndNoneType(){
//    /* set cursor pointer*/
//    $("#imgHome").css('cursor', 'pointer');
//    $("#imgBack").css('cursor', 'pointer');
//    
//    $("#control_screen").removeClass();
//    $("#control_screen_2").removeClass();
//    
//    $('#imgHome').bind('click', imgHome_click);
//    $('#imgHome').removeClass();
//    
//    $('#imgBack').bind('click', imgBack_click);
//    $('#imgBack').removeClass();
//    
//    $("#control_screen").bind('click', fullScreenForNotPdfType);
//    $("#control_screen_2").bind('click', originalScreenForNotPdfType);
//    
//    if (COMMON.isTouchDevice() == true) {/* set css for device */
//        $('#imgHome').addClass('home_device');
//        $('#imgBack').addClass('back_device');
//    
//        $("#control_screen").addClass('toolbar_device');
//        //$("#control_screen_2").addClass('toolbar_device');   
//        $("#control_screen_2").addClass('toolbar_close_device');    
//         
//    } else { /* set css for PC */
//        $('#imgHome').addClass('home');
//        $('#imgBack').addClass('back');
//        
//        $("#control_screen").addClass('toolbar');
//        $("#control_screen_2").addClass('toolbar_close');    
//    }  
//};

//Full screen function for not pdf type
function fullScreenForNotPdfType(){
    
    if(contentType == COMMON.ContentTypeKeys.Type_Video){
        if(avwUserEnvObj.os == 'ipad'){
            $('#content_video').removeAttr('controls');
        }       
    }
           
    var $container = $('#dialog');
    
    $('#header_toolbar').hide();
    //START TRB00097
    //$('#footer_toolbar_2').show();
    //END TRB00097
    $('#control_screen_2').show();
    $('#footer_toolbar_2').css('z-index', '999');
    $('#control_screen_2').css('z-index', '999');
    $('#footer_toolbar_1').hide();
    
    $container.css('top', '0%')
              .css('left', '0%')
              .css('height', '100%')
              .css('width', '100%');
    //$container.attr('style', 'top: 0; left: 0; height: 100%; width: 100%;');
              
    isZoomingContent = true;
    isFullScreen = true;
};

//Original screen for not pdf type
function originalScreenForNotPdfType(){
    $('#footer_toolbar_2').css('z-index', '');
    $('#control_screen_2').css('z-index', '');
    $('#footer_toolbar_1').show();
    $('#footer_toolbar_2').hide();
    $('#control_screen_2').hide();
    $('#header_toolbar').show();
                  
    var $container = $('#dialog');
    $container.removeAttr('style');  
    
    if(contentType == COMMON.ContentTypeKeys.Type_Music){
        $container.css('background', 'url(./img/iPad_music.png) center no-repeat');
        $container.css('background-color', 'white');
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_Html){
        $container.css('left','0%');
        $container.css('position','absolute');
        //$container.css('height','100%');
        $container.css('width','100%');
        $container.css('background-color', 'white');
        $container.css('overflow', 'scroll');
        $container.css('-webkit-overflow-scrolling', 'touch');
    }
    
    //START TRB00068
    if (avwUserEnvObj.os == "ipad") {
        if(contentType == COMMON.ContentTypeKeys.Type_Video){
            $('#content_video').attr('controls', 'controls');
            
            if(isShowVideoContent){
                $container.show();
            }
            else{
                
            }
        }
        else{
            $container.show();  
        }       
    }
    else{
        $container.show(); 
    }
    //END TRB00068
 
    isZoomingContent = false;
    isFullScreen = false;
};

//Get resource Id of content
function downloadResourceById(contentId){
    var params = {
        sid: ClientData.userInfo_sid(),
        contentId: contentId,
        getType: '2',
    };
    
    var resourceUrl;
    abapi('webGetContent', params, 'GET', function (data) {
        var resourceId;      
        if(contentType == COMMON.ContentTypeKeys.Type_Html){
            resourceUrl = data.contentDataSub[0].resourceUrl;
        }
        else{
            $.each(data.contentData , function(i, n){
                if(typeof n == "object"){
                    resourceId = n.resourceId;                
                }                        
            });      
           //Get resource
           resourceUrl = getResourceByIdFromAPI(resourceId);
        }
                                          
    });   
    
    return resourceUrl;         
};

//Start : TRB00015 - Editor : Long - Date : 08/28/2013 - Summary : For win 8 rotate handling.
function setViewportForWin8(){
    if (window.navigator.msPointerEnabled) {                   
        //Landscape
        if($(window).width() > $(window).height()){
    
            var msViewportStyle = document.createElement("style");
            msViewportStyle.appendChild(
              document.createTextNode("@-ms-viewport{width: device-width;!important}")
            );
            document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
        }
        //Portrait
        else{
            var msViewportStyle = document.createElement("style");
            msViewportStyle.appendChild(
              document.createTextNode("@-ms-viewport{width: device-height;!important}")
            );
            document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
        }       
    }   
};
//End : TRB00015 - Editor : Long - Date : 08/28/2013 - Summary : For win 8 rotate handling.

//Start : TRB00022 - Editor : Long - Date : 08/28/2013 - Summary : For ipad rotate handling.  
function setViewportForTouchDevice(maximumScale){
    if (COMMON.isTouchDevice()) {
        if(avwUserEnvObj.os == 'ipad'){
            var viewportmeta = document.querySelector('meta[name="viewport"]');
            if (viewportmeta) {                          
                viewportmeta.content = 'minimum-scale=0.75, maximum-scale=' + maximumScale;
            }
        }       
    }
};
//End : TRB00022 - Editor : Long - Date : 08/28/2013 - Summary : For ipad rotate handling.  

$("document").ready(function () {     
          
    /* check login */
    if (!avwCheckLogin(COMMON.ScreenIds.Login)) return;
    // Set event to prevent leave
    COMMON.ToogleLogoutNortice();
    //START TRB00048 - EDITOR : Long - Date : 09/18/2013 - Summary : Fix Jumpcontent              
    getContentID();     
               
    avwCmsApi(ClientData.userInfo_accountPath(),
         "webGetContent",
         "GET",
         { contentId: contentID, sid: ClientData.userInfo_sid(), getType: 1 },
         function (data) {
             
            contentType = data.contentData.contentType;
            
            if (avwUserEnvObj.os == 'ipad') {
                //Start : TRB00022 - Editor : Long - Date : 08/28/2013 - Summary : For ipad rotate handling.  
                setViewportForTouchDevice();
                //End : TRB00022 - Editor : Long - Date : 08/28/2013 - Summary : For ipad rotate handling.  
                if (ClientData.IsRefresh() == true) {     
                                                      
                    //Check if is pdf content
                    if(isMediaAndHTMLContent()){
                        initPageMediaAndHtmlType();
                         
                        //START TRB00059 - EDITOR: Long - Date : 09/19/2013 - Summary : Add title for media and html type                
                        document.title = data.contentData.contentName + ' | ' + I18N.i18nText('sysAppTitle');   
                        //END TRB00059 - EDITOR: Long - Date : 09/19/2013 - Summary : Add title for media and html type    
                    }
                    else{
                        initPage();
                    }                     
                } else {
                    $('body, html').hide();
                    ClientData.IsRefresh(true);
                    location.reload();
                }
            }
            else {
                
                //Check if is pdf content
                if(isMediaAndHTMLContent()){
                    initPageMediaAndHtmlType();
                    
                    //START TRB00059 - EDITOR: Long - Date : 09/19/2013 - Summary : Add title for media and html type                
                    document.title = data.contentData.contentName + ' | ' + I18N.i18nText('sysAppTitle');    
                    //END TRB00059 - EDITOR: Long - Date : 09/19/2013 - Summary : Add title for media and html type  
                }
                else{
                    initPage();
                }     
            }                                                               
         },
         null);      
       //END TRB00048 - EDITOR : Long - Date : 09/18/2013 - Summary : Fix Jumpcontent
//End Function : No.12
});

/* ========================================================================================================== */

/**
* CurrentPage Class Definition 
*/
/* constructor */
var ContentPage = function (pageNum, pageImageUrl) {

    this.pageNumber = 0;
    this.pageImageUrl = pageImageUrl;
    this.bInitialized = false;

    /* init screen image */
    this.image = null;

    /* array page objects */
    this.pageObjects = new Array();
};

/* Load page */
ContentPage.prototype.load = function (onCompletedFunc) {

    /* load image  */
    this.image = new Image();
    this.image.onerror = function () {

    };
    this.image.onload = function (context) {
        /* load complete */
        if (onCompletedFunc) {
            onCompletedFunc();
        }
    };

    this.image.src = this.pageImageUrl;
};

/* add 1 page to pageObject */
ContentPage.prototype.addPageObject = function (pageObject) {
    this.pageObjects.push(pageObject);
};

/* init Json object using for init pages */
ContentPage.prototype.addPageObjects = function (pageObjects) {
    for (var i = 0; i < pageObjects.length; i++) {
        var obj = pageObjects[i];

        var pageObj = null;
        switch (obj.mediaType) {
            case 1:
                //mediaType = 1
                if (obj.actionType == 0) {
                    pageObj = new imageNoAction(     /* no action */
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.objectId
                                );
                } else if (obj.actionType == 1) {   /* play video */
                    pageObj = new videoType1(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.mediaFile,
                                    obj.media,
                                    obj.mediaResourceId,
                                    obj.objectId
                                );
                } else if (obj.actionType == 2) {
                    pageObj = new audioType1(    /* play audio */
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.audioFile,
                                    obj.audio,
                                    obj.audioResourceId,
                                    obj.objectId
                                );
                } else if (obj.actionType == 3) { /*open new url */
                    pageObj = new linkURL(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.action,
                                    obj.linkUrl,
                                    obj.browserType,
                                    obj.objectId
                                );
                } else if (obj.actionType == 4) { /*image preview */
                    pageObj = new imagePreview(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.imagePreview,
                                    obj.imagePreviewResourceIds,
                                    obj.objectId
                                );
                } else if (obj.actionType == 5) {  /*jump page */
                    pageObj = new jumpPage(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.jumpPage,
                                    obj.objectId
                                );
                } else if (obj.actionType == 6) { /*send mail */
                    pageObj = new sendMail(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.emailSubject,
                                    obj.emailAddress,
                                    obj.objectId
                                );
                } else if (obj.actionType == 8) { /* show popup */
                    pageObj = new openPopUp(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.content,
                                    obj.objectId
                                );
                } else if (obj.actionType == 10) { /* move to another content */
                    pageObj = new moveToContent(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.contentId,
                                    obj.pageNo,
                                    obj.objectId
                                );
                //Start Function : No.9 - Editor : Long - Summary : 
                }else if(obj.actionType == 11){
                    pageObj = new htmlLinkButton(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.resourceUrl,
                                    obj.objectId
                                );
                }else if(obj.actionType == 12){
                    
                    pageObj = new anket(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.questionNo, 
                                    obj.replyLimit, 
                                    obj.fullScreen, 
                                    obj.saveAs,
                                    obj.resourceId,
                                    obj.enquete,
                                    obj.objectId
                                );
                }
                //End Function : No.9 - Editor : Long - Summary : 
                break;
            case 2:
                pageObj = new videoType2(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.mediaFile,
                                    obj.media,
                                    obj.embed,
                                    obj.objectId
                                );
                break;
            case 3:
                pageObj = new audioType3(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.audioFile,
                                    obj.audioResourceId,
                                    obj.playType,
                                    obj.objectId
                                );
                break;
            case 4:
                // mediaType = 4
                objType4_5.push(obj);
                pageObj = new listImage(
                                    obj.mediaType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.dataObjects,
                                    obj.triggerType,
                                    obj.objectId
                                );
                break;
            case 5:
                // mediaType = 5    
                objType4_5.push(obj);
                pageObj = new listVideo(
                                    obj.mediaType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.dataObjects,
                                    obj.objectId
                                );
                break;
            case 6:
                // mediaType = 6
                pageObj = new trigger(
                                        obj.mediaType,
                                        obj.actionType,
                                        obj.id,
                                        obj.imageUrl,
                                        obj.x,
                                        obj.y,
                                        obj.width,
                                        obj.height,
                                        obj.index,
                                        obj.target,
                                        obj.visible,
                                        obj.action,
                                        obj.objectId
                                    );
                break;
            case 7:
                // mediaType = 7
                pageObj = new text(
                                        obj.mediaType,
                                        obj.actionType,
                                        obj.id,
                                        obj.x,
                                        obj.y,
                                        obj.width,
                                        obj.height,
                                        obj.visible,
                                        obj.action,
                                        obj.content,
                                        obj.objectId
                                    );
                break;
            //Start Function : No.9 - Editor : Long - Date : 08/15/2013 - Summary : 3d object
            case 8:
                //mediaType = 9              
                //obj["_3dLastId"] = convNumTo2Char(Math.round(obj.verticalCount/2)) +"-"+ convNumTo2Char(Math.round(obj.horizonCount/2));
                obj["_currFrameX"] = Math.round(obj.horizonCount/2);
                obj["_currFrameY"] = Math.round(obj.verticalCount/2);
                obj["_lastSelectedFrame"] = Object();
                obj["arrFrame"] = createMatrixPoints(obj.width, obj.height, obj.verticalCount,
                     obj.horizonCount, Math.round(obj.horizonCount/2), Math.round(obj.verticalCount/2));
                
                _object3DImageArr.push(obj);
                pageObj = new object3d(
                                        obj.mediaType,
                                        obj.actionType,
                                        obj.id,
                                        obj.initImage,
                                        obj.x,
                                        obj.y,
                                        obj.width,
                                        obj.height,
                                        obj.horizonCount,
                                        obj.verticalCount,
                                        obj.visible,
                                        obj['3dview'],
                                        obj.objectId
                                    );
                break;
            case 9:
                //mediaType = 9
                if(obj.actionType == 11){
                    pageObj = new htmlLinkButton(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.resourceUrl,
                                    obj.objectId
                                );  
                }
                break;
            case 11:
                //mediaType = 11
                if(obj.actionType == 12){
                
                    pageObj = new anket(
                                    obj.mediaType,
                                    obj.actionType,
                                    obj.id,
                                    obj.imageUrl,
                                    obj.x,
                                    obj.y,
                                    obj.width,
                                    obj.height,
                                    obj.visible,
                                    obj.questionNo, 
                                    obj.replyLimit, 
                                    obj.fullScreen, 
                                    obj.saveAs,
                                    obj.resourceId,
                                    obj.enquete,
                                    obj.objectId
                                );  
                }
                break;
            //Start Function : No.9 - Editor : Long - Date : 08/15/2013 - Summary : 3d object
            default:
                // default Object
                pageObj = new PageObject();
                pageObj.setup(
                            obj.mediaType,
                            obj.actionType,
                            obj.id,
                            obj.imageUrl,
                            obj.x,
                            obj.y,
                            obj.width,
                            obj.height,
                            obj.visible,
                            obj.action,
                            null,
                            obj.objectId
                        );
        }
        // add pageObject
        this.addPageObject(pageObj);
    }
};
//Start Function: No.4 - Editor : Long - Date : 08/09/2013 - Summary: Edit function to draw on multi canvas
/* drawing for current page */
ContentPage.prototype.drawPage = function (context, opt) {
    /*set status is loading page */
    isLoadingObject = true;
    /* lock all controls in page */
    disableAllControl();
    /* init array image */
    arrImage = [];
    nCountObjectLoad = 0;
    $('#divImageLoading').css('display', 'block');

    //var width = this.image.width;
    //var height = this.image.height;


    //START TRB00097 - Editor: Long - Date: 09/30/2013 - Summary : Get All Page size of content
    if(contentType == COMMON.ContentTypeKeys.Type_PDF){
        if(opt == null || opt == 0){
            getPageSizeByPageNo(changePageIndex(getPageIndex()));
            //#11478
            //widthEachPage = widthContentImage;
            //heightEachPage = heightContentImage;
            widthEachPageApi = widthContentImage;
            heightEachPageApi = heightContentImage;
        }
        else if(opt == 1){
            getPageSizeByPageNo(changePageIndex(getPageIndex() + 1));
            widthEachNextPage = widthContentImage;
            heightEachNextPage = heightContentImage;
            //#11478
            widthEachNextPageApi = widthContentImage;
            heightEachNextPageApi = heightContentImage; 
        }
        else if(opt == 2){
            getPageSizeByPageNo(changePageIndex(getPageIndex() - 1));
            widthEachPrevPage = widthContentImage;
            heightEachPrevPage = heightContentImage;
            //#11478
            widthEachPrevPageApi = widthContentImage;
            heightEachPrevPageApi = heightContentImage;
        }
    }
    else{
        widthEachPage = widthContentImage;
        heightEachPage = heightContentImage;
        //#11478
        widthEachPageApi = widthContentImage;
        heightEachPageApi = heightContentImage;
        widthEachNextPageApi = widthContentImage;
        heightEachNextPageApi = heightContentImage; 
        widthEachPrevPageApi = widthContentImage;
        heightEachPrevPageApi = heightContentImage;
    }

    /* set width canvas */
    /*
    if (width > height) {
        if (widthContentImage > heightContentImage) {
            widthEachPage = widthContentImage;
            heightEachPage = heightContentImage;
        } else {
            widthEachPage = heightContentImage;
            heightEachPage = widthContentImage;
        }
    } else {
        if (widthContentImage < heightContentImage) {
            widthEachPage = widthContentImage;
            heightEachPage = heightContentImage;
        } else {
            widthEachPage = heightContentImage;
            heightEachPage = widthContentImage;
        }
    }*/
    
    if(contentType == COMMON.ContentTypeKeys.Type_PDF){
        //#11478
        //if(opt == null || opt == 0){
        //    $("#offscreen").attr('height', heightEachPage);
        //    $("#offscreen").attr('width', widthEachPage);
        //}
        //else if(opt == 1){
        //    $("#offscreenNext").attr('height', heightEachNextPage);
        //    $("#offscreenNext").attr('width', widthEachNextPage);
        //}
        //else if(opt == 2){
        //    $("#offscreenPre").attr('height', heightEachPrevPage);
        //    $("#offscreenPre").attr('width', widthEachPrevPage);
        //}
    }
    else{
        if(opt == null || opt == 0){
            $("#offscreen").attr('height', heightEachPage);
            $("#offscreen").attr('width', widthEachPage);
        }
        else if(opt == 1){
            $("#offscreenNext").attr('height', heightEachPage);
            $("#offscreenNext").attr('width', widthEachPage);
        }
        else if(opt == 2){
            $("#offscreenPre").attr('height', heightEachPage);
            $("#offscreenPre").attr('width', widthEachPage);
        }
    }
    
    //END TRB00097 - Editor: Long - Date: 09/30/2013 - Summary : Get All Page size of content
    
    var objPageTemp = this.pageObjects;
    var img = new Image();
    img.onload = function () {
        //START TRB00097 - Editor: Long - Date: 09/30/2013 - Summary : Get All Page size of content
        if(contentType == COMMON.ContentTypeKeys.Type_PDF){
            if(opt == null || opt == 0){
                //#11478
                heightEachPage = img.naturalHeight;
                widthEachPage = img.naturalWidth;
                $("#offscreen").attr('height', heightEachPage);
                $("#offscreen").attr('width', widthEachPage);
                
                context.drawImage(img, 0, 0, widthEachPage, heightEachPage);
            }
            else if(opt == 1){
                //#11478
                heightEachNextPage = img.naturalHeight;
                widthEachNextPage = img.naturalWidth;
                $("#offscreenNext").attr('height', heightEachNextPage);
                $("#offscreenNext").attr('width', widthEachNextPage);
                
                context.drawImage(img, 0, 0, widthEachNextPage, heightEachNextPage);
            }
            else if(opt == 2){
                //#11478
                heightEachPrevPage = img.naturalHeight;
                widthEachPrevPage = img.naturalWidth;
                $("#offscreenPre").attr('height', heightEachPrevPage);
                $("#offscreenPre").attr('width', widthEachPrevPage);
                
                context.drawImage(img, 0, 0, widthEachPrevPage, heightEachPrevPage);
            } 
        }
        else{
            context.drawImage(img, 0, 0, widthEachPage, heightEachPage);
        }
        
        //END TRB00097 - Editor: Long - Date: 09/30/2013 - Summary : Get All Page size of content
        
        flip(opt);
        //Start Function: No.12        
        if(contentType == COMMON.ContentTypeKeys.Type_PDF){
            /* draw linkList */
            drawGetWebContent4(context, opt);
        }        
        //Start Function: No.12
       
        if (objPageTemp.length > 0) {
            // draw object
            for (var i = 0; i < objPageTemp.length; i++) {
                if (objPageTemp[i].imageUrl != null) {
                    objPageTemp[i].drawPageObject(context, opt);
                } 
                else {
                    nCountObjectLoad++;
                
                    if (nCountObjectLoad == objPageTemp.length) {
                        /* draw marking */
                        drawMarkingOnScreen(opt);

                        /*set status is loading page */
                       if(contentType == COMMON.ContentTypeKeys.Type_PDF || contentType == COMMON.ContentTypeKeys.Type_NoFile){
                            if(totalPage > 1){
                                if(opt != 0 && opt != null){
                                    isLoadingObject = false;
                                }
                            }
                            else{
                                isLoadingObject = false;
                            }                         
                       }
                       else{
                           isLoadingObject = false;
                       }
                                               
                        /* enable controls in page */
                        if (ClientData.IsAddingMarking() == true) {
                            disableAllControl();
                            enableButtonMarking();
                        } else {
                            //Start Function : No.4 - Summary : make sure next or prev page is loaded
                            if(contentType == COMMON.ContentTypeKeys.Type_PDF || contentType == COMMON.ContentTypeKeys.Type_NoFile){
                                if(totalPage > 1){
                                    if(opt != 0 && opt != null){
                                        enableAllControl();
                                    }
                                }
                                else{
                                    enableAllControl();
                                }                          
                            }
                            else{
                                enableAllControl();
                            }                                                    
                            //End Function : No.4 - Summary : make sure next or prev page is loaded                            
                        }
                        /*finish loading */
                       //Start Function : No.4 - Summary : make sure next or prev page is loaded
                        if(contentType == COMMON.ContentTypeKeys.Type_PDF || contentType == COMMON.ContentTypeKeys.Type_NoFile){
                            if(totalPage > 1){
                                if(opt != 0 && opt != null){
                                   $('#divImageLoading').css('display', 'none');
                                }   
                            }
                            else{
                                $('#divImageLoading').css('display', 'none');
                            }                      
                        }
                        else{
                            $('#divImageLoading').css('display', 'none');
                        }
                        //End Function : No.4 - Summary : make sure next or prev page is loaded                          
                        /* set pos video */
                        zoomVideo();
                    }

                }
            }
        } 
        else {
            /* draw marking */
            drawMarkingOnScreen(opt);

            /*set status is loading page */
            if(contentType == COMMON.ContentTypeKeys.Type_PDF || contentType == COMMON.ContentTypeKeys.Type_NoFile){
                if(totalPage > 1){
                   if(opt != 0 && opt != null){
                        isLoadingObject = false;
                   }      
                }
                else{
                    isLoadingObject = false;
                }                      
            }
            else{
                 isLoadingObject = false;
            }
            /* enable controls in page */
            if (ClientData.IsAddingMarking() == true) {
                disableAllControl();
                enableButtonMarking()
            } 
            else {
                //Start Function : No.4 - Summary : make sure next or prev page is loaded 
                if(contentType == COMMON.ContentTypeKeys.Type_PDF || contentType == COMMON.ContentTypeKeys.Type_NoFile){
                    if(totalPage > 1){
                        if(opt != 0 && opt != null){
                            enableAllControl();
                        }
                    }
                    else{
                        enableAllControl();
                    }                         
                }
                else{
                     enableAllControl();
                }
                //End Function : No.4 - Summary : make sure next or prev page is loaded
            }

            /*finish loading */
            //Start Function : No.4 - Summary : make sure next or prev page is loaded

            if(contentType == COMMON.ContentTypeKeys.Type_PDF || contentType == COMMON.ContentTypeKeys.Type_NoFile){
                if(totalPage > 1){
                    if(opt != 0 && opt != null){
                        $('#divImageLoading').css('display', 'none');
                    }   
                }
                else{
                    $('#divImageLoading').css('display', 'none');
                }                    
            }
            else{
                 $('#divImageLoading').css('display', 'none');
            }
            //End Function : No.4 - Summary : make sure next or prev page is loaded   

            /* set pos video */
            zoomVideo();
        }
               
    };
    img.src = this.image.src;
};
//End Function: No.4 - Editor : Long - Date : 08/09/2013 - Summary: Edit function to draw on multi canvas


/* If have hitTest on the objects within the page and return PageObject */
ContentPage.prototype.hitTest = function (px, py) {
    for (var i = 0; i < this.pageObjects.length; i++) {
        if (this.pageObjects[i].hitTest(px, py)) {
            return this.pageObjects[i];
        }
    }
    return null;
};

/* search by Object ID */
ContentPage.prototype.findById = function (id) {
    for (var i = 0; i < this.pageObjects.length; i++) {
        if (this.pageObjects[i].id == id) {
            return this.pageObjects[i];
        }
    }
    return null;
};


/* check status button move page when change page */
function checkExistNextPrePage() {
    //check next page
    
    if (getContent().hasNextPage()) {
        //$('#nextpage').show();
        //COMMON.enable('#nextpage');
        $('#nextpage').unbind('click');
        $('#nextpage').bind('click', nextPage_click);

        $('#lastpage').unbind('click');
        $('#lastpage').bind('click', lastPage_click);

        if (COMMON.isTouchDevice() == true) {
            $('#nextpage').removeClass();
            $('#nextpage').addClass('next_device');

            $('#lastpage').removeClass();
            $('#lastpage').addClass('last_device');
        } else {
            $('#nextpage').removeClass();
            $('#nextpage').addClass('next');

            $('#lastpage').removeClass();
            $('#lastpage').addClass('last');
        }
    } else {
        //$('#nextpage').hide();
        //COMMON.disable('#nextpage');
        $('#nextpage').unbind('click');
        $('#lastpage').unbind('click');

        if (COMMON.isTouchDevice() == true) {
            $('#nextpage').removeClass();
            $('#nextpage').addClass('next_off');

            $('#lastpage').removeClass();
            $('#lastpage').addClass('last_off');
        } else {
            $('#nextpage').removeClass();
            $('#nextpage').addClass('next_off');

            $('#lastpage').removeClass();
            $('#lastpage').addClass('last_off');
        }
        $('#button_next_canvas').css('opacity', '0');
    }

    //check prev page
    if (getContent().hasPreviousPage()) {
        //$('#prevpage').show();
        //COMMON.enable('#prevpage');
        $('#prevpage').unbind('click');
        $('#prevpage').bind('click', prevPage_click);

        $('#firstpage').unbind('click');
        $('#firstpage').bind('click', firstPage_click);

        if (COMMON.isTouchDevice() == true) {
            $('#prevpage').removeClass();
            $('#prevpage').addClass('prev_device');

            $('#firstpage').removeClass();
            $('#firstpage').addClass('begin_device');
        } else {
            $('#prevpage').removeClass();
            $('#prevpage').addClass('prev');

            $('#firstpage').removeClass();
            $('#firstpage').addClass('begin');
        }
    } else {
        //$('#prevpage').hide();
        //COMMON.disable('#prevpage');
        $('#prevpage').unbind('click');
        $('#firstpage').unbind('click');

        if (COMMON.isTouchDevice() == true) {
            $('#prevpage').removeClass();
            $('#prevpage').addClass('prev_off');

            $('#firstpage').removeClass();
            $('#firstpage').addClass('begin_off');
        } else {
            $('#prevpage').removeClass();
            $('#prevpage').addClass('prev_off');

            $('#firstpage').removeClass();
            $('#firstpage').addClass('begin_off');
        }
        $('#button_pre_canvas').css('opacity', '0');

    }

};

/* init variable */
var content = new Content();
var srcRect = new Rect(0, 0, 0, 0);
var destRect = new Rect(0, 0, 0, 0);
//START TRB00097
var srcRectNext = new Rect(0, 0, 0, 0);
var srcRectPrev = new Rect(0, 0, 0, 0);
var destRectNext = new Rect(0, 0, 0, 0);
var destRectPrev = new Rect(0, 0, 0, 0);
var moveXNext = 0, moveYNext = 0;
var moveXPrev = 0, moveYPrev = 0;
//END TRB00097
var isDestPositionDetect = false;
var destPosX = 0, destPosY = 0;
var moveX = 0, moveY = 0;
var userScale = 1;
var userScaleNow = 1;
var scaleDelta = 0.5;
var scaleX, scaleY;
var canvasObject;
var contextObject;
var objType4_5 = [];
/*var objType5;
var isObjType4 = false;
var isObjType5 = false;*/
/* variable for event mouse */

var moveFlag = false;
var cancelClick = false;
var timeCreateMemo;

var imageData;
var isLoadBackgroundComplete = false;


/* Point objects */
var Point = function (x, y) {
    this.x = x;
    this.y = y;
};

/**
* constants 
*/
var marginX = 13;
var marginY = 65;

/* remove all object when change page */
function removeObject() {
    $('#text').children().remove();

    /* close dialog */
    if (isOpenPopUpText == true) {
        isOpenPopUpText = false;
        ClosePopupText();
    }

    $("#bgmConfirm").hide();
    $("#boxCopyText").hide();
    $("#boxSearching").hide();
    $("#boxIndex").hide();
    $("#boxBookMark").hide();
    $('#pop_up_memo').hide();
    isSendingData = false;


    isDisplayBookMarkList = false;
    isDisplayCopyText = false;
    isDisplayListIndex = false;

    if ($('#playvideo').children().length > 0) {
        $('#playvideo').children().remove();
    }

    if ($('#playaudio').children().length > 0) {
        $('#playaudio').children().remove();
    }
    if ($('#playaudiopage').children().length > 0) {
        if (avwUserEnvObj.os != "ipad") {
            $('#playaudiopage').children().remove();
        }
    }

    if (avwUserEnvObj.browser == 'firefox') {
        srcAudioType0 = '';
        TypeAudio0 = '';
        srcAudioType2 = '';
        TypeAudio2 = '';
    } else {
        /* do nothing */
    }


    //Start Function : No.12 - Editor :Long - Date: 08/12/2013 - Summary : prevent close dialog if content is not pdf
    if(contentType == COMMON.ContentTypeKeys.Type_PDF || contentType == COMMON.ContentTypeKeys.Type_NoFile){
        hideDialog();    
    }
    //End Function : No.12 - Editor :Long - Date: 08/12/2013 - Summary : prevent close dialog if content is not pdf

    /* play background audio */
    playAllAudio();

    /* mediaType = 4 */
    mediaType4_changeImage = 0;
};

/* View Component setDefaultEvent */
function setDefaultEvent() {
    
    _bTouchDeviceEnabled = COMMON.isTouchDevice();
    
    var canvasPre = document.getElementById('mainPre');
    var canvasNext = document.getElementById('mainNext');
    //mouse event
    // add event for wrap

    //remove wrapper event
    canvasPre.removeEventListener('mousedown',function(){},false);
    canvasPre.removeEventListener('mousemove',function(){},false);
    canvasPre.removeEventListener('mouseup',function(){},false);
    canvasPre.removeEventListener('mouseout',function(){},false);

    canvasNext.removeEventListener('mousedown',function(){},false);
    canvasNext.removeEventListener('mousemove',function(){},false);
    canvasNext.removeEventListener('mouseup',function(){},false);
    canvasNext.removeEventListener('mouseout',function(){},false);
    
    document.getElementById('main').addEventListener('click', onClick_CanvasMain, false);
    document.getElementById('divCheckExistMarking').addEventListener('click', onClick_CanvasMain, false);
       
    if(avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android"){
    
        document.getElementById('main').addEventListener('mousedown', mouseDown_CanvasMain, false);
        document.getElementById('main').addEventListener('mousemove', mouseMove_CanvasMain, false);
        document.getElementById('main').addEventListener('mouseup', mouseUp_CanvasMain, false); 
        
        //#12408 ホイール対応
        // MouseScrollEvent に対応している（FireFox 専用）
        if(window.MouseScrollEvent){
//console.log("addEventListener DOMMouseScroll"); 
            document.getElementById('main').addEventListener('DOMMouseScroll', function(event){ 
                mouseWheel_CanvasMain(event, event.detail);
            }, false);
        // FireFox 以外の主要ブラウザの場合
        }else{
//console.log("addEventListener mousewheel"); 
            var mousewheelevent = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';            
            document.getElementById('main').addEventListener(mousewheelevent, function(e){
                mouseWheel_CanvasMain(event, -(e.wheelDelta / 40));
            }, false);
        }
        
        if (avwUserEnvObj.browser == 'msie') {
            _bWin8TouchEnabled = window.navigator.msPointerEnabled;
        } else {
            if( _bTouchDeviceEnabled ){
                document.getElementById('main').addEventListener('touchstart', onTouchstart, false);
                document.getElementById('main').addEventListener('touchmove', onTouchmove, false);
                document.getElementById('main').addEventListener('touchend', onTouchend, false);
                //iPad&Andの実装から
                document.getElementById('canvasWrapper').addEventListener('touchstart', function(event){event.preventDefault();}, false);
                document.getElementById('canvasWrapper').addEventListener('touchmove', function(event){event.preventDefault();}, false);
                document.getElementById('canvasWrapper').addEventListener('touchend', function(event){event.preventDefault();}, false); 
                document.getElementById('overlay').addEventListener('touchstart', function(event){event.preventDefault(); return false;}, false);
                document.getElementById('overlay').addEventListener('touchmove', function(event){event.preventDefault(); return false;}, false);
                document.getElementById('overlay').addEventListener('touchend', function(event){event.preventDefault(); return false;}, false); 
                //デフォルトのD&Dが効いてしまう問題回避
                document.getElementById('button_next_canvas').addEventListener('touchstart', function(event){event.preventDefault();}, false);
                document.getElementById('button_next_canvas').addEventListener('touchmove', function(event){event.preventDefault();}, false);
                document.getElementById('button_next_canvas').addEventListener('touchend', function(event){event.preventDefault();}, false); 
                document.getElementById('button_pre_canvas').addEventListener('touchstart', function(event){event.preventDefault();}, false);
                document.getElementById('button_pre_canvas').addEventListener('touchmove', function(event){event.preventDefault();}, false);
                document.getElementById('button_pre_canvas').addEventListener('touchend', function(event){event.preventDefault();}, false); 
                
            }
        }
        
        if(_bWin8TouchEnabled){
            document.getElementById('main').addEventListener('MSPointerDown', onTouchstart, false);
            document.getElementById('main').addEventListener('MSPointerMove', onTouchmove, false);
            document.getElementById('main').addEventListener('MSPointerUp', onTouchend, false);
        }
    }
    else if(avwUserEnvObj.os == "ipad" || avwUserEnvObj.os == "android"){
        document.getElementById('main').removeEventListener('click', function(){}, false);
        document.getElementById('main').addEventListener('touchstart', onTouchstart, false);
        document.getElementById('main').addEventListener('touchmove', onTouchmove, false);
        document.getElementById('main').addEventListener('touchend', onTouchend, false);
        
        
        //Start : TRB00016 - Editor : Long - Date : 29/08/2013 - Summary : Fix for ipad move all page when move page
        document.getElementById('canvasWrapper').addEventListener('touchstart', function(event){event.preventDefault();}, false);
        document.getElementById('canvasWrapper').addEventListener('touchmove', function(event){event.preventDefault();}, false);
        document.getElementById('canvasWrapper').addEventListener('touchend', function(event){event.preventDefault();}, false); 
        //End : TRB00016 - Editor : Long - Date : 29/08/2013 - Summary : Fix for ipad move all page when move pages
        
        //document.getElementById('wrapper').addEventListener('touchstart', function(event){event.preventDefault();}, false);
        //document.getElementById('wrapper').addEventListener('touchmove', function(event){event.preventDefault();}, false);
        //document.getElementById('wrapper').addEventListener('touchend', function(event){event.preventDefault();}, false);   
        
        //START TRB00075 - Editor: Long - Date - 24/09/2013 - Summary : Fix for prevent moving page when display dialog
        document.getElementById('overlay').addEventListener('touchstart', function(event){event.preventDefault(); return false;}, false);
        document.getElementById('overlay').addEventListener('touchmove', function(event){event.preventDefault(); return false;}, false);
        document.getElementById('overlay').addEventListener('touchend', function(event){event.preventDefault(); return false;}, false); 
        //END TRB00075 - Editor: Long - Date - 24/09/2013 - Summary : Fix for prevent moving page when display dialog
    }
                       
    $('#main').mouseout(function (event) {
        if (moveFlag) {
            moveFlag = false;
        }

        $('#button_pre_canvas').css('opacity', '0');
        $('#button_next_canvas').css('opacity', '0');
    });
};

/*disable all control when click copy memo */
function disableControlsCopyMemo() {
    /* set cursor pointer*/
    $("#imgHome").css('cursor', 'default');
    $("#imgBack").css('cursor', 'default');
    $("#listbookmark").css('cursor', 'default');
    $("#imgbookmark").css('cursor', 'default');
    $("#listindex").css('cursor', 'default');
    $("#copytext").css('cursor', 'default');
    $("#imgmemo").css('cursor', 'default');
    $("#imgaddmemo").css('cursor', 'default');
    $("#imgmarking").css('cursor', 'default');
    $("#imgmarkingtoolbar").css('cursor', 'default');
    $("#firstpage").css('cursor', 'default');
    $("#prevpage").css('cursor', 'default');
    $("#nextpage").css('cursor', 'default');
    $("#lastpage").css('cursor', 'default');

    $('#imgHome').unbind('click');
    $('#imgHome').removeClass();
    $('#imgHome').addClass('home_off');

    /* back button */
    $('#imgBack').unbind('click');
    $('#imgBack').removeClass();
    $('#imgBack').addClass('back_off');

    /*list bookmark */
    $('#listbookmark').unbind('click');
    $('#listbookmark').removeClass();
    $('#listbookmark').addClass('bmList_off');

    $('#imgbookmark').unbind('click');
    $('#imgbookmark').removeClass();
    $('#imgbookmark').addClass('bmAdd_off');

    $('#listindex').unbind('click');
    $('#listindex').removeClass();
    $('#listindex').addClass('index_off');

    $('#copytext').unbind('click');
    $('#copytext').removeClass();
    $('#copytext').addClass('copy_off');

    /* imgage display memo */
    $('#imgmemo').unbind('click');
    $('#imgmemo').removeClass();
    $('#imgmemo').addClass('memoDisplay_off');

    /* image add memo */
    $('#imgaddmemo').unbind('click');
    $('#imgaddmemo').removeClass();
    $('#imgaddmemo').addClass('memoAdd_off');

    $('#imgmarking').unbind('click');
    $('#imgmarking').removeClass();
    $('#imgmarking').addClass('marking_off');

    /* check is loading page */
    $('#imgmarkingtoolbar').unbind('click');
    $('#imgmarkingtoolbar').removeClass();
    $('#imgmarkingtoolbar').addClass('markingToolbar_off');

    $('#firstpage').unbind('click');
    $('#firstpage').removeClass();
    $('#firstpage').addClass('begin_off');
    $('#prevpage').unbind('click');
    $('#prevpage').removeClass();
    $('#prevpage').addClass('prev_off');
    $('#nextpage').unbind('click');
    $('#nextpage').removeClass();
    $('#nextpage').addClass('next_off');
    $('#lastpage').unbind('click');
    $('#lastpage').removeClass();
    $('#lastpage').addClass('last_off');

    if (avwUserEnvObj.os != "android") {
        $("#slider_page").slider("option", "disabled", true);
    }
    COMMON.disable('#txtSearch', '#txtSlider');

    $('#button_next_canvas').css('display', 'none');
    $('#button_pre_canvas').css('display', 'none');
};

/*enable all control when finish copy memo */
function enableControlsCopyMemo() {
    disableControlsCopyMemo();

    /* set cursor pointer*/
    $("#imgHome").css('cursor', 'pointer');
    $("#imgBack").css('cursor', 'pointer');
    $("#listbookmark").css('cursor', 'pointer');
    $("#imgbookmark").css('cursor', 'pointer');
    $("#listindex").css('cursor', 'pointer');
    $("#copytext").css('cursor', 'pointer');
    $("#imgmemo").css('cursor', 'pointer');
    $("#imgaddmemo").css('cursor', 'pointer');
    $("#imgmarking").css('cursor', 'pointer');
    $("#imgmarkingtoolbar").css('cursor', 'pointer');
    $("#firstpage").css('cursor', 'pointer');
    $("#prevpage").css('cursor', 'pointer');
    $("#nextpage").css('cursor', 'pointer');
    $("#lastpage").css('cursor', 'pointer');

    $("#control_screen").removeClass();
    $("#control_screen_2").removeClass();

    $('#imgHome').bind('click', imgHome_click);
    $('#imgHome').removeClass();

    $('#imgBack').bind('click', imgBack_click);
    $('#imgBack').removeClass();

    /*list bookmark */
    $('#listbookmark').bind('click', showListBookMark);
    $('#listbookmark').removeClass();

    $('#imgbookmark').bind('click', bookmarkPage);
    $('#imgbookmark').removeClass();

    //Start Function : No.12 - Editor : Long - Date : 08/28/2013 - Summary : 
    if(contentType == COMMON.ContentTypeKeys.Type_PDF){
        $('#listindex').bind('click', showListPageIndex);
        $('#listindex').removeClass();
    
        $('#copytext').bind('click', showCopyText);
        $('#copytext').removeClass();   
    }
    //Start Function : No.12 - Editor : Long - Date : 08/28/2013 - Summary : 
 
    /* image memo */
    $('#imgmemo').bind('click', handleMemo);
    $('#imgmemo').removeClass();

    /* image add memo */
    $('#imgaddmemo').bind('click', handleAddMemo);
    $('#imgaddmemo').removeClass();

    $('#imgmarking').bind('click', imgmarking_click);
    $('#imgmarking').removeClass();

    if (ClientData.serviceOpt_marking() == 'Y') {
        $('#imgmarkingtoolbar').bind('click', handleDrawCanvas);
        $('#imgmarkingtoolbar').removeClass();
    }
    
    if(contentType == COMMON.ContentTypeKeys.Type_PDF){
        $("#slider_page").slider("option", "disabled", false);
        COMMON.enable('#txtSearch', '#txtSlider');
    }
    else if(contentType == COMMON.ContentTypeKeys.Type_NoFile){
        $("#slider_page").slider("option", "disabled", false);
        COMMON.enable('#txtSlider');
    }


    if (avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android") {
        $('#button_next_canvas').css('display', 'block');
        $('#button_pre_canvas').css('display', 'block');
    }

    if (COMMON.isTouchDevice() == true) {/* set css for device */
        $('#imgHome').addClass('home_device');
        $('#imgBack').addClass('back_device');
        /*$('#firstpage').addClass('begin_device');
        $('#prevpage').addClass('prev_device');
        $('#nextpage').addClass('next_device');
        $('#lastpage').addClass('last_device');*/
        $("#control_screen").addClass('toolbar_device');
        //$("#control_screen_2").addClass('toolbar_device');
        $("#control_screen_2").addClass('toolbar_close_device');
        
        var nBookmarkId = isExistBookmark();
        if (nBookmarkId == -1) {
            $('#imgbookmark').addClass('bmAdd_device');
        } else {
            $('#imgbookmark').addClass('bmAdd_hover');
        }

        if (isDisplayBookMarkList == true) {
            $('#listbookmark').addClass('bmList_hover');
        } else {
            $('#listbookmark').addClass('bmList_device');
        }

        if (isDisplayCopyText == true) {
            $('#copytext').addClass('copy_hover');
        } else {
            $('#copytext').addClass('copy_device');
        }

        if (isDisplayListIndex == true) {
            $('#listindex').addClass('index_hover');
        } else {
            $('#listindex').addClass('index_device');
        }

        if (ClientData.IsDisplayMemo() == true) {
            $('#imgmemo').addClass('memoDisplay_hover');
        } else {
            $('#imgmemo').addClass('memoDisplay_device');
        }

        if (ClientData.IsAddingMemo() == true) {
            $('#imgaddmemo').addClass('memoAdd_hover');
        } else {
            $('#imgaddmemo').addClass('memoAdd_device');
        }

        if (ClientData.IsDisplayMarking() == true) {
            $('#imgmarking').addClass('marking_hover');
        } else {
            $('#imgmarking').addClass('marking_device');
        }
        if (ClientData.serviceOpt_marking() == 'Y') {
            if (ClientData.IsAddingMarking() == true) {
                $('#imgmarkingtoolbar').addClass('markingToolbar_hover');
            } else {
                $('#imgmarkingtoolbar').addClass('markingToolbar_device');
            }
        }
    } else { /* set css for PC */
        $('#imgHome').addClass('home');
        $('#imgBack').addClass('back');
        /*$('#firstpage').addClass('begin');
        $('#prevpage').addClass('prev');
        $('#nextpage').addClass('next');
        $('#lastpage').addClass('last');*/
        $("#control_screen").addClass('toolbar');
        $("#control_screen_2").addClass('toolbar_close');

        var nBookmarkId = isExistBookmark();
        if (nBookmarkId == -1) {
            $('#imgbookmark').addClass('bmAdd');
        } else {
            $('#imgbookmark').addClass('bmAdd_hover');
        }

        if (isDisplayBookMarkList == true) {
            $('#listbookmark').addClass('bmList_hover');
        } else {
            $('#listbookmark').addClass('bmList');
        }

        if (isDisplayCopyText == true) {
            $('#copytext').addClass('copy_hover');
        } else {
            $('#copytext').addClass('copy');
        }

        if (isDisplayListIndex == true) {
            $('#listindex').addClass('index_hover');
        } else {
            $('#listindex').addClass('index');
        }

        if (ClientData.IsDisplayMemo() == true) {
            $('#imgmemo').addClass('memoDisplay_hover');
        } else {
            $('#imgmemo').addClass('memoDisplay');
        }

        if (ClientData.IsAddingMemo() == true) {
            $('#imgaddmemo').addClass('memoAdd_hover');
        } else {
            $('#imgaddmemo').addClass('memoAdd');
        }

        if (ClientData.IsDisplayMarking() == true) {
            $('#imgmarking').addClass('marking_hover');
        } else {
            $('#imgmarking').addClass('marking');
        }
        if (ClientData.serviceOpt_marking() == 'Y') {
            if (ClientData.IsAddingMarking() == true) {
                $('#imgmarkingtoolbar').addClass('markingToolbar_hover');
            } else {
                $('#imgmarkingtoolbar').addClass('markingToolbar');
            }
        }
    }
    checkExistNextPrePage();
};

/* Change Coordinate Screen to Image */
function screenToImage(x, y) {

    var pt = new Point(0, 0);

    // get current position of mouse on screen  
    if (isFullScreen == true) {
        pt.x = x - marginX;
        pt.y = y;
    } else {
        pt.x = x - marginX;
        pt.y = y - marginY;
    }

    var sx = (destRect.right - destRect.left) / (srcRect.right - srcRect.left);
    var sy = (destRect.bottom - destRect.top) / (srcRect.bottom - srcRect.top);

    // change size image correct
    var nx = (pt.x - destRect.left) / sx;
    var ny = (pt.y - destRect.top) / sy;
    pt.x = Math.floor(nx + srcRect.left);
    pt.y = Math.floor(ny + srcRect.top);

    //console.log('screenToImage ' + srcRect.right + ' ' + srcRect.left + ' ' + destRect.right + ' ' + destRect.left + ' ' + x + ' ' + sx + ' ' + nx + ' ' + pt.x + ' ' + srcRect.bottom + ' ' + srcRect.top + ' ' + destRect.bottom + ' ' + destRect.top + ' ' + y + ' ' + sy + ' ' + ny + ' ' + pt.y);

    return pt;
};

//Start Function : No.4 - Editor : Long - Date: 08/09/2013  - Summary : Edit function adjust page to draw multi canvas
/* Adjust page size */
function adjustPage(opt) {
    
    drawCanvas(opt);
};
/* draw Canvas  */
function drawCanvas(opt) {
    
    //Draw on offscreen
    if(opt==null || opt == 0){
        // draw main canvas
        var canvas = document.getElementById('offscreen');
        var context = canvas.getContext('2d');
              
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        draw(context, 0);
    } 
    //Draw on next offscreen
    else if (opt==1){
        // draw mainNext canvas
        var canvas = document.getElementById('offscreenNext');
        var context = canvas.getContext('2d');
               
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        draw(context, 1);
    }
    //Draw on previous offscreen
    else if (opt==2){
        // draw mainPre canvas
        var canvas = document.getElementById('offscreenPre');
        var context = canvas.getContext('2d');
        
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        draw(context, 2);        
    }
};
//End Function : No.4 - Editor : Long - Date: 08/09/2013 - Summary : Edit function adjust page to draw multi canvas

/* draw memo */
function drawMemoOnScreen(opt) {
    
    //Start Function : No.4
    var canvas;
    var context;
    //START TRB00097
    var tempPageHeight;
    var tempPageWidth;
    //END TRB00097
    var tempPageNo = 0;
    
    if(opt == null || opt == 0){
        canvas = document.getElementById('offscreen');
        canvasWidth = $('#offscreen').width();
        canvasHeight = $('#offscreen').height();    
        
        //START TRB00097           
        tempPageHeight = heightEachPage;
        tempPageWidth = widthEachPage;
        //END TRB00097
        tempPageNo = changePageIndex(getPageIndex());
    }
    else if(opt == 1){
        canvas = document.getElementById('offscreenNext');
        canvasWidth = $('#offscreenNext').width();
        canvasHeight = $('#offscreenNext').height();
        
        //START TRB00097           
        tempPageHeight = heightEachNextPage;
        tempPageWidth = widthEachNextPage;
        //END TRB00097
        tempPageNo = changePageIndex(getPageIndex() + 1);
    }
    else if(opt == 2){
        canvas = document.getElementById('offscreenPre');
        canvasWidth = $('#offscreenPre').width();
        canvasHeight = $('#offscreenPre').height();
        //START TRB00097           
        tempPageHeight = heightEachPrevPage;
        tempPageWidth = widthEachPrevPage;
        //END TRB00097
        tempPageNo = changePageIndex(getPageIndex() - 1);
    }
    
    context = canvas.getContext('2d');
    //End Function : No.4

    if (ClientData.IsDisplayMemo() == true) {
        memoObjects = [];

        /*get data memo */
        var memoData = ClientData.MemoData();
        
        //Start Function : No.17 - Editor : Long - Date: 08/13/2013 - Summary : Draw newest memo
        var tempPosX = 0;
        var tempPosY = 0;
        //End Function : No.17 - Editor : Long - Date: 08/13/2013 - Summary : Draw newest memo
        
        for (var nIndex = 0; nIndex < memoData.length; nIndex++) {
            if (memoData[nIndex].contentid == contentID
            && memoData[nIndex].pageNo == tempPageNo) {
                /* create object of memo */
                var memoObject = null;
                 //START TRB00097 
                if (memoData[nIndex].posY > tempPageHeight - 50) {
                    memoData[nIndex].posY = tempPageHeight - 50;
                }

                if (memoData[nIndex].posX > tempPageWidth - 50) {
                    memoData[nIndex].posX = tempPageWidth - 50;
                }
                 //END TRB00097 
                 
                //Start Function : No.17 - Editor : Long - Date: 08/13/2013 - Summary : Draw newest memo
                if(memoData[nIndex].posY != tempPosY && memoData[nIndex].posX != tempPosX){
                    tempPosX = memoData[nIndex].posX;
                    tempPosY = memoData[nIndex].posY;
                    
                    memoObject = new memo(
                        nIndex,
                        memoData[nIndex].Text,
                        memoData[nIndex].posX,
                        memoData[nIndex].posY,
                        50,
                        50,
                        "img/memo.png"
                    );
                    
                     memoObjects.push(memoObject);
                     
                }else{
                    for (var i = memoObjects.length - 1; i >= 0; i--) {
                        var tempObj = memoObjects[i];
                        
                        if(tempObj.x == tempPosX && tempObj.y == tempPosY){
                            memoObjects.slice(i, 1);  
                        }
                    }
                    
                    memoObject = new memo(
                        nIndex,
                        memoData[nIndex].Text,
                        memoData[nIndex].posX,
                        memoData[nIndex].posY,
                        50,
                        50,
                        "img/memo.png"
                    );
                    
                    memoObjects.push(memoObject);
                }                                                                      
            }
        }
        
        for (var nIndex = 0; nIndex < memoObjects.length; nIndex++) {
            var tempObj = memoObjects[nIndex];
            tempObj.drawMemo(context, opt);
        }
        
        //End Function : No.17 - Editor : Long - Date: 08/13/2013 - Summary : Draw newest memo  
    }
};

/* draw webGetContent4 */
function drawGetWebContent4(context, opt) {
    webGetContentType4Objects = [];
    //Start Function : No.4 - Editor : Long - Date: 08/14/2013 - Summary : For lazy loading
    var tempIndex = 0;
    
    if(opt == 0 || opt == null){
        tempIndex = getPageIndex();
    }
    else if(opt == 1){
        tempIndex = getPageIndex() + 1;
    }
    else if(opt == 2){
        tempIndex = getPageIndex() - 1;   
    }
    
    for (var nIndex = 0; nIndex < dataJsonType4.length; nIndex++) {
        /* get data belong current page*/
        var dataLinkList = dataJsonType4[nIndex].linkList;
        for (var nLinkList = 0; nLinkList < dataLinkList.length; nLinkList++) {
            /* create object webContentTyp4 */
            var dataObject = null;

            dataObject = new webContentType4(
                nLinkList,
                dataLinkList[nLinkList].linkLocationX,
                dataLinkList[nLinkList].linkLocationY,
                dataLinkList[nLinkList].linkLocationWidth,
                dataLinkList[nLinkList].linkLocationHeight,
                "img/webGetContent4.png",
                dataLinkList[nLinkList].linkKind,
                dataLinkList[nLinkList].destURI,
                dataLinkList[nLinkList].destPageNumber
            );
            
            dataObject["pageNo"] = dataJsonType4[nIndex].page;
            webGetContentType4Objects.push(dataObject);
            
            //Start Fix Bug : Cannot not click on link object - Editor : Long - Date : 08/30/2013
            if (changePageIndex(tempIndex) == dataObject["pageNo"]) {
                dataObject.drawObject(context, opt);
            }  
            //End Fix Bug : Cannot not click on link object - Editor : Long - Date : 08/30/2013         
        }        
    }
    //End Function : No.4 - Editor : Long - Date: 08/14/2013 - Summary : For lazy loading
};

//Start Function : No.4 - Editor : Long - Date: 08/14/2013 - Summary : For lazy loading
var isExistDrawing = false;
/* draw marking */
function drawMarkingOnScreen(opt) {
   
    var canvas;
    var context;
    var canvasWidth = $('#offscreen').width();
    var canvasHeight = $('#offscreen').height();
    var indexMarking;

    var tempPageNo = 0;
    
    if(opt == null || opt == 0){
        canvas = document.getElementById('offscreen');
        canvasWidth = $('#offscreen').width();
        canvasHeight = $('#offscreen').height();
                    
        tempPageNo = changePageIndex(getPageIndex()); 
    }
    else if(opt == 1){
        canvas = document.getElementById('offscreenNext');
        canvasWidth = $('#offscreenNext').width();
        canvasHeight = $('#offscreenNext').height();
        
        tempPageNo = changePageIndex(getPageIndex() + 1);
    }
    else if(opt == 2){
        canvas = document.getElementById('offscreenPre');
        canvasWidth = $('#offscreenPre').width();
        canvasHeight = $('#offscreenPre').height();
        
        tempPageNo = changePageIndex(getPageIndex() - 1);
    }

    context = canvas.getContext('2d');
    
    if (ClientData.IsAddingMarking() == false && ClientData.IsDisplayMarking() == true) {
        isExistDrawing = false;

        /* get data marking on local */
        var dataMarking = ClientData.MarkingData();
        for (var nIndex = 0; nIndex < dataMarking.length; nIndex++) {
            if (dataMarking[nIndex].contentid == contentID
            && dataMarking[nIndex].pageNo == tempPageNo) {
                /*create image */
                var img = new Image();
                img.onload = function () {
                    //context.drawImage(img,dataMarking[indexMarking].left,0,dataMarking[indexMarking].right - dataMarking[indexMarking].left,dataMarking[indexMarking].bottom - dataMarking[indexMarking].top,0,0,canvasWidth,canvasHeight);
                    context.drawImage(img, 0, 0, canvasWidth, canvasHeight);
                    flip(opt);
                    /* set flag */
                    isExistDrawing = true;
                    /* draw memo */
                    drawMemoOnScreen(opt);
                };
                img.src = dataMarking[nIndex].content;
                indexMarking = nIndex;
            }
        }

        if (isExistDrawing == false) {
            /* draw memo */
            drawMemoOnScreen(opt);
        }
    } else {
        /* draw memo */
        drawMemoOnScreen(opt);
    }
};

/*draw canvas*/
function draw(context, opt) {
    context.save();
    
    //Draw on main canvas
    if(opt==null || opt == 0){
        /* draw page objects */
        getContent().currentPage.drawPage(context);
    }
    //Draw on next canvas
    else if(opt == 1){
        getNextContent().currentPage.drawPage(context, 1);
    }
    //Draw on previous canvas
    else if(opt == 2){
        getPrevContent().currentPage.drawPage(context, 2);
    }
    
    context.restore();

    initImageCheckMarking();
};
//End Function : No.4 - Editor : Long - Date: 08/09/2013 - Summary : Edit function to draw multi canvas

var leftCanvas = 0;
var topCanvas = 0;
var count = 0;

//Start Function : No.4 - Editor : Long - Date: 08/09/2013 - Summary : Edit function to draw multi canvas
/* display to screen */
function flip(opt) {
    var canvas;
    var offscreen;
    
    if(opt==null || opt == 0){
        canvas = document.getElementById('main');
        offscreen = document.getElementById('offscreen');
    }else if(opt==1){
        canvas = document.getElementById('mainNext');
        offscreen = document.getElementById('offscreenNext');
    }else if(opt==2){
        canvas = document.getElementById('mainPre');
        offscreen = document.getElementById('offscreenPre');
    }

    var context = canvas.getContext('2d');
    
    //START TRB00097 - Editor: Long - Date: 09/30/2013 - Summary : Get All Page size of content  
    // init rect
    if(opt==null || opt == 0){
        if (srcRect.width == 0) {           
            srcRect = new Rect(0, 0, offscreen.width, offscreen.height);
        }
    }
    else if(opt==1){
        srcRectNext = new Rect(0, 0, offscreen.width, offscreen.height);      
    }
    else if(opt==2){
        srcRectPrev = new Rect(0, 0, offscreen.width, offscreen.height);
    }
    //END TRB00097 - Editor: Long - Date: 09/30/2013 - Summary : Get All Page size of content
    
    if(opt==null || opt==0){
        
        // display rect
        srcRect.add(moveX, moveY);
        
        // fix rect
        if (srcRect.left < 0) {
            srcRect.left = 0;
            srcRect.right = srcRect.left + srcRect.width;
        } else if (srcRect.right > offscreen.width) {
            srcRect.left = offscreen.width - srcRect.width;
            srcRect.right = offscreen.width
        }
        if (srcRect.top < 0) {
            srcRect.top = 0;
            srcRect.bottom = srcRect.top + srcRect.height;
        } else if (srcRect.bottom > offscreen.height) {
            srcRect.top = offscreen.height - srcRect.height;
            srcRect.bottom = offscreen.height;
        }
        
        // target rect
        var width = offscreen.width;
        var height = offscreen.height;
        var aspect = offscreen.width / offscreen.height;
        
        if (canvas.width > canvas.height) {
            height = canvas.height;
            width = height * aspect;
        } else {
            width = canvas.width;
            height = width / aspect;
        }
    
        if (height > canvas.height) {
            var size = canvas.height / height;
            height = canvas.height;
            width = width * size;
        }
    
        if (width > canvas.width) {
            var size = canvas.width / width;
            width = canvas.width;
            height = height * size;
        }
        
        if (userScale != 1 && width < canvas.width) {

            width = width * userScale;
            if (width > canvas.width) {
                width = canvas.width;
            }
    
        } else if (userScale != 1 && height < canvas.height) {
    
            height = height * userScale;
    
            if (height > canvas.height) {
                height = canvas.height;
            }
        }
        
        var destX = 0, destY = 0;
        destX = (canvas.width / 2) - (width / 2);
        destY = (canvas.height / 2) - (height / 2);
    
        if (destX < 0) {
            destX = 0;
        }
        if (destY < 0) {
            destY = 0;
        }
    
        if (srcRect.left < 0) {
            srcRect.left = 0;
        }
        if (srcRect.top < 0) {
            srcRect.top = 0;
        }
    
        destRect = new Rect(destX, destY, width, height);
    
        /* get position for drawing canvas*/
        if (isFirstLoad == true) {
            nPositionCanvas.left = destRect.left;
            nPositionCanvas.right = destRect.right;
            nPositionCanvas.top = destRect.top;
            nPositionCanvas.bottom = destRect.bottom;
    
            $("#draw_canvas").attr('height', destRect.bottom - destRect.top)
                  .attr('width', destRect.right - destRect.left)
                   .css('top', destRect.top + marginY)
                   .css('left', destRect.left + marginX);
    
            $("#marker_canvas").attr('height', destRect.bottom - destRect.top)
                  .attr('width', destRect.right - destRect.left)
                   .css('top', destRect.top + marginY)
                   .css('left', destRect.left + marginX);
    
            isFirstLoad = false;
        }
    
        leftCanvas = destX;
        topCanvas = destY;
        // change scale
        scaleX = offscreen.width / width;
        scaleY = offscreen.height / height;
        
        // draw canvas      
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.save();
    
        context.drawImage(offscreen,
                              srcRect.left, srcRect.top, srcRect.right - srcRect.left, srcRect.bottom - srcRect.top,
                          destRect.left, destRect.top, width, height);
        context.restore();
    }
    else if(opt==1){
        // display rect
        //srcRectNext.add(moveX, moveY);
        
        // fix rect
        if (srcRectNext.left < 0) {
            srcRectNext.left = 0;
            srcRectNext.right = srcRectNext.left + srcRectNext.width;
        } else if (srcRectNext.right > offscreen.width) {
            srcRectNext.left = offscreen.width - srcRectNext.width;
            srcRectNext.right = offscreen.width
        }
        if (srcRectNext.top < 0) {
            srcRectNext.top = 0;
            srcRectNext.bottom = srcRectNext.top + srcRectNext.height;
        } else if (srcRectNext.bottom > offscreen.height) {
            srcRectNext.top = offscreen.height - srcRectNext.height;
            srcRectNext.bottom = offscreen.height;
        }
        
        // target rect
        var width = offscreen.width;
        var height = offscreen.height;
        var aspect = offscreen.width / offscreen.height;
        
        if (canvas.width > canvas.height) {
            height = canvas.height;
            width = height * aspect;
        } else {
            width = canvas.width;
            height = width / aspect;
        }
    
        if (height > canvas.height) {
            var size = canvas.height / height;
            height = canvas.height;
            width = width * size;
        }
    
        if (width > canvas.width) {
            var size = canvas.width / width;
            width = canvas.width;
            height = height * size;
        }
        
        if (userScale != 1 && width < canvas.width) 
        {

            width = width * userScale;
            if (width > canvas.width) {
                width = canvas.width;
            }
    
        } 
        else if (userScale != 1 && height < canvas.height) {
    
            height = height * userScale;
    
            if (height > canvas.height) {
                height = canvas.height;
            }
        }
        
        var destX = 0, destY = 0;
        destX = (canvas.width / 2) - (width / 2);
        destY = (canvas.height / 2) - (height / 2);
    
        if (destX < 0) {
            destX = 0;
        }
        if (destY < 0) {
            destY = 0;
        }
    
        if (srcRectNext.left < 0) {
            srcRectNext.left = 0;
        }
        if (srcRectNext.top < 0) {
            srcRectNext.top = 0;
        }
    
        destRectNext = new Rect(destX, destY, width, height);
    
        /* get position for drawing canvas*/
        if (isFirstLoad == true) {
            nPositionCanvas.left = destRectNext.left;
            nPositionCanvas.right = destRectNext.right;
            nPositionCanvas.top = destRectNext.top;
            nPositionCanvas.bottom = destRectNext.bottom;
    
            $("#draw_canvas").attr('height', destRectNext.bottom - destRectNext.top)
                  .attr('width', destRectNext.right - destRectNext.left)
                   .css('top', destRectNext.top + marginY)
                   .css('left', destRectNext.left + marginX);
    
            $("#marker_canvas").attr('height', destRectNext.bottom - destRectNext.top)
                  .attr('width', destRectNext.right - destRectNext.left)
                   .css('top', destRectNext.top + marginY)
                   .css('left', destRectNext.left + marginX);
    
            isFirstLoad = false;
        }
    
        //leftCanvas = destX;
        //topCanvas = destY;
        // change scale
        //scaleX = offscreen.width / width;
        //scaleY = offscreen.height / height;
        
        // draw canvas      
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.save();
    
        context.drawImage(offscreen,
                              srcRectNext.left, srcRectNext.top, srcRectNext.right - srcRectNext.left, srcRectNext.bottom - srcRectNext.top,
                          destRectNext.left, destRectNext.top, width, height);
        context.restore();
    }
    else if(opt==2){
        // display rect
        //srcRectNext.add(moveX, moveY);
        
        // fix rect
        if (srcRectPrev.left < 0) {
            srcRectPrev.left = 0;
            srcRectPrev.right = srcRectPrev.left + srcRectPrev.width;
        } else if (srcRectNext.right > offscreen.width) {
            srcRectPrev.left = offscreen.width - srcRectPrev.width;
            srcRectPrev.right = offscreen.width
        }
        if (srcRectPrev.top < 0) {
            srcRectPrev.top = 0;
            srcRectPrev.bottom = srcRectPrev.top + srcRectPrev.height;
        } else if (srcRectPrev.bottom > offscreen.height) {
            srcRectPrev.top = offscreen.height - srcRectPrev.height;
            srcRectPrev.bottom = offscreen.height;
        }
        
        // target rect
        var width = offscreen.width;
        var height = offscreen.height;
        var aspect = offscreen.width / offscreen.height;
        
        if (canvas.width > canvas.height) {
            height = canvas.height;
            width = height * aspect;
        } else {
            width = canvas.width;
            height = width / aspect;
        }
    
        if (height > canvas.height) {
            var size = canvas.height / height;
            height = canvas.height;
            width = width * size;
        }
    
        if (width > canvas.width) {
            var size = canvas.width / width;
            width = canvas.width;
            height = height * size;
        }
        
        if (userScale != 1 && width < canvas.width) 
        {

            width = width * userScale;
            if (width > canvas.width) {
                width = canvas.width;
            }
    
        } 
        else if (userScale != 1 && height < canvas.height) {
    
            height = height * userScale;
    
            if (height > canvas.height) {
                height = canvas.height;
            }
        }
        
        var destX = 0, destY = 0;
        destX = (canvas.width / 2) - (width / 2);
        destY = (canvas.height / 2) - (height / 2);
    
        if (destX < 0) {
            destX = 0;
        }
        if (destY < 0) {
            destY = 0;
        }
    
        if (srcRectPrev.left < 0) {
            srcRectPrev.left = 0;
        }
        if (srcRectPrev.top < 0) {
            srcRectPrev.top = 0;
        }
    
        destRectPrev = new Rect(destX, destY, width, height);
    
        /* get position for drawing canvas*/
        if (isFirstLoad == true) {
            nPositionCanvas.left = destRectPrev.left;
            nPositionCanvas.right = destRectPrev.right;
            nPositionCanvas.top = destRectPrev.top;
            nPositionCanvas.bottom = destRectPrev.bottom;
    
            $("#draw_canvas").attr('height', destRectPrev.bottom - destRectPrev.top)
                  .attr('width', destRectPrev.right - destRectPrev.left)
                   .css('top', destRectPrev.top + marginY)
                   .css('left', destRectPrev.left + marginX);
    
            $("#marker_canvas").attr('height', destRectPrev.bottom - destRectPrev.top)
                  .attr('width', destRectPrev.right - destRectPrev.left)
                   .css('top', destRectPrev.top + marginY)
                   .css('left', destRectPrev.left + marginX);
    
            isFirstLoad = false;
        }
    
        //leftCanvas = destX;
        //topCanvas = destY;
        // change scale
        //scaleX = offscreen.width / width;
        //scaleY = offscreen.height / height;
        
        // draw canvas      
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.save();
    
        context.drawImage(offscreen,
                              srcRectPrev.left, srcRectPrev.top, srcRectPrev.right - srcRectPrev.left, srcRectPrev.bottom - srcRectPrev.top,
                          destRectPrev.left, destRectPrev.top, width, height);
        context.restore();
    }                 
};
//End Function : No.4 - Editor : Long - Date: 08/09/2013 - Summary : Edit function to draw multi canvas

/* handle display controls of video */
function showControlsVideo(target) {
    $(target).click(function () {
        $(target).attr('controls', '');
    });
    $(target).mouseout(function () {
        $(target).removeAttr('controls');
    });
    $(target).removeAttr('controls');
};

/* show video*/
function showVideoObject(x, y, width, height, src, isFullscreen) {

    var pt1 = imageToScreen(x, y);
    var pt2 = imageToScreen(x + width, y + height);

    if (isFullScreen == true) {
        pt2.y = pt2.y - marginY;
        pt1.y = pt1.y - marginY;
    }

    //getPosVideo(x, y, (pt2.x - pt1.x), (pt2.y - pt1.y));
    getPosVideo(x, y, width, height);

    if (isFullscreen === false) {
        $('#playvideo').attr('z-order', '1000');
        $('#playvideo').css('left', pt1.x + 'px');
        $('#playvideo').css('top', pt1.y + 'px');
        $('#playvideo').children().remove();

        if (ClientData.userOpt_videoMode() == "1") {/* loop video */
            $('#playvideo').html('<video class="mov" id="videoOnPage" ' +
                             'width="' + (pt2.x - pt1.x) + '" ' +
                             'height="' + (pt2.y - pt1.y) + '" ' +
                             'autoplay controls loop>' +
                             '   <source src="' + src + '&key=' + (new Date()).toIdString() + '" type="video/mp4"> ' +
                             '    <source src="' + src + '&key=' + (new Date()).toIdString() + '" type="video/ogg"> ' +
                             '</video>'
                );
        } else {
            $('#playvideo').html('<video class="mov" id="videoOnPage"' +
                             'width="' + (pt2.x - pt1.x) + '" ' +
                             'height="' + (pt2.y - pt1.y) + '" ' +
                             'autoplay controls>' +
                             '   <source src="' + src + '&key=' + (new Date()).toIdString() + '" type="video/mp4"> ' +
                             '    <source src="' + src + '&key=' + (new Date()).toIdString() + '" type="video/ogg"> ' +
                             '</video>'
                );
        }
    } else {
        $('#playvideo').attr('z-order', '1000');
        $('#playvideo').html('<video class="mov" id="videoOnPage" src="' + src + '" ' +
                         'autoplay controls></video>');
    }

    //showControlsVideo($('#videoOnPage'));

};

/* stop all audio on page */
function stopAllAudio() {
    if (avwUserEnvObj.browser == 'firefox') {
        $('#playaudiopage').children().remove();
        $('#playaudioallpage').children().remove();
        $('#playaudio').children().remove();
    } else {
        if (document.getElementById("play_audio_0") != undefined) {
            if(document.getElementById("play_audio_0").played){
               document.getElementById("play_audio_0").pause(); 
            }           
        }

        if (document.getElementById("play_audio_1") != undefined) {                       
            if(document.getElementById("play_audio_1").played){
               document.getElementById("play_audio_1").pause();
            }     
        }

        if (document.getElementById("play_audio_2") != undefined) {
            document.getElementById("play_audio_2").pause();
            
            if(document.getElementById("play_audio_2").played){
               document.getElementById("play_audio_2").pause();
            } 
        }
    }
};

/* play all audio on page */
function playAllAudio() {
    if (avwUserEnvObj.browser == 'firefox') {
        if (srcAudioType0 != '') {
            createAudio(srcAudioType0, TypeAudio0);
        } else if (srcAudioType2 != '') {
            createAudio(srcAudioType2, TypeAudio2);
        } else if (TypeAudio1 != '') {
            createAudio(srcAudioType1, TypeAudio1);
        }
    } else {
        if (document.getElementById("play_audio_0") != undefined) {
            if (avwUserEnvObj.os == "ipad") {
                //document.getElementById("play_audio_0").load();
            }
            document.getElementById("play_audio_0").play();
        } else if (document.getElementById("play_audio_2") != undefined) {
            if (avwUserEnvObj.os == "ipad") {
                //document.getElementById("play_audio_2").load();
            }
            document.getElementById("play_audio_2").play();
        } else if (document.getElementById("play_audio_1") != undefined) {
            if (avwUserEnvObj.os == "ipad") {
                //document.getElementById("play_audio_1").load();
            }
            document.getElementById("play_audio_1").play();
        }
    }
};

var srcAudioType0 = '';
var TypeAudio0;
var srcAudioType1 = '';
var TypeAudio1;
var srcAudioType2 = '';
var TypeAudio2;

/* change main image of media type 4 */
function changeImageType4(objTarget, nIndex, nIndex1) {
    var imageObj = new Image();
    imageObj.onload = function () {
        var canvasObject = document.getElementById("offscreen");
        var contextObject = canvasObject.getContext("2d");
        
        //#11478
        var canvasWidth = $('#offscreen').width();
        var canvasHeight = $('#offscreen').height();
        var tempRatioWidth = canvasWidth / widthEachPageApi;
        if( tempRatioWidth < 1 ){
            tempRatioWidth = 1;
        }
        var tempRatioHeight = canvasHeight / heightEachPageApi;
        if( tempRatioHeight < 1 ){
            tempRatioHeight = 1;
        }
        var tmpX = objTarget[nIndex].x *  tempRatioWidth;
        var tmpY = objTarget[nIndex].y * tempRatioHeight;
        var tmpW = objTarget[nIndex].width *  tempRatioWidth;
        var tmpH = objTarget[nIndex].height * tempRatioHeight;
        
        contextObject.drawImage(imageObj, tmpX, tmpY, tmpW, tmpH);
        //contextObject.drawImage(imageObj, objTarget[nIndex].x, objTarget[nIndex].y, objTarget[nIndex].width, objTarget[nIndex].height);
        
        flip();
    };
    imageObj.src = objTarget[nIndex].dataObjects[nIndex1].fileName;
};

function imageToScreen(x, y) {

    //#11478
    var canvasWidth = $('#offscreen').width();
    var canvasHeight = $('#offscreen').height();
    var tempRatioWidth = canvasWidth / widthEachPageApi;
    if( tempRatioWidth < 1 ){
        tempRatioWidth = 1;
    }
    var tempRatioHeight = canvasHeight / heightEachPageApi;
    if( tempRatioHeight < 1 ){
        tempRatioHeight = 1;
    }
    var tmpX = x *  tempRatioWidth;
    var tmpY = y * tempRatioHeight;

    var pt = new Point(0, 0);

    // scale vertical and horizontal 
    var sx = (destRect.right - destRect.left) / (srcRect.right - srcRect.left);
    var sy = (destRect.bottom - destRect.top) / (srcRect.bottom - srcRect.top);

    pt.x = Math.round(sx * (tmpX - srcRect.left)) + destRect.left + marginX;
    pt.y = Math.round(sy * (tmpY - srcRect.top)) + destRect.top + marginY;

    return pt;
};
//Start Function : No.4 - Editor : Long - Date : 08/09/2013 - Summary : 
/* Adjust Component size */
function sizingNotFull(width, height) {
    
    //START TRB
    if(isMediaAndHTMLContent()){

    }
    //END TRB
    else{
        //adjust size of canvas using for draw      
        if (COMMON.isTouchDevice() == true) {
            $("#main").css('top', marginY);
            $("#main").attr('height', height - (marginY * 2))
              .attr('width', width - (marginX * 2));
            $("#mainNext").css('top', marginY);
            $("#mainPre").css('top', marginY);    
                
            $("#mainNext").attr('height', height - (marginY * 2))
              .attr('width', width - (marginX * 2))
              .css('left', width + marginX);
              
            $("#mainPre").attr('height', height - (marginY * 2))
              .attr('width', width - (marginX * 2))
              .css('left', - (width + marginX));
    
        } else {
            $("#main").attr('height', height - (marginY * 2))
                  .attr('width', width - (marginX * 2))
                   .css('top', marginY);
                        
            $("#mainNext").attr('height', height - (marginY * 2))
              .attr('width', width - (marginX * 2))
               .css('top', marginY)
               .css('left', width + marginX);
               
            $("#mainPre").attr('height', height - (marginY * 2))
              .attr('width', width - (marginX * 2))
               .css('top', marginY)
               .css('left', -(width + marginX));
         
        }
    
        $("#draw_canvas").css('cursor', 'default');
        $("#marker_canvas").css('cursor', 'default');
    
        if (userScale != 1) {
            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
        }
            
        /* move image check marking*/
        $('#divCheckExistMarking').css('top', '70px');
        $('#divCheckExistMarking').show();
    }   
};

/* Adjust Component size */
function sizingFullSize(width, height) {
    // adjust size of body
    
    //START TRB
    if(isMediaAndHTMLContent()){

    }
    //END TRB
    else{
        if (COMMON.isTouchDevice() == true) {
            $("#main").css('top', '0px');
            $("#main").attr('height', height)
                       .attr('width', width - (marginX * 2));
                       
            $("#mainNext").css('top', '0px');
            $("#mainNext").attr('height', height)
                       .attr('width', width - (marginX * 2));
                       
            $("#mainPre").css('top', '0px');
            $("#mainPre").attr('height', height)
                       .attr('width', width - (marginX * 2));
        } else {
            $("#main").attr('height', height)
                       .attr('width', width - (marginX * 2))
                       .css('top', '0px');
            $("#mainNext").attr('height', height)
                        .attr('width', width - (marginX * 2))
                    .css('top', '0px');
            $("#mainPre").attr('height', height)
                    .attr('width', width - (marginX * 2))
                .css('top', '0px');
        }
    
        //adjust size of canvas using for draw
    
        $("#draw_canvas").css('cursor', 'default');
        $("#marker_canvas").css('cursor', 'default');
    
        if (userScale != 1) {
            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
        }
    
        /* move image check marking*/
        $('#divCheckExistMarking').css('top', '5px');
        if (ClientData.IsAddingMarking() == true) {
            $('#divCheckExistMarking').hide();
        } else {
            $('#divCheckExistMarking').show();
        }
    }   
};
//End Function : No.4 - Editor : Long - Date : 08/09/2013 - Summary : 
function zoomVideo() {
    var objVideo = document.getElementsByTagName('video');
    if (objVideo.length > 0) {
        var pt1 = imageToScreen(pxVideo, pyVideo);
        var pt2 = imageToScreen(pxVideo + wVideo, pyVideo + hVideo);

        if (isFullScreen == true) {
            pt2.y = pt2.y - marginY;
            pt1.y = pt1.y - marginY;
        }
        $('#playvideo').attr('z-order', '1000');

        $('#playvideo').css('left', pt1.x + 'px');
        $('#playvideo').css('top', pt1.y + 'px');

        $(objVideo[0]).attr('width', pt2.x - pt1.x);
        $(objVideo[0]).attr('height', pt2.y - pt1.y);
    }
};

var scaleFactor = 1.1;
var zoom = function (clicks) {

    var pt = context_main.transformedPoint(lastX, lastY);
    context_main.translate(lastX, lastY);
    var factor = Math.pow(scaleFactor, clicks);
    context_main.scale(factor, factor);
    maxposY += canvas_main.width * (factor - 1);
    context_main.translate(-lastX, -lastY);
};

// Adds ctx.getTransform() - returns an SVGMatrix
// Adds ctx.transformedPoint(x,y) - returns an SVGPoint
function trackTransforms(ctx) {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg');
    var xform = svg.createSVGMatrix();
    ctx.getTransform = function () { return xform; };

    var savedTransforms = [];
    var save = ctx.save;
    ctx.save = function () {
        savedTransforms.push(xform.translate(0, 0));
        return save.call(ctx);
    };
    var restore = ctx.restore;
    ctx.restore = function () {
        xform = savedTransforms.pop();
        return restore.call(ctx);
    };

    var scale = ctx.scale;
    ctx.scale = function (sx, sy) {
        xform = xform.scaleNonUniform(sx, sy);
        return scale.call(ctx, sx, sy);
    };
    var rotate = ctx.rotate;
    ctx.rotate = function (radians) {
        xform = xform.rotate(radians * 180 / Math.PI);
        return rotate.call(ctx, radians);
    };
    var translate = ctx.translate;
    ctx.translate = function (dx, dy) {
        xform = xform.translate(dx, dy);
        return translate.call(ctx, dx, dy);
    };
    var transform = ctx.transform;
    ctx.transform = function (a, b, c, d, e, f) {
        var m2 = svg.createSVGMatrix();
        m2.a = a; m2.b = b; m2.c = c; m2.d = d; m2.e = e; m2.f = f;
        xform = xform.multiply(m2);
        return transform.call(ctx, a, b, c, d, e, f);
    };
    var setTransform = ctx.setTransform;
    ctx.setTransform = function (a, b, c, d, e, f) {
        xform.a = a;
        xform.b = b;
        xform.c = c;
        xform.d = d;
        xform.e = e;
        xform.f = f;
        return setTransform.call(ctx, a, b, c, d, e, f);
    };
    var pt = svg.createSVGPoint();
    ctx.transformedPoint = function (x, y) {
        pt.x = x; pt.y = y;
        return pt.matrixTransform(xform.inverse());
    }
};

/* zoomIn event */
function zoomIn() {
    userScale += scaleDelta;

    if (userScale > 4) {
        userScale = 4;
    }
    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();

    /* close dialog popuptext */
    closeDialogPopUpText();
};

/* close dialog pop */
function closeDialogPopUpText() {
    if (isOpenPopUpText == true) {
        isOpenPopUpText = false;
        ClosePopupText();
    }
};

function checkDisableButtonZoom() {
    if (userScale >= 4) {
        $('#zoomin').removeClass();
        $('#zoomin').addClass('expansion_off');
        $("#zoomin").css('cursor', 'default');
    } else {
        $('#zoomin').unbind('click');
        $('#zoomin').bind('click', zoomIn);

        $('#zoomin').removeClass();
        if (COMMON.isTouchDevice() == true) {
            $('#zoomin').addClass('expansion_device');
        } else {
            $('#zoomin').addClass('expansion');
        }
        $("#zoomin").css('cursor', 'pointer');
    }

    if (userScale <= 1) {
        $('#zoomout').removeClass();
        $('#zoomout').addClass('reduction_off');
        $("#zoomout").css('cursor', 'default');
    } else {
        $('#zoomout').unbind('click');
        $('#zoomout').bind('click', zoomOut);

        $('#zoomout').removeClass();
        if (COMMON.isTouchDevice() == true) {
            $('#zoomout').addClass('reduction_device');
        } else {
            $('#zoomout').addClass('reduction');
        }
        $("#zoomout").css('cursor', 'pointer');
    }

    if (userScale == 1) {
        $('#zoomfit').removeClass();
        $('#zoomfit').addClass('fit_off');
        $("#zoomfit").css('cursor', 'default');
    } else {
        $('#zoomfit').unbind('click');
        $('#zoomfit').bind('click', screenFit);

        $('#zoomfit').removeClass();
        if (COMMON.isTouchDevice() == true) {
            $('#zoomfit').addClass('fit_device');
        } else {
            $('#zoomfit').addClass('fit');
        }
        $("#zoomfit").css('cursor', 'pointer');
    }
};

/* zoomOut event */
function zoomOut() {
    userScale -= scaleDelta;
    if (userScale < 1) {
        userScale = 1;
    } 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();

    /* close dialog popuptext */
    closeDialogResize();
};

/* restore screen size */
function screenFit() {

    var canvas = document.getElementById('main');
    var offScreen = document.getElementById('offscreen'); 
    context_main.clearRect(0, 0, canvas_main.width, canvas_main.height);
    srcRect = new Rect(0, 0, offScreen.width, offScreen.height);
    userScale = 1;
    userScaleNow = 1;
    
    moveX = 0;
    moveY = 0;

    flip();
    
    //Start Function : No.4 - Editor : Long - Date : 08/13/2013 - Summary : Fix for zooming
    if(getPageIndex() < totalPage - 1){
        flip(1);
    }
    
    if(getPageIndex() > 0){
        flip(2);
    }
    //End Function : No.4 - Editor : Long - Date : 08/13/2013 - Summary : Fix for zooming
    
    /* zoom video */
    zoomVideo();

    checkDisableButtonZoom();

    /* close dialog popuptext */
    closeDialogResize();
};

/* change Scale screen*/
function changeScale(scale) {

    //拡大か判定
    var isZoom = false;
    if( userScaleNow < scale ){
        isZoom = true;
    }
    userScaleNow = scale;

    var canvas = document.getElementById('main');
    var offScreen = document.getElementById('offscreen');

    var sc = srcRect.center();

    var sw = offScreen.width, sh = offScreen.height;

    var width = offScreen.width;
    var height = offScreen.height;
    var aspect = offScreen.width / offScreen.height;
    if (canvas.width > canvas.height) {
        height = canvas.height;
        width = height * aspect;
        /*if(width > canvas.width) {
        width = canvas.width;
        height = width / aspect;
        }*/
    } else {
        width = canvas.width;
        height = width / aspect;
    }

    if (height > canvas.height) {
        var size = canvas.height / height;
        height = canvas.height;
        width = width * size;
    }

    if (width > canvas.width) {
        var size = canvas.width / width;
        width = canvas.width;
        height = height * size;
    }

    if (width < canvas.width) {

        //if(width >= height){
        width = width * scale;

        if (width > canvas.width) {
            sw /= scale;
            sh = sw / (canvas.width / canvas.height);

        } else {
            sh /= scale;
        }

        //}else if(height <= canvas.height){
    } else if (height < canvas.height) {

        height = height * scale;

        if (height > canvas.height) {
            sh /= scale;
            sw = sh / (canvas.height / canvas.width);


        } else {
            sw /= scale;
        }

    } else {
        sh /= scale;
        sw /= scale;
    }

    srcRect.left = sc.x - Math.round(sw / 2);
    srcRect.top = sc.y - Math.round(sh / 2);
    srcRect.right = Math.round(srcRect.left + sw);
    srcRect.bottom = Math.round(srcRect.top + sh);
    srcRect.width = srcRect.right - srcRect.left;
    srcRect.height = srcRect.bottom - srcRect.top;
    
    if( isZoom ){
        
        //var tempRatioWidth = offScreen.width / widthEachPageApi;
        var tempRatioWidth = widthEachPageApi / offScreen.width;
            if( tempRatioWidth > 1 ){
                tempRatioWidth = 1;
            }
        //var tempRatioHeight = offScreen.height / heightEachPageApi;
        var tempRatioHeight = heightEachPageApi / offScreen.height;
        if( tempRatioHeight > 1 ){
            tempRatioHeight = 1;
        }
        
        
        var tmpX = 0;
        var tmpY = 0;
        if( srcRect.top > 0 ){
            tmpX = Math.round(srcRect.top * tempRatioWidth);
        }
        if( srcRect.left > 0 ){
            tmpY = Math.round(srcRect.left * tempRatioHeight);
        }
        
        var tmpW = Math.round(srcRect.width * tempRatioWidth);
        var tmpH = Math.round(srcRect.height * tempRatioHeight);
        
        var zoomX = tmpX + Math.round( tmpH / 2 );
        var zoomY = tmpY + Math.round( tmpW / 2 );
        
        //console.log("tempRatio.width:height " + tempRatioWidth + "," + tempRatioHeight);
        //console.log("srcRect.left:top " + srcRect.left + "," + srcRect.top);
        //console.log("srcRect.width:height " + srcRect.width + "," + srcRect.height);
        //console.log("tmpX.Y " + tmpX + "," + tmpY);
        //console.log("tmpW.H " + tmpW + "," + tmpH);
        //console.log("zoomX.Y " + zoomX + "," + zoomY);
    
        //詳細ログ作成
        var objectLog = new ObjectLogEntity();
        objectLog.contentid = contentID;
        objectLog.pageNo = getPageIndex() + 1; //0始まりのページ番号
        objectLog.objectId = 0;
        objectLog.resourceId = "";
        objectLog.mediaType = "";
        objectLog.actionType = "101"; //拡大アクション定数
        objectLog.actionValue = "";
        objectLog.actionTime = "0";
        objectLog.locationX = zoomX;
        objectLog.locationY = zoomY;
        objectLog.locationHeight = "";
        objectLog.locationWidth = "";
        objectLog.eventType = "5"; //暫定でピンチアウト
        COMMON.SetObjectLog(contentID, objectLog);
        //---
    }
    
};
/* change Scale screen*/
function changeScaleDrawCanvas(scale) {
    var canvas = document.getElementById('draw_canvas');
    var offScreen = document.getElementById('draw_canvas');

    var sc = srcRect.center();

    var sw = offScreen.width, sh = offScreen.height;
    sw /= scale;
    sh /= scale;
    srcRect.left = sc.x - Math.floor(sw / 2);
    srcRect.top = sc.y - Math.floor(sh / 2);
    srcRect.right = srcRect.left + sw;
    srcRect.bottom = srcRect.top + sh;
    srcRect.width = sw;
    srcRect.height = sh;
};


//Start Function : No.9 - Editor : Long - Date : 08/16/2013 - Summary :
function is3DObject(pageContent){
    var result = false;
    if(pageContent == null || pageContent == undefined){
        result = false;
    }
    else{
        if(pageContent.actionType == 9 && pageContent.mediaType == 8){
            result = true;
        }
    }    
    return result;
};
//End Function : No.9 - Editor : Long - Date : 08/16/2013 - Summary :