/// <reference path="../common/js/jquery-1.8.1.min.js" />

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

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

/* init const */
var WIDTH_DIALOG_BOOKMARK = 300;
var HEIGHT_DIALOG_BOOKMARK = 700;
var HEIGHT_DIALOG_BOOKMARK_NO_BOOKMARK = 200;

var WIDTH_DIALOG_INDEX = 300;
var HEIGHT_DIALOG_INDEX = 700;
var HEIGHT_DIALOG_INDEX_NO_INDEX = 200;

var WIDTH_DIALOG_SEARCH = 300;
var HEIGHT_DIALOG_SEARCH = 700;
var HEIGHT_DIALOG_SEARCH_NO_SEARCH = 200;

var WIDTH_DIALOG_COPYTEXT = 300;
var HEIGHT_DIALOG_COPYTEXT = 500;
var HEIGHT_DIALOG_COPYTEXT_NO_COPYTEXT = 200;

/* init variable */
var pageImages = '';
var totalPage = 0;
var pageObjects = [];
var pageObjectsData = [];
var tool;
var isFullScreen = false;
var ctrlMode = false;
var dataWebContentPage;
var dataPageTitle;
var dataJsonType4;
var dataJsonType5;
var contentID;
var isOpenPopUpText = false;
var isOpenPopUpMemo = true;
var objEditMemo;
var isCopyMemo = false;
var isExistCopyMemo = false;
var posXPopupMemo = 0;
var posYPopupMemo = 0;
var contentName = '';
var nCountObjectLoad = 0;
var nAjaxLoad = 0;
var isClearDrawing = false;
var isDrawing = false;
var mediaType4_changeImage = 0;
var isLoadingObject = false;
var isFirstLoad = true;
var nPositionCanvas = [];
var arrImage = [];
var posTxtSearch = [];
var sx, sy;
var imgDrawingTemp;
var imgMarkerTemp;
var isSizingDrawCanvas = false;
var isDisplayBookMarkList = false;
var avwUserEnvObj = new UserEnvironment();
var canvas_marker;
var context_marker;
var canvas_draw;
var context_draw;
var canvas_main;
var context_main;
var canvas_offscreen;
var context_offscreen;
var isAddingMarking;
var penSize;
var penColor;
var makerSize;
var makerColor;
var eraseSize;
var markingType;
var isDisplayCopyText = false;
var isDisplayListIndex = false;
var isChangeSizeScreen = false;
var widthContentImage = 0;
var heightContentImage = 0;
var widthEachPage = 0;
var heightEachPage = 0;
var px = 0;
var py = 0;
var isPressLeftMouse = false;
var isMoveOutDrawCanvas = false;
var typeSelectMemo = 0;
var arrThumbnailsLoaded = [];
var isSendingData = true;
var isPlayBGMUnlock = false;
var isJumpNotFromFirstPage = false;
var standardRatio = 1;
var currentRatio = 1;
/*
Clear canvas
*/
function clearCanvas(targetCanvas) {
    targetCanvas.width = targetCanvas.width;
};

/* get Json stored content info */
function getJsonContentInfo() {
    avwGrabContentPageImage(ClientData.userInfo_accountPath(),
	     { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: 1 },
	     function (data) {
	         pageImages = data;
	         webGetContentData();
	         getSearchDataFromJson();
	         getJsonDataPageTitle();
	         getJsonDataType4();
	         getJsonDataType5();
	         getDataJsonFile();
	         webGetPageImageContentSize();
	     },
	     function (xmlHttpRequest, txtStatus, errorThrown) {
	         showErrorScreen();
	     });
};

function webGetPageImageContentSize() {
    avwCmsApi(ClientData.userInfo_accountPath(),
	     "webContentPageSize",
	     "GET",
	     { contentId: contentID, sid: ClientData.userInfo_sid() },
	     function (data) {
	         widthContentImage = data.width;
	         heightContentImage = data.height;
	     },
	     null);
};


function webGetContentData() {
    avwCmsApi(ClientData.userInfo_accountPath(),
	     "webGetContent",
	     "GET",
	     { contentId: contentID, sid: ClientData.userInfo_sid(), getType: 1 },
	     function (data) {
	         totalPage = data.contentData.allPageNum;
	     },
	     null);
};

/* get Json stored page title */
function getJsonDataPageTitle() {
    avwCmsApi(ClientData.userInfo_accountPath(),
	     "webGetContent",
	     "GET",
	     { contentId: contentID, sid: ClientData.userInfo_sid(), getType: 3 },
	     function (data) {
	         dataPageTitle = [];
	         for (var nIndex = 0; nIndex < totalPage; nIndex++) {
	             dataPageTitle.push("");
	         }
	         if (data.contentData) {

	             if (data.contentData.titleInfo) {
	                 dataPageTitle = data.contentData.titleInfo;
	             }
	         }
	     },
	     null);
};

/* get Json webGetContent4 */
function getJsonDataType4() {
    avwCmsApi(ClientData.userInfo_accountPath(),
	     "webGetContent",
	     "GET",
	     { contentId: contentID, sid: ClientData.userInfo_sid(), getType: 4 },
	     function (data) {
	         dataJsonType4 = data.contentData.linkData;
	     },
	     null);
};

/* get Json webGetContent5 */
function getJsonDataType5() {
    avwCmsApi(ClientData.userInfo_accountPath(),
	     "webGetContent",
	     "GET",
	     { contentId: contentID, sid: ClientData.userInfo_sid(), getType: 5 },
	     function (data) {
	         dataJsonType5 = data.contentData.outlineData;
	     },
	     null);
};

/* get url */
function getURL(apiName) {
    var sysSettings = avwSysSetting();
    var url = sysSettings.apiResourceDlUrl;
    url = format(url, ClientData.userInfo_accountPath()) + '/' + apiName;
    return url;
};

/* get url */
function getURLPageImage(apiName) {
    var sysSettings = avwSysSetting();
    var url = sysSettings.apiUrl;
    url = format(url, ClientData.userInfo_accountPath()) + '/' + apiName;
    return url;
};

/* read file Json -> get page objects */
function getDataJsonFile() {
    //get content from JSON
    avwCmsApi(ClientData.userInfo_accountPath(),
		     "webGetContent",
		     "GET",
		     { sid: ClientData.userInfo_sid(), contentId: contentID, getType: 2 },
		     function (data) {
		         var JsonFile = data.contentData;
		         pageObjectsData = [];
		         if (JsonFile.vertical) {
		             if (JsonFile.vertical.pages) {
		                 pageObjectsData = JsonFile.vertical.pages;
		             }
		         }
		         else if (JsonFile.horizontal) {
		             if (JsonFile.horizontal.pages) {
		                 pageObjectsData = JsonFile.horizontal.pages;
		             }
		         }

		         getPageObjectsByPageIndex(pageObjectsData, 0);
		     },
		     null);
};

function getPageObjectsByPageIndex(contentData, nIndexPage) {
    pageObjects = [];

    var currentPageObjects;
    for (var nIndex = 0; nIndex < contentData.length; nIndex++) {
        if (contentData[nIndex].page == nIndexPage) {
            currentPageObjects = contentData[nIndex].objects;
            break;
        }
    }

    if (currentPageObjects != undefined) {
        for (var nIndex = 0; nIndex < currentPageObjects.length; nIndex++) {
            /*get object page*/
            if (currentPageObjects[nIndex].mediaType == 1) {/*media type = 1 */
                var pageObject = getMediaType1(currentPageObjects[nIndex]);
                /*add object to page */
                if ( pageObject != null ) {
                    pageObjects.push(pageObject);
                }
            } else if (currentPageObjects[nIndex].mediaType == 2) { /*mediaType = 2 */
                var pageObject = getMediaType2(currentPageObjects[nIndex]);
                /*add object to page */
                pageObjects.push(pageObject);
            } else if (currentPageObjects[nIndex].mediaType == 3) { /*mediaType = 3*/
                var pageObject = getMediaType3(currentPageObjects[nIndex]);
                /*add object to page */
                pageObjects.push(pageObject);
            } else if (currentPageObjects[nIndex].mediaType == 4) { /*mediaType = 4*/
                var pageObject = getMediaType4(currentPageObjects[nIndex]);
                /*add object to page */
                pageObjects.push(pageObject);
            } else if (currentPageObjects[nIndex].mediaType == 5) { /*mediaType = 5*/
                var pageObject = getMediaType5(currentPageObjects[nIndex]);
                /*add object to page */
                pageObjects.push(pageObject);
            } else if (currentPageObjects[nIndex].mediaType == 6) { /*mediaType = 6*/
                var pageObject = getMediaType6(currentPageObjects[nIndex]);
                /*add object to page */
                pageObjects.push(pageObject);
            } else if (currentPageObjects[nIndex].mediaType == 7) { /*mediaType = 7*/
                var pageObject = getMediaType7(currentPageObjects[nIndex]);
                /*add object to page */
                pageObjects.push(pageObject);
            } else if (currentPageObjects[nIndex].mediaType == 8) { /*mediaType = 8*/
                var pageObject = getMediaType8(currentPageObjects[nIndex]);
                /*add object to page */
                pageObjects.push(pageObject);
            }
        }
    }
};

/*get data mediaType = 1 */
function getMediaType1(iValueObj) {
    /*
    * Action Type = 1 : video
    * Action Type = 2 : music
    * Action Type = 3 : url
    * Action Type = 4 : image preview
    * Action Type = 5 : jump page
    * Action Type = 6 : email
    * Action Type = 7 : 
    * Action Type = 8 : popup
    * Action Type = 9 : video
    * Action Type = 10 : content
    * Action Type = 11 : html
    */
    if ( iValueObj.action != null ) {
        if ( iValueObj.action.actionType == 10 || iValueObj.action.actionType == 11 || iValueObj.action.actionType == 12 || iValueObj.action.actionType == 13 ) {
            return null;
        }
    }
    var pageObject = [];

    pageObject['mediaType'] = iValueObj.mediaType;
    pageObject['actionType'] = iValueObj.action.actionType;
    pageObject['visible'] = true;

    /*get location */
    pageObject['x'] = iValueObj.location.x;
    pageObject['y'] = iValueObj.location.y;
    pageObject['width'] = iValueObj.location.width;
    pageObject['height'] = iValueObj.location.height;
    pageObject['id'] = "MediaType1_" + iValueObj.action.actionType;
    if (iValueObj.action.actionType == 0) {
        /*get mediaInfo */
        if (iValueObj.mediaInfo) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }
    } else if (iValueObj.action.actionType == 1) {
        /*get mediaInfo */
        if (iValueObj.mediaInfo) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }

        /*get video file */

        if (iValueObj.action.video) {
            pageObject['mediaFile'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceName=" + removeExt(iValueObj.action.video);
            pageObject['media'] = iValueObj.action.video;
        } else {
            pageObject['mediaFile'] = '';
            pageObject['media'] = '';
        }

    } else if (iValueObj.action.actionType == 2) {
        /*get mediaInfo */
        if (iValueObj.mediaInfo) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }

        /*get video file */
        if (iValueObj.action.music) {
            if (avwUserEnvObj.browser == 'msie') {
                pageObject['audioFile'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceName=" + removeExt(iValueObj.action.music) + "&isIE=true";
            } else {
                pageObject['audioFile'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceName=" + removeExt(iValueObj.action.music);
            }
        } else {
            pageObject['audioFile'] = '';
        }

    } else if (iValueObj.action.actionType == 3) {
        /*get browserType */
        if (iValueObj.action.browserType) {
            pageObject['browserType'] = iValueObj.action.browserType;
        } else {
            pageObject['browserType'] = '';
        }

        /*get browser */
        if (iValueObj.action.browser) {
            pageObject['browser'] = iValueObj.action.browser;
        } else {
            pageObject['browser'] = '';
        }

        /*get linkUrl */
        if (iValueObj.action.linkUrl) {
            pageObject['linkUrl'] = iValueObj.action.linkUrl;
        } else {
            pageObject['linkUrl'] = '';
        }

        /*get mediaInfo */
        if (iValueObj.mediaInfo) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }

        /* action */
        pageObject['action'] = null;

    } else if (iValueObj.action.actionType == 4) {
        /*get mediaInfo */
        if (iValueObj.mediaInfo.resourceId) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }

        /*get Image Preview */
        var dataResourceImage = iValueObj.action.preview;
        var dataImageFromResource = [];

        for (var nIndex = 0; nIndex < dataResourceImage.length; nIndex++) {
            dataImageFromResource.push(getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceName=" + removeExt(dataResourceImage[nIndex]));
        }

        pageObject['imagePreview'] = dataImageFromResource;

    } else if (iValueObj.action.actionType == 5) {
        /*get mediaInfo */
        if (iValueObj.mediaInfo.resourceId) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }

        /*get Image Preview */
        if (iValueObj.action.jumpPage) {
            pageObject['jumpPage'] = iValueObj.action.jumpPage;
        } else {
            pageObject['jumpPage'] = '';
        }

    }
    else if (iValueObj.action.actionType == 6) {
        /*get mediaInfo */
        if (iValueObj.mediaInfo.resourceId) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }

        /*get emailSubject */
        if (iValueObj.action.emailSubject) {
            pageObject['emailSubject'] = iValueObj.action.emailSubject;
        } else {
            pageObject['emailSubject'] = '';
        }

        /*get emailAddress */
        if (iValueObj.action.emailAddress) {
            pageObject['emailAddress'] = iValueObj.action.emailAddress;
        } else {
            pageObject['emailAddress'] = '';
        }

    }
    else if (iValueObj.action.actionType == 8) {
        /*get mediaInfo */
        if (iValueObj.mediaInfo.resourceId) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }

        /*get content */
        pageObject['content'] = iValueObj.action.content;
    }
    else if (iValueObj.action.actionType == 10) {
        /*get mediaInfo */
        if (iValueObj.mediaInfo.resourceId) {
            /* get image from Json */
            pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        } else {
            pageObject['imageUrl'] = null;
        }

        /*get contentId */
        pageObject['contentId'] = iValueObj.action.contentId;

        /*get pageNo */
        pageObject['pageNo'] = iValueObj.action.pageNo;

    }
    return pageObject;
};

function getMediaType2(iValueObj) {
    var pageObject = [];

    pageObject['mediaType'] = iValueObj.mediaType;

    /*get actionType*/
    if (iValueObj.action.actionType) {
        pageObject['actionType'] = iValueObj.action.actionType;
    } else {
        pageObject['actionType'] = '';
    }

    pageObject['id'] = "media" + iValueObj.mediaInfo.resourceId;

    /*get mediaInfo */
    if (iValueObj.mediaInfo.resourceId) {
        pageObject['mediaFile'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        pageObject['media'] = iValueObj.mediaInfo.resourceId;
    } else {
        pageObject['mediaFile'] = '';
        pageObject['media'] = '';
    }

    /*get mediaInfo */
    if (iValueObj.action.embed) {
        pageObject['embed'] = iValueObj.action.embed;
    } else {
        pageObject['embed'] = '';
    }

    pageObject['imageUrl'] = 'img/iPad_video.png';

    /*get location */
    pageObject['x'] = iValueObj.location.x;
    pageObject['y'] = iValueObj.location.y;
    pageObject['width'] = iValueObj.location.width;
    pageObject['height'] = iValueObj.location.height;
    pageObject['visible'] = true;

    return pageObject;
};

function getMediaType3(iValueObj) {
    var pageObject = [];

    pageObject['mediaType'] = iValueObj.mediaType;

    /*get actionType*/
    if (iValueObj.action.actionType) {
        pageObject['actionType'] = iValueObj.action.actionType;
    } else {
        pageObject['actionType'] = '';
    }

    pageObject['id'] = "audio" + iValueObj.mediaInfo.resourceId;

    /*get mediaInfo */
    if (iValueObj.mediaInfo.resourceId) {
        if (avwUserEnvObj.browser == 'msie') {
            pageObject['audioFile'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId + "&isIE=true";
        } else {
            pageObject['audioFile'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
        }
    } else {
        pageObject['audioFile'] = '';
    }

    /*get playtype */
    pageObject['playType'] = iValueObj.action.playType;

    pageObject['imageUrl'] = 'img/iPad_music.png';

    /*get location */
    pageObject['x'] = iValueObj.location.x;
    pageObject['y'] = iValueObj.location.y;
    pageObject['width'] = iValueObj.location.width;
    pageObject['height'] = iValueObj.location.height;
    pageObject['visible'] = true;

    return pageObject;
};

function getMediaType4(iValueObj) {
    var pageObject = [];

    pageObject['mediaType'] = iValueObj.mediaType;

    pageObject['id'] = iValueObj.mediaInfo.id;

    /*get image List info */
    var imageObjects = iValueObj.mediaInfo.media;

    for (var nIndex = 0; nIndex < imageObjects.length; nIndex++) {
        /* get image from Json */
        imageObjects[nIndex].fileName = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + imageObjects[nIndex].resourceId;
    }

    pageObject['dataObjects'] = imageObjects;

    if (iValueObj.mediaInfo.triggerType) {
        pageObject['triggerType'] = iValueObj.mediaInfo.triggerType;
    } else {
        pageObject['triggerType'] = '';
    }

    /*get image url */
    if (imageObjects.length > 0) {
        pageObject['imageUrl'] = imageObjects[0].fileName;
    } else {
        pageObject['imageUrl'] = null;
    }


    /*get location */
    pageObject['x'] = iValueObj.location.x;
    pageObject['y'] = iValueObj.location.y;
    pageObject['width'] = iValueObj.location.width;
    pageObject['height'] = iValueObj.location.height;
    pageObject['visible'] = true;

    return pageObject;
};

function getMediaType5(iValueObj) {
    var pageObject = [];

    pageObject['mediaType'] = iValueObj.mediaType;

    pageObject['id'] = iValueObj.mediaInfo.id;

    /*get video List info */
    var videoObjects = iValueObj.mediaInfo.media;
    for (var nIndex = 0; nIndex < videoObjects.length; nIndex++) {
        /* get image from Json */
        videoObjects[nIndex].fileName = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + videoObjects[nIndex].resourceId;
    }

    pageObject['dataObjects'] = videoObjects;

    /*get image url */
    pageObject['imageUrl'] = '';

    /*get location */
    pageObject['x'] = iValueObj.location.x;
    pageObject['y'] = iValueObj.location.y;
    pageObject['width'] = iValueObj.location.width;
    pageObject['height'] = iValueObj.location.height;
    pageObject['visible'] = true;

    return pageObject;
};

function getMediaType6(iValueObj) {
    var pageObject = [];

    pageObject['mediaType'] = iValueObj.mediaType;

    /*get actionType*/
    if (iValueObj.action.actionType) {
        pageObject['actionType'] = iValueObj.action.actionType;
    } else {
        pageObject['actionType'] = '';
    }

    pageObject['id'] = "trigger" + iValueObj.mediaInfo.resourceId;

    /*get mediaInfo */
    if (iValueObj.mediaInfo) {
        /* get image from Json */
        pageObject['imageUrl'] = getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + iValueObj.mediaInfo.resourceId;
    } else {
        pageObject['imageUrl'] = null;
    }

    /*get index */
    if (iValueObj.action.index) {
        pageObject['index'] = iValueObj.action.index;
    } else {
        pageObject['index'] = '';
    }

    /*get target */
    if (iValueObj.action.target) {
        pageObject['target'] = iValueObj.action.target;
    } else {
        pageObject['target'] = '';
    }

    /*get location */
    pageObject['x'] = iValueObj.location.x;
    pageObject['y'] = iValueObj.location.y;
    pageObject['width'] = iValueObj.location.width;
    pageObject['height'] = iValueObj.location.height;
    pageObject['visible'] = true;

    return pageObject;
};

function getMediaType7(iValueObj) {
    var pageObject = [];

    pageObject['mediaType'] = iValueObj.mediaType;

    /*get actionType*/
    if (iValueObj.action.actionType) {
        pageObject['actionType'] = iValueObj.action.actionType;
    } else {
        pageObject['actionType'] = '';
    }

    pageObject['id'] = "testText";

    /*get mediaInfo */
    if (iValueObj.mediaInfo.content) {
        pageObject['content'] = iValueObj.mediaInfo.content;
    } else {
        pageObject['content'] = '';
    }

    if (iValueObj.action) {
        pageObject['action'] = "";
    }

    /*get location */
    pageObject['x'] = iValueObj.location.x;
    pageObject['y'] = iValueObj.location.y;
    pageObject['width'] = iValueObj.location.width;
    pageObject['height'] = iValueObj.location.height;
    pageObject['visible'] = true;

    return pageObject;
};

function getMediaType8(iValueObj) {
    var pageObject = [];



    return pageObject;
};

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

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

    if (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);
    }

};

/* get page index */
function getPageIndex() {
    var content = getContent();
    return eval(content.pageIndex);
};

/* init Image memo */
function initImageMemo() {
    if (ClientData.IsDisplayMemo() == true) {
        //change class
        $('#imgmemo').removeClass();
        $('#imgmemo').addClass('memoDisplay_hover');

    } else {
        //change class
        $('#imgmemo').removeClass();
        $('#imgmemo').addClass('memoDisplay');
    }
};

/* init Image add memo */
function initImageAddMemo() {
    if (ClientData.IsAddingMemo() == true) {
        //change class
        $('#imgaddmemo').removeClass();
        $('#imgaddmemo').addClass('memoAdd_hover');

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

    }
};

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

    if (ClientData.IsDisplayMemo() == true) {
        ClientData.IsDisplayMemo(false);
        isCopyMemo = false;
        drawCanvas();

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

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

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

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

        drawMemoOnScreen();

        //change class
        $('#imgmemo').removeClass();
        $('#imgmemo').addClass('memoDisplay_hover');

    }
};

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

        /* draw memo */
        drawMemoOnScreen();

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

    } else {

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

        /* draw memo */
        drawMemoOnScreen();

        //change class
        $('#imgmemo').removeClass();
        $('#imgmemo').addClass('memoDisplay_hover');

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

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

/*check display marking?? */
function initDisplayMarking() {
    if (ClientData.IsDisplayMarking() == true) {
        // change class
        $('#imgmarking').removeClass();
        $('#imgmarking').addClass('marking_hover');

        if (ClientData.IsAddingMarking() == true) {
            if (ClientData.IsHideToolbar() == false) {
                ShowMarking();
            }

            disableAllControl();
        } else {
            //change image				
            $('#imgmarkingtoolbar').removeClass();
            $('#imgmarkingtoolbar').addClass('markingToolbar');

        }
    } else {
        $("#dlgMarking").hide();

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

        $('#draw_canvas').css('display', 'none');

        //change image				
        $('#imgmarkingtoolbar').removeClass();
        $('#imgmarkingtoolbar').addClass('markingToolbar');

    }
};

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

/* Marking toolbar*/
function imgmarking_click() {
    if (ClientData.IsDisplayMarking() == false) {
        ClientData.IsDisplayMarking(true);
        drawCanvas();

        $("#dlgMarking").hide();

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

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

        drawCanvas();

    }

};

/* get data marking from local storage */
function getDataClientStorage() {
    /*set default size and color */
    if (!ClientData.penOpt_size()) {
        ClientData.penOpt_size(5);
    }

    if (!ClientData.penOpt_color()) {
        ClientData.penOpt_color("fe0000");
    }

    if (!ClientData.maker_size()) {
        ClientData.maker_size(5);
    }

    if (!ClientData.maker_color()) {
        ClientData.maker_color("f8ff00");
    }

    if (!ClientData.erase_size()) {
        ClientData.erase_size(5);
    }

    isAddingMarking = ClientData.IsAddingMarking();
    penSize = ClientData.penOpt_size();
    penColor = ClientData.penOpt_color();
    makerSize = ClientData.maker_size();
    makerColor = ClientData.maker_color();
    eraseSize = ClientData.erase_size();
    markingType = ClientData.MarkingType();
};

/* 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 */
        /*var w = $("#wrapper").width();
        var h = $("#wrapper").height();*/
        handleDisplayToolbar();

        /* invisible button fullscreen */
        $('#footer_toolbar_2').hide();

        /* draw again */
        drawCanvas();



        displayCanvasDraw();
        disableAllControl();

        // change class
        /*$('#imgmarking').removeClass();
        $('#imgmarking').addClass('marking_hover');
        $('#imgmarkingtoolbar').removeClass();
        $('#imgmarkingtoolbar').addClass('markingToolbar_hover');*/

    }

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

};

/*disable all control on page */
function disableAllControl() {
    /* 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');
    $("#zoomfit").css('cursor', 'default');
    $("#zoomin").css('cursor', 'default');
    $("#zoomout").css('cursor', 'default');
    $("#control_screen").css('cursor', 'default');
    $("#control_screen_2").css('cursor', 'default');
    $("#slider_page").css('cursor', 'default');
    $(".ui-slider-handle").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');

    $('#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');

    $('#zoomfit').unbind('click');
    $('#zoomfit').removeClass();
    $('#zoomfit').addClass('fit_off');
    $('#zoomin').unbind('click');
    $('#zoomin').removeClass();
    $('#zoomin').addClass('expansion_off');
    $('#zoomout').unbind('click');
    $('#zoomout').removeClass();
    $('#zoomout').addClass('reduction_off');
    if (avwUserEnvObj.os != "android") {
        $("#slider_page").slider("option", "disabled", true);
    }

    disable('#txtSearch', '#txtSlider');

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

};

/*enable all control on page */
function enableAllControl() {
    disableAllControl();

    /* 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');
    $("#zoomfit").css('cursor', 'pointer');
    // $("#zoomin").css('cursor', 'pointer');
    // $("#zoomout").css('cursor', 'pointer');
    $("#control_screen").css('cursor', 'pointer');
    $("#control_screen_2").css('cursor', 'pointer');
    $("#slider_page").css('cursor', 'pointer');
    $(".ui-slider-handle").css('cursor', 'pointer');
    $("#liAddMemo").css('cursor', 'pointer');
    $("#liCopyMemo").css('cursor', 'pointer');
    $("#liDeleteMemo").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();


    $('#listindex').bind('click', showListPageIndex);
    $('#listindex').removeClass();

    $('#copytext').bind('click', showCopyText);
    $('#copytext').removeClass();


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

    checkDisableButtonZoom();
    $("#slider_page").slider("option", "disabled", false);
    enable('#txtSearch', '#txtSlider');

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

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

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

        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();
};

/* 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());
        enBookmark.contentTitle = dataWebContentPage.contentTitle;
        enBookmark.contentTitleKana = dataWebContentPage.contentTitleKana;
        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 (isTouchDevice() == true) {
            $('#imgbookmark').addClass('bmAdd_device');
        } else {
            $('#imgbookmark').addClass('bmAdd');
        }

    }
};

/* function changePage Index->pageno */
function changePageIndex(page_index) {
    return dataWebContentPage.pages[page_index].pageNo;
};

/* function change PageNo -> pageIndex */
function changePageNo(page_no) {
    var dataContent = dataWebContentPage.pages;
    for (var nIndex = 0; nIndex < dataContent.length; nIndex++) {
        if (dataContent[nIndex].pageNo == page_no) {
            return nIndex;
        }
    }
    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 list bookmark of content */
function getBookMarkListByContentID() {
    var bmList = [];
    var bmListResult = [];
    bmList = ClientData.BookMarkData();

    for (var nIndex = 0; nIndex < bmList.length; nIndex++) {
        if (bmList[nIndex].contentid == contentID) {
            bmListResult.push(bmList[nIndex]);
        }
    }

    return bmListResult;
};

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

    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">' +
		    					i18nText('txtPage') + (changePageNo(bmList[nIndex].pageNo) + 1) + '<br /> ' +
		    					truncate(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">' +
		    					i18nText('txtPage') + (changePageNo(bmList[nIndex].pageNo) + 1) + '<br /> ' +
		    					truncate(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";

                /*avwCmsApiSync(ClientData.userInfo_accountPath(),
                "webContentPage",
                "GET",
                {sid:ClientData.userInfo_sid(),contentId: contentID,pageNos: bmList[nIndex].pageNo, thumbnailFlg:1},
                function(data){					     		     	
                getDataLoaded(data.pages);
				     	
                //Resize Image
                var imgTemp = new Image();
                $('#img_bookmark_' +data.pages[0].pageNo).attr('src',formatStringBase64(data.pages[0].pageThumbnail));
					    
                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(data.pages[0].pageThumbnail);        
                },
                null); 	*/
                lstPageNoBookMark.push(bmList[nIndex].pageNo);
            }


        } else { /* page deleted */
            $('#divListBookmark').append(
	    			'	<li id="' + changePageNo(bmList[nIndex].pageNo) + '">' +
		    		'		<span class="mdltext">' +

		    		'			<span>' + i18nText('txtPage') + bmList[nIndex].pageNo + '</span> <br /> ' +
		    		'		</span>' +
		    		'	</li>' +
		    		'	<li>' +
		    		'		<span class="mdltext">' +
		    		'			<span style="color:red">' + i18nText('msgShioriDeleted') + '</span>' +
		    		'		</span>' +
		    		'	</li>'
	    		);
        }
    }
    if (lstPageNoBookMark.length > 0) {
        isSendingData = true;
        loadDataBookmark(lstPageNoBookMark);
    }
};

function loadDataBookmark(lstPageNo) {
    if (isSendingData == true) {

        avwCmsApi(ClientData.userInfo_accountPath(),
		     "webContentPage",
		     "GET",
		     { sid: ClientData.userInfo_sid(), contentId: contentID, pageNos: lstPageNo[0], thumbnailFlg: 1 },
		     function (data) {
		         getDataLoaded(data.pages);

		         //Resize Image
		         var imgTemp = new Image();
		         $('#img_bookmark_' + data.pages[0].pageNo).attr('src', formatStringBase64(data.pages[0].pageThumbnail));

		         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(data.pages[0].pageThumbnail);

		         lstPageNo = jQuery.grep(lstPageNo, function (value) {
		             return value != lstPageNo[0];
		         });

		         if (lstPageNo.length > 0) {
		             loadDataBookmark(lstPageNo);
		         } else {
		             isSendingData = false;
		         }
		     },
		     null);
    }
};

/* 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;
};

/* get data load*/
function getDataLoaded(data) {
    var isExist = false;

    for (var i = 0; i < data.length; i++) {
        isExist = false;
        for (var n = 0; n < arrThumbnailsLoaded.length; n++) {
            if (data[i].pageNo == arrThumbnailsLoaded[n].pageNo) {
                isExist = true;
                break;
            }
        }

        /* insert if not exist */
        if (isExist == false) {
            arrThumbnailsLoaded.push(data[i]);
        }
    }

    /* sort data */
    arrThumbnailsLoaded.sort(function (a, b) {
        var a1 = a.pageNo, b1 = b.pageNo;
        if (a1 == b1) return 0;
        return a1 > b1 ? 1 : -1;
    });

};

/* event for list bookmark: changePageNo */
function clickBookmark() {
    changePage($(this).attr('id'));

    /* close popup */
    // $('#divListBookmark').dialog("close");
    $("#overlay").hide();

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

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

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

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

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

};

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

/* get list info bookmark */
function getBookmarklist(pos) {
    var isExistBookMarkInContent = false;
    sortBookmarkList();
    var bmList = [];
    bmList = ClientData.BookMarkData();

    for (var nIndex = 0; nIndex < bmList.length; nIndex++) {
        if (bmList[nIndex].contentid == contentID) {
            isExistBookMarkInContent = true;
            break;
        }
    }

    if (isExistBookMarkInContent == false) {
        $('#divListBookmark').children().remove();
        $('#divListBookmark').append('<span class="last">' + i18nText('msgShioriNotExists') + '</span>');

        // $("#divListBookmark").dialog({ 		 		
        // show: "blind",
        // modal: true,
        // resizable:false,
        // width: WIDTH_DIALOG_BOOKMARK,
        // height: HEIGHT_DIALOG_BOOKMARK_NO_BOOKMARK,
        // title: i18nText('txtShioriCtnLs'),
        // position: pos});

        //title start
        $('#bookmarkBoxHdBM').children().remove();
        $('#bookmarkBoxHdBM').html('<a id="bookmarkClosing" class="delete" > </a>');
        $("#bookmarkClosing").click(closeBookmarkBox);
        $('#bookmarkBoxHdBM').append(i18nText('txtShioriCtnLs'));
        //title end
        //lockLayout();
        $('#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()) });
    }
    else {
        //display dialog	
        // $("#divListBookmark").dialog({ 		 		
        // show: "blind",
        // modal: true,
        // width: WIDTH_DIALOG_BOOKMARK,
        // height:HEIGHT_DIALOG_BOOKMARK,
        // resizable:false,
        // title: i18nText('txtShioriCtnLs'),
        // position: pos});					    

        handleAPIWebContentPage(dataWebContentPage, pos)
    }
};

/* init Image bookmark */
function initImageBookmark() {
    if (isExistBookmark() == -1) {
        //change class
        $('#imgbookmark').removeClass();
        $('#imgbookmark').addClass('bmAdd_off');

    } else {
        //change class
        $('#imgbookmark').removeClass();
        $('#imgbookmark').addClass('bmAdd');
    }
};

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

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

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

    getBookmarklist(array);
};

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

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

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

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

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

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


/* get list info bookmark */
function getPageIndexJson(pos) {
    if (dataJsonType5.length > 0) {
        $('#divListIndex').children().remove();

        // $("#divListIndex").dialog({ 		 		
        // show: "blind",
        // modal: true,
        // width: WIDTH_DIALOG_INDEX,
        // height:HEIGHT_DIALOG_INDEX,
        // resizable:false,
        // closeOnEscape: false,
        // title: i18nText('txtIndex'),
        // position: pos});

        //title start
        $('#indexBoxHdIndex').children().remove();
        $('#indexBoxHdIndex').html('<a id="indexClosing" class="delete" > </a>');
        $("#indexClosing").click(closeIndexBox);
        $('#indexBoxHdIndex').append(i18nText('txtIndex'));
        //title end
        //lockLayout();
        $('#boxIndex').css('z-index', '101');
        $('#boxIndex').css('display', 'block');
        $('#boxIndex').draggable({ handle: "h1" });
        $("#boxIndex").offset({ left: pos[0], top: pos[1] });
        $("#divListIndex").show();
        $("#divListIndex").offset({ left: pos[0], top: (pos[1] + $('#indexBoxHdIndex').height()) });

        //set data for dialog index			        		        
        var dataContent = dataJsonType5;
        var arrData = new Array();
        $.each(dataContent, function (i, value) {
            if (dataContent[i].level == 0) {
                //add parent node
                var node = new TreeNode();
                node.IsCategory = true;
                //node.Text = htmlEncode(truncateByBytes(dataContent[i].title, 30));
                /* check data text */
                if (getBytes(dataContent[i].title) > 30) {
                    node.Text = htmlEncode(truncateByBytes(dataContent[i].title, 30)) + '...';
                } else {
                    node.Text = htmlEncode(dataContent[i].title);
                }
                node.id = dataContent[i].ID;
                node.Value = dataContent[i].destPageNumber;
                AddChidrenNode(node, dataContent);

                arrData.push(node);
            }
        });

        var tree = new TreeViewIndex();
        tree.IsShowTotal = false;
        tree.Show("divListIndex", arrData, "listIndex_Callback");
        $("#divListIndex").treeview();
        $(".treeview, .treeview ul").css('padding', '0px 8px 0');
    } else {
        $('#divListIndex').children().remove();
        $('#divListIndex').append('<span style="color:#333333; font-size:12px; cursor:default; text-decoration:none;">' + i18nText('msgNoIndex') + '</span>');

        // //show dialog index
        // $("#divListIndex").dialog({ 		 		
        // show: "blind",
        // modal: true,
        // resizable:false,
        // width: WIDTH_DIALOG_INDEX,
        // height:HEIGHT_DIALOG_INDEX_NO_INDEX,
        // title: i18nText('txtIndex'),
        // position: pos});

        //title start
        $('#indexBoxHdIndex').children().remove();
        $('#indexBoxHdIndex').html('<a id="indexClosing" class="delete" > </a>');
        $("#indexClosing").click(closeIndexBox);
        $('#indexBoxHdIndex').append(i18nText('txtIndex'));
        //title end
        //lockLayout();
        $('#boxIndex').css('z-index', '101');
        $('#boxIndex').css('display', 'block');
        $('#boxIndex').draggable({ handle: "h1" });
        $("#boxIndex").offset({ left: pos[0], top: pos[1] });
        $("#divListIndex").show();
        $("#divListIndex").offset({ left: pos[0], top: (pos[1] + $('#indexBoxHdIndex').height()) });

    }
};

/* 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 = htmlEncode(truncateByBytes(dataChild[i].title,30));
        /* check data text */
        if (getBytes(dataChild[i].title) > 30) {
            item.Text = htmlEncode(truncateByBytes(dataChild[i].title, 30)) + '...';
        } else {
            item.Text = 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);

    });
};

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

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

    changePage(node.Value - 1);
};

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

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

function getText() {
    /* init var page text */
    var data = dataWebContentPage.pages;
    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 = htmlEncode(data[nIndex].pageText);
            break;
        }
    }
    if (sPageText == '') {
        return { text: i18nText('txtNoTextCopy'), title: i18nText('txtTextCopy') + ' | ' + i18nText('sysAppTitle') };
    }
    else {
        var strPattern = "\n";
        var strTemp = sPageText;
        strTemp = strTemp.replaceAll(strPattern, "<br/>");
        strTemp += "<br/>";
        return { text: strTemp, title: i18nText('txtTextCopy') + ' | ' + i18nText('sysAppTitle') };
    }
};

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

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

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

/* 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 = htmlEncode(data[nIndex].pageText);
            break;
        }
    }

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

        // $("#divCopyText").dialog({ 		 		
        // show: "blind",
        // modal: true,
        // resizable:false,
        // width: WIDTH_DIALOG_COPYTEXT,
        // height: HEIGHT_DIALOG_COPYTEXT_NO_COPYTEXT,
        // title: 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(i18nText('txtTextCopy'));
        //title end

        //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: 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(i18nText('txtTextCopy'));

        //title end

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

};

/* get data using for search */
function getSearchDataFromJson() {
    //get data from JSON file

    var arrPageNo = '';
    for (var nIndex = 0; nIndex < totalPage; nIndex++) {
        if (nIndex == 0) {
            arrPageNo += (nIndex + 1);
        } else {
            arrPageNo += "," + (nIndex + 1);
        }
    }
    avwCmsApi(ClientData.userInfo_accountPath(),
     "webContentPage",
     "GET",
     { sid: ClientData.userInfo_sid(), contentId: contentID, thumbnailFlg: 0 },
     function (data) {
         contentName = data.contentTitle;
         dataWebContentPage = data;

     },
     null);

};

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

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

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

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


/*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(i18nText('txtSearchResult'));
            //title end

            //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">' +
			    					i18nText('txtPage') + (changePageNo(sPageNo[i].pageNo) + 1) + '<br /> ' +
			    					htmlEncode(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">' +
			    					i18nText('txtPage') + (changePageNo(sPageNo[i].pageNo) + 1) + '<br /> ' +
			    					htmlEncode(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);

                    /*avwCmsApi(ClientData.userInfo_accountPath(),
                    "webContentPage",
                    "GET",
                    {sid:ClientData.userInfo_sid(),contentId: contentID,pageNos: sPageNo[i].pageNo, thumbnailFlg:1},
                    function(data){					     		     	
                    getDataLoaded(data.pages);
				     	
                    //Resize Image
                    var imgTemp = new Image();
                    $('#img_search_' +data.pages[0].pageNo).attr('src',formatStringBase64(data.pages[0].pageThumbnail));
					    
                    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(data.pages[0].pageThumbnail);        
                    },
                    null); 
                    */

                }
            }

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

            // $("#divSearchResult").dialog({ 		 		
            // show: "blind",
            // modal: true,
            // resizable:false,
            // width: WIDTH_DIALOG_SEARCH,
            // height: HEIGHT_DIALOG_SEARCH_NO_SEARCH,
            // title: i18nText('txtSearchResult'),
            // position: pos});


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

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

function loadDataSearch(lstPageNo) {
    if (isSendingData == true) {
        avwCmsApi(ClientData.userInfo_accountPath(),
		     "webContentPage",
		     "GET",
		     { sid: ClientData.userInfo_sid(), contentId: contentID, pageNos: lstPageNo[0], thumbnailFlg: 1 },
		     function (data) {
		         getDataLoaded(data.pages);

		         //Resize Image
		         var imgTemp = new Image();
		         $('#img_search_' + data.pages[0].pageNo).attr('src', formatStringBase64(data.pages[0].pageThumbnail));

		         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(data.pages[0].pageThumbnail);

		         lstPageNo = jQuery.grep(lstPageNo, function (value) {
		             return value != lstPageNo[0];
		         });

		         if (lstPageNo.length > 0) {
		             loadDataSearch(lstPageNo);
		         } else {
		             isSendingData = false;
		         }
		     },
		     null);
    }
};

/* 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">' +
		    					i18nText('txtPage') + (changePageNo(searchResult[nIndex].pageNo) + 1) + '<br /> ' +
		    					htmlEncode(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);
    }
};

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

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();
            }
        }
    }
};

/* event next page */
function nextPage_click() {
    if (getContent().hasNextPage()) {
        playBGMOfContent();
        playBGMOfPage(getPageIndex() + 1);

        disableAllControl();

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

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

        avwGrabContentPageImage(ClientData.userInfo_accountPath(),
		     { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: getPageIndex() + 2 },
		     function (data) {
		         pageImages = data;

		         /* get page Objects */
		         getPageObjectsByPageIndex(pageObjectsData, (getPageIndex() + 1));
		         getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);

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

		         var tran = new Transition();
		         tran.flipNextPage();

		     },
		     function (xmlHttpRequest, txtStatus, errorThrown) {
		         showErrorScreen();
		     });
    }
};

/* display error screen*/
function showErrorScreen() {
    // エラーメッセージの表示
    var errMes = i18nText('msgPageImgErr');
    /*var tags = '<div id="avw-sys-error" style="text-align:center; vertical-align:middle;">' +errMes+ '</div>';
    $('body').prepend(tags);
    $('#avw-sys-error').css( {
    'opacity': 0.7,
    'position': 'fixed',
    'top': '0',
    'left': '0',
    'width': $(window).width(),
    'height': $(window).height(),
    'background': '#999',
    'z-index': 100
    })
    // resize error page 
    $(window).resize(function() {
    $('#avw-sys-error').css( {
    'width': $(window).width(),
    'height': $(window).height()
    });   
    });*/
    $('#divImageLoading').css('display', 'none');
    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);
};

/* event prev page */
function prevPage_click() {
    if (getContent().hasPreviousPage()) {
        playBGMOfContent();
        playBGMOfPage(getPageIndex() - 1);

        disableAllControl();

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

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

        //pageImages = getURLPageImage("webContentPageImage") + "?contentId=" + contentID + "&sid=" + ClientData.userInfo_sid() + "&pageNo=" + (getPageIndex() - 1);
        avwGrabContentPageImage(ClientData.userInfo_accountPath(),
		     { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: getPageIndex() },
		     function (data) {
		         pageImages = data;

		         /* get page Objects */
		         getPageObjectsByPageIndex(pageObjectsData, (getPageIndex() - 1));
		         getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);

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

		         var tran = new Transition();
		         tran.flipPreviousPage();

		     },
		     function (xmlHttpRequest, txtStatus, errorThrown) {
		         showErrorScreen();
		     });
    }
};

/* event first page */
function firstPage_click() {
    if (getContent().pageIndex != 0) {
        playBGMOfContent();
        playBGMOfPage(0);

        disableAllControl();

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

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

        avwGrabContentPageImage(ClientData.userInfo_accountPath(),
		     { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: 1 },
		     function (data) {
		         pageImages = data;

		         /* get page Objects */
		         getPageObjectsByPageIndex(pageObjectsData, 0);
		         getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);

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

		         var tran = new Transition();
		         tran.flipToPage(0);

		     },
		     function (xmlHttpRequest, txtStatus, errorThrown) {
		         showErrorScreen();
		     });
    }
};

/* event last page */
function lastPage_click() {
    if (getContent().pageIndex != (totalPage - 1)) {
        playBGMOfContent();
        playBGMOfPage(totalPage - 1);

        disableAllControl();

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

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

        //pageImages = getURLPageImage("webContentPageImage") + "?contentId=" + contentID + "&sid=" + ClientData.userInfo_sid() + "&pageNo=" + (totalPage - 1);
        avwGrabContentPageImage(ClientData.userInfo_accountPath(),
		     { contentId: contentID, sid: ClientData.userInfo_sid(), pageNo: totalPage },
		     function (data) {
		         pageImages = data;

		         /* get page Objects */
		         getPageObjectsByPageIndex(pageObjectsData, totalPage - 1);
		         getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects);

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

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

		         var tran = new Transition();
		         tran.flipToPage(totalPage - 1);

		     },
		     function (xmlHttpRequest, txtStatus, errorThrown) {
		         showErrorScreen();
		     });
    }

};

/* move to page ?? */
function 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');

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

        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();
		     });

    } else if (ClientData.IsJumpBack() == true
	   || ClientData.common_prePageNo()) {
        getContent().setPageImages(totalPage, pageImages)
					 				.setPageObjects(pageObjects)
					 				.setUpPage(0);
    }
};

/* add event draw on canvas */
function drawOnCanvas() {
    tool = new tool_drawing();
    if (isTouchDevice() == true) {
        initializeCanvas(document.getElementById('draw_canvas'));

        initializeCanvas(document.getElementById('marker_canvas'));
    }
    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) {
        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() {
    /* handle play BGM of content jump */
    // 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);
    // }
    // }
    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() {
    /* handle play BGM of content jump */
    // 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);
    // }
    // }

    isJumpNotFromFirstPage = true;

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

/* handle button back */
function oldContent_Back() {
    /* handle play BGM of content jump */
    // 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);
    // }
    // }						
    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();
            $('#header_toolbar').show();
            sizingNotFull(w, h);
            drawCanvas();

        } else {
            isFullScreen = true;

            $('#header_toolbar').hide();
            $('#footer_toolbar_2').show();
            $('#footer_toolbar_1').hide();
            sizingFullSize(w, h);
            drawCanvas();

        }
        /* 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 ($('#txtSlider').val() <= 0) {
                $('#txtSlider').val('1');
            } else if ($('#txtSlider').val() > totalPage) {
                $('#txtSlider').val(totalPage);
            } else if (/\D/g.test($('#txtSlider').val())) {
                $('#txtSlider').val('1');
            }

            if ($('#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', i18nText('dspHome'));
    $('#imgBack').attr('title', i18nText('txtTooltipBack'));
    $('#listbookmark').attr('title', i18nText('txtShioriCtnLs'));
    $('#imgbookmark').attr('title', i18nText('txtTooltipBookmark'));
    $('#listindex').attr('title', i18nText('txtIndex'));
    $('#copytext').attr('title', i18nText('txtTextCopy'));
    $('#imgmemo').attr('title', i18nText('txtTooltipShowMemo'));
    $('#imgaddmemo').attr('title', i18nText('txtTooltipAddMemo'));
    $('#imgmarking').attr('title', i18nText('txtTooltipShowMarking'));
    $('#imgmarkingtoolbar').attr('title', i18nText('txtTooltipShowMarkingTool'));		*/
};

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


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

                /* zoom */ 
                case ShortKeys.ZoomIn: /* zoomIn */
                    zoomIn();
                    break;
                case ShortKeys.ZoomOut: /* zoomOut */
                    zoomOut();
                    break;
                case ShortKeys.ZoomFit: /* screenFit*/
                    screenFit();
                    break;

                /* marking && toolbar */ 
                case ShortKeys.ShowHideToolbar: /* handle toolbar */
                    handleDisplayToolbar();
                    break;
                case ShortKeys.ShowHideMarking: /* hide marking */
                    imgmarking_click();
                    break;
            }
        }
    }
});

/* handle keydown */
$(document).keyup(function (e) {
    ctrlMode = false;
});

/*$(document).mousemove(function(e){
if(e.which == 1 && !isPressLeftMouse){
e.which = 0;		 	
}
})*/

/* get contentID */
function getContentID() {
    /* init contentID */
    if (ClientData.common_preContentId()) {
        contentID = ClientData.common_preContentId();
        ClientData.common_preContentId(null);
    } else if (ClientData.IsJumpBack() == true) {
        var dataJump = ClientData.JumpQueue();
        contentID = dataJump[dataJump.length - 1].oldContentID;
    } else {
        contentID = ClientData.contentInfo_contentId();
    }
};

/* init flag marking, memo when init page */
function initFlagDisplay() {
    ClientData.IsDisplayMemo(false);
    ClientData.IsAddingMemo(false);
    if (ClientData.userOpt_makingDsp() == "1") {
        ClientData.IsDisplayMarking(true);
    } else {
        ClientData.IsDisplayMarking(false);
    }
    ClientData.IsAddingMarking(false);
};

function onUnlock() {
    removeObject();
    getPageObjectsByPageIndex(pageObjectsData, 0);
    /* handle play BGM of content jump */
    for (var nIndex = 0; nIndex < pageObjects.length; nIndex++) {
        if (pageObjects[nIndex].mediaType == '3' && pageObjects[nIndex].playType == '1') {
            if (avwUserEnvObj.os == "ipad") {
                $('#play_audio_1').attr('src', pageObjects[nIndex].audioFile);
                //document.getElementById("play_audio_1").load();           
                document.getElementById("play_audio_1").play();
                isPlayBGMUnlock = true;
            } else {
                createAudio(pageObjects[nIndex].audioFile, pageObjects[nIndex].playType);
            }
        }
    }


    getPageObjectsByPageIndex(pageObjectsData, getPageIndex());
    getContent().setPageImages(totalPage, pageImages).setPageObjects(pageObjects).setUpPage(getPageIndex);

};

function StartTimerUpdateLog() {
    /* set end log */
    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');
    }
};

/* set size bot toolbar for ipad */
function initDisplayToolbarDevice() {
    if (avwUserEnvObj.os == "ipad" || avwUserEnvObj.os == "android") {
        $('.transition').css('padding', '4px 0 0 0');
        $('.sizing').css('padding', '4px 0 0 2px');
        $('.toolbar').css('margin', '0 0 0 0');
    }
};

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 (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;

    }
};

function changePageWithoutSlide(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);
            }
        }
    }

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

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

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

	         //changeSlider(pageMove);
	         /* handle slider bar */
	         handleSliderBar();

	         if (dataPageTitle[pageMove]) {
	             if (dataPageTitle[pageMove] != '') {
	                 document.title = contentName + '_' + dataPageTitle[pageMove] + ' | ' + i18nText('sysAppTitle');
	             } else {
	                 document.title = contentName + ' | ' + i18nText('sysAppTitle');
	             }
	         } else {
	             document.title = contentName + ' | ' + i18nText('sysAppTitle');
	         }

	     },
	     function (xmlHttpRequest, txtStatus, errorThrown) {
	         showErrorScreen();
	     });
};

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

function createTextConfirmAudio() {
    var text = i18nText('msgBGMPlayConfirm');
    $('#txtAudio').html(text);

    var text = i18nText('msgBGMPagePlayConfirm');
    $('#txtAudio_page').html(text);
};

function initPage() {
    //$('body,html').animate({ scrollTop: 0 }, 350);

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

    /* init footer toolbar */
    $('#footer_toolbar_2').hide();
    $('#footer_toolbar_1').show();

    /* init pos bottom toolbar*/
    initDisplayToolbarDevice();

    /* check login */
    if (!avwCheckLogin(ScreenIds.Login)) return;
    // Set event to prevent leave
    ToogleLogoutNortice();

    // Lock screen
    LockScreen();

    getContentID();

    StartTimerUpdateLog();

    /* set start log */
    SetStartLog(contentID);

    /* get info of content */
    //getDataJsonFile();
    getJsonContentInfo();

    initializeViewerComponent('wrapper');

    /* handle display tooltip */
    handleTooltip();

    /* set text dialog confirm of audio */
    createTextConfirmAudio();

    /* handle toolbar */
    $('#control_screen').click(handleDisplayToolbar);
    $('#control_screen_2').click(handleDisplayToolbar);

    /* bookmark Page */
    $('#imgbookmark').click(bookmarkPage);
    $('#listbookmark').click(showListBookMark);
    $('#divListBookmark li').live('click', clickBookmark);

    /* close bookmark dialog */
    //$("#bookmarkClosing").live('click',closeBookmarkBox);

    /* page index */
    $('#listindex').click(showListPageIndex);
    $('#divSearchResult li').live('click', clickSearchDetail);

    /* copy text */
    $('#copytext').click(showCopyText);
    /* close copy text dialog */
    $("#copyTextClosing").click(closeCopyTextBox);

    /*event click next page button */
    $('#nextpage').click(nextPage_click);
    $('#button_next_canvas').click(nextPage_click);
    /*event click prev page button */
    $('#prevpage').click(prevPage_click);
    $('#button_pre_canvas').click(prevPage_click);
    /*event click fist page button */
    $('#firstpage').click(firstPage_click);
    /*event click last page button */
    $('#lastpage').click(lastPage_click);

    $("#imgBack").click(imgBack_click);
    $("#imgHome").click(imgHome_click);
    $("#btn_show_memo").click(showEditMemo);
    $("#btn_copy_memo").click(copyMemo);
    $('#memoClosing').click(closePopUpCopyMemo);
    $('#liAddMemo').click(click_liAddMemo);
    $('#liCopyMemo').click(click_liCopyMemo);
    $('#liDeleteMemo').click(click_liDeleteMemo);

    /*event search*/
    showListSearchResult();

    /* zoom event */
    $('#zoomin').click(zoomIn);
    $('#zoomout').click(zoomOut);
    $('#zoomfit').click(screenFit);

    /* event memo */
    $('#imgmemo').click(handleMemo);
    $('#imgaddmemo').click(handleAddMemo);

    /* event marking */
    $('#imgmarking').click(imgmarking_click);
    $('#imgmarkingtoolbar').click(handleDrawCanvas);

    /*draw canvas*/
    drawOnCanvas();

    /*init flag */
    initFlagDisplay();

    sizingScreen();

    /* move image check marking*/
    $('#divCheckExistMarking').css('top', '70px');
    $('#divCheckExistMarking').hide();

    /* disable controls */
    isLoadingObject = true;
    disableAllControl();

    /* window resize event */
    $(window).resize(function () {
        sizingScreen();
        /* close dialog popuptext */
        closeDialogResize();
    });

    $(document).ajaxComplete(function () {

        /*Init Page */
        nAjaxLoad++;
        if (nAjaxLoad == 7) {

            /* handle from bookmark page */
            //handleFromBookMarkPage();	
            /* check move content */
            if (ClientData.bookmark_pageNo()) {
                //changePage(changePageNo(ClientData.bookmark_pageNo()));
                //changePageWithoutSlide(changePageNo(ClientData.bookmark_pageNo()));
                //ClientData.bookmark_pageNo(null)
                handleFromBookMarkPage();

            } else if (ClientData.common_prePageNo()) {
                /* handle from jump content */
                handleFromJumpContent();
            } else if (ClientData.IsJumpBack() == true) {
                /* handle back */
                oldContent_Back();
            } else {
                if (getPageIndex() == 0) {
                    getContent().setPageImages(totalPage, pageImages)
					 				.setPageObjects(pageObjects)
					 				.setUpPage(0);

                    /* set pageTitle*/
                    if (dataPageTitle[0]) {
                        if (dataPageTitle[0] != '') {
                            document.title = contentName + '_' + dataPageTitle[0] + ' | ' + i18nText('sysAppTitle');
                        } else {
                            document.title = contentName + ' | ' + i18nText('sysAppTitle');
                        }
                    } else {
                        document.title = contentName + ' | ' + i18nText('sysAppTitle');
                    }

                    /* handle slider bar */
                    handleSliderBar();
                }
            }

            /* window resize event */
            $(window).resize(function () {

                if (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");
                        }
                    }
                }

                resizeScreen();
                isChangeSizeScreen = false;

                /* change position dialog */
                changePosDialog();

                /* close dialog popuptext */
                closeDialogResize();

                

            });

            /* check status button */
            checkExistNextPrePage();

            /*init Image Bookmark */
            initImageBookmark();

            $('#lblSlider').text('/ ' + totalPage);
            /* memo */
            initImageMemo();
            initImageAddMemo();

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

            /* check status */
            checkStatusImageMarking();

            trackTransforms(context_main);

            //nAjaxLoad = 0;	

            if (isTouchDevice() == true) {
                if (avwUserEnvObj.os == "android") {
                    standardRatio = document.documentElement.clientWidth / window.innerWidth;
                    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();
                }
            }
        }

    });
};

$("document").ready(function () {
    if (avwUserEnvObj.os == 'ipad') {
        if (ClientData.IsRefresh() == true) {
            initPage();
        } else {
            $('body, html').hide();
            ClientData.IsRefresh(true);
            location.reload();
        }
    }
    else {
        initPage();
    }

});

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


/* rect object */
var Rect = function (x, y, w, h) {
    this.left = Math.floor(x);
    this.top = Math.floor(y);
    this.right = Math.floor(x + w);
    this.bottom = Math.floor(y + h);
    this.width = w;
    this.height = h;
};
Rect.prototype.add = function (x, y) {
    this.left = Math.floor(this.left + x);
    this.right = Math.floor(this.right + x);
    this.top = Math.floor(this.top + y);
    this.bottom = Math.floor(this.bottom + y);
    this.width = this.right - this.left;
    this.height = this.bottom - this.top;
};
Rect.prototype.center = function () {
    var x = (this.left + this.right) / 2;
    var y = (this.top + this.bottom) / 2;
    return new Point(Math.floor(x), Math.floor(y));
};


/**
* 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 () {
        //alert(this.pageImageUrl + " hasn't loaded..");
    };
    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
								);
                } 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
								);
                } 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
								);
                } 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
								);
                } 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
								);
                } 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
								);
                } 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
								);
                } 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
								);
                } 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
								);
                }

                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
								);
                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.playType
								);
                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
								);
                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
								);
                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
									);
                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
									);
                break;
            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
						);
        }
        // add pageObject
        this.addPageObject(pageObj);
    }
};

/* drawing for current page */
ContentPage.prototype.drawPage = function (context) {
    /*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;

    /* 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;
        }
    }

    $("#offscreen").attr('height', heightEachPage);
    $("#offscreen").attr('width', widthEachPage);

    var objPageTemp = this.pageObjects;
    var img = new Image();
    img.onload = function () {
        context.drawImage(img, 0, 0, widthEachPage, heightEachPage);
        flip();

        /* draw linkList */
        drawGetWebContent4(context);

        if (objPageTemp.length > 0) {
            // draw object
            for (var i = 0; i < objPageTemp.length; i++) {
                if (objPageTemp[i].imageUrl != null) {
                    objPageTemp[i].drawPageObject(context);
                } else {
                    nCountObjectLoad++;

                    if (nCountObjectLoad == pageObjects.length) {
                        /* draw marking */
                        drawMarkingOnScreen();

                        /*set status is loading page */
                        isLoadingObject = false;
                        /* enable controls in page */
                        if (ClientData.IsAddingMarking() == true) {
                            disableAllControl();
                            enableButtonMarking()
                        } else {
                            enableAllControl();
                        }
                        /*finish loading */
                        $('#divImageLoading').css('display', 'none');

                        /* set pos video */
                        zoomVideo();
                    }
                }
            }
        } else {
            /* draw marking */
            drawMarkingOnScreen();

            /*set status is loading page */
            isLoadingObject = false;
            /* enable controls in page */
            if (ClientData.IsAddingMarking() == true) {
                disableAllControl();
                enableButtonMarking()
            } else {
                enableAllControl();
            }

            /*finish loading */
            $('#divImageLoading').css('display', 'none');

            /* set pos video */
            zoomVideo();
        }
    };
    img.src = this.image.src;
};

/* 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;
};


/**
* PageObject Class Definition 
*/

/* constructor */
var PageObject = function (id, imageUrl, x, y, w, h, visible, actionFunction, displayBorder) {
};

/* setup each properties */
PageObject.prototype.setup = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, actionFunction, displayBorder) {

    this.mediaType = mediaType;
    this.actionType = actionType;
    this.id = id;
    this.x = x;
    this.y = y;
    this.width = w;
    this.height = h;
    this.displayBorder = displayBorder;
    this.visible = visible;
    this.imageUrl = imageUrl;
    this.image = new Image();

    this.image.src = this.imageUrl;
};

/* prototype hitTest */
PageObject.prototype.hitTest = function (px, py) {
    if (this.x <= px && px <= (this.x + this.width)) {
        if (this.y <= py && py <= (this.y + this.height)) {
            return true;
        }
    }
    return false;
};
var check;
/* draw page Object */
PageObject.prototype.drawPageObject = function (context) {
    if (this.visible) {
        /* init data */
        var mediaType = this.mediaType;
        var displayBorder = this.displayBorder;
        var x = this.x;
        var y = this.y;
        var w = this.width;
        var h = this.height;

        if (mediaType == '5') {
            nCountObjectLoad++;
            context.strokeStyle = "black";
            context.lineWidth = "1";
            context.strokeRect(x, y, w, h);
        }

        if (this.imageUrl != '') {
            /* init image  */
            var img = new Image();

            img.onload = function () {
                nCountObjectLoad++;

                /* create object store value image */
                var objTemp = [];
                objTemp.mediaType = mediaType;
                objTemp.img = img;
                objTemp.x = x;
                objTemp.y = y;
                objTemp.w = w;
                objTemp.h = h;
                objTemp.displayBorder = displayBorder;

                /* push to array */
                arrImage.push(objTemp);

                if (mediaType == '2') {/*  media */
                    img.width = 50;
                    img.height = 50;

                    if (img.width > w) {
                        context.drawImage(img, x, y, w, h);
                    } else {
                        /*draw image and border */
                        context.drawImage(img, x + ((w - img.width) / 2), y + ((h - img.height) / 2), img.width, img.height);
                        if (displayBorder == '1') {/* draw border */
                            context.strokeStyle = "black";
                            context.lineWidth = "1";
                            context.strokeRect(x, y, w, h);
                        }
                    }

                } else if (mediaType == '3') {/* audio */
                    img.width = 50;
                    img.height = 50;
                    context.drawImage(img, x, y, img.width, img.height);
                } else {
                    context.drawImage(img, x, y, w, h);
                }
                flip();
                if (nCountObjectLoad == pageObjects.length) {

                    /* draw image */
                    // for(var nIndex = 0; nIndex < arrImage.length; nIndex ++){
                    // if(arrImage[nIndex].mediaType == '2'){/*  media */
                    // 					
                    // if(arrImage[nIndex].img.width > arrImage[nIndex].w){
                    // context.drawImage(arrImage[nIndex].img, arrImage[nIndex].x, arrImage[nIndex].y, arrImage[nIndex].w, arrImage[nIndex].h);
                    // }else{	
                    // /*draw image and border */				
                    // context.drawImage(arrImage[nIndex].img, arrImage[nIndex].x +((arrImage[nIndex].w - arrImage[nIndex].img.width)/2) , arrImage[nIndex].y + ((arrImage[nIndex].h- arrImage[nIndex].img.height)/2), arrImage[nIndex].img.width, arrImage[nIndex].img.height);			
                    // if(arrImage[nIndex].displayBorder == '1'){/* draw border */
                    // context.strokeStyle = "black";
                    // context.lineWidth = "1";
                    // context.strokeRect(arrImage[nIndex].x, arrImage[nIndex].y, arrImage[nIndex].w, arrImage[nIndex].h);
                    // }	
                    // }
                    // 							
                    // }else if(arrImage[nIndex].mediaType == '3'){/* audio */
                    // context.drawImage(arrImage[nIndex].img, arrImage[nIndex].x, arrImage[nIndex].y, arrImage[nIndex].img.width, arrImage[nIndex].img.height);
                    // }else{					
                    // context.drawImage(arrImage[nIndex].img, arrImage[nIndex].x, arrImage[nIndex].y, arrImage[nIndex].w, arrImage[nIndex].h);
                    // }	
                    // 								
                    // }			
                    // flip();		

                    /* draw marking */
                    drawMarkingOnScreen();

                    /*set status is loading page */
                    isLoadingObject = false;

                    /* enable controls in page */
                    if (ClientData.IsAddingMarking() == true) {
                        disableAllControl();
                        enableButtonMarking()
                    } else {
                        enableAllControl();
                    }

                    /*finish loading */
                    $('#divImageLoading').css('display', 'none');

                    /* set pos video */
                    zoomVideo();
                }
            };
            img.src = this.imageUrl;
        } else {
            if (nCountObjectLoad == pageObjects.length) {
                /* draw marking */
                drawMarkingOnScreen();

                /*set status is loading page */
                isLoadingObject = false;
                /* enable controls in page */
                if (ClientData.IsAddingMarking() == true) {
                    disableAllControl();
                    enableButtonMarking()
                } else {
                    enableAllControl();
                }

                /*finish loading */
                $('#divImageLoading').css('display', 'none');

                /* set pos video */
                zoomVideo();
            }
        }
    }
};

/**
* Content Class Definition 
*/
var Content = function () {

    this.pageCount = 0;
    this.pageIndex = 0;
    this.pageImages = null;
    this.pageObjects = null;
    this.currentPage = null;

};

/* ste page images (json data) */
Content.prototype.setPageImages = function (pageCount, imageUrls) {
    this.pageCount = pageCount;
    this.pageImages = imageUrls;
    return this;
};

/* set page objects data (json data) */
Content.prototype.setPageObjects = function (pageObjects) {
    this.pageObjects = pageObjects;
    return this;
};

/* Set up page */
Content.prototype.setUpPage = function (pageIndex) {
    this.currentPage = createPage(
 							this.pageIndex,
							this.pageImages,
							this.pageObjects,
							function () {
							    adjustPage();
							});
    return this;
};

/* check next page exists */
Content.prototype.hasNextPage = function () {

    if ((this.pageIndex + 1) > (this.pageCount - 1)) {
        return false;
    }
    return true;
};

/* setup next page */
Content.prototype.nextPage = function () {
    this.pageIndex++;
    if (this.pageIndex > (this.pageCount - 1)) {
        this.pageIndex = this.pageCount - 1;
    }
    this.setUpPage(this.pageIndex);
    return this;
};

/* check previous page exists */
Content.prototype.hasPreviousPage = function () {
    if ((this.pageIndex - 1) < 0) {
        return false;
    }
    return true;
};

/* setup previous page */
Content.prototype.previousPage = function () {
    this.pageIndex--;
    if (this.pageIndex < 0) {
        this.pageIndex = 0;
    }
    this.setUpPage(this.pageIndex);
    return this;
};

/* setup previous page */
Content.prototype.toPage = function (index) {
    this.pageIndex = eval(index);
    if (this.pageIndex < 0) {
        this.pageIndex = 0;
    }
    this.setUpPage(this.pageIndex);
    return this;
};

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

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

        if (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();
        //disable('#nextpage');
        $('#nextpage').unbind('click');
        $('#lastpage').unbind('click');

        if (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();
        //enable('#prevpage');
        $('#prevpage').unbind('click');
        $('#prevpage').bind('click', prevPage_click);

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

        if (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();
        //disable('#prevpage');
        $('#prevpage').unbind('click');
        $('#firstpage').unbind('click');

        if (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);
var isDestPositionDetect = false;
var destPosX = 0, destPosY = 0;
var moveX = 0, moveY = 0;
var userScale = 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;



/**
* Transition Class Definition 
*/
var Transition = function () { };
/* Flip Next Page Transition */
Transition.prototype.flipNextPage = function () {
    var w = $('#main').attr('width');
    removeObject();

    if (getContent().hasNextPage()) {
        context_main.clearRect(0, 0, canvas_main.width, canvas_main.height);
        $('#main').animate(
				{ left: '-' + w + 'px' },
				{
				    duration: "slow",
				    complete: function () {

				        // change page
				        $('#main').css('left', w + 'px');
				        // animate 
				        $('#main').animate(
							{ left: marginX + 'px' },
							{ duration: 'slow',
							    complete: function () {
							        isFirstLoad = true;
							        screenFit();
							    }
							});

				        //change pageIndex and image bookmark						
				        getContent().nextPage();
				        initImageBookmark();
				        checkExistNextPrePage();
				        changeSlider(getContent().pageIndex);
				        /* init image had draw */
				        initDisplayMarking();
				        /* change title of page */
				        if (dataPageTitle[getContent().pageIndex]) {
				            if (dataPageTitle[getContent().pageIndex] != '') {
				                document.title = contentName + '_' + dataPageTitle[getContent().pageIndex] + ' | ' + i18nText('sysAppTitle');
				            } else {
				                document.title = contentName + ' | ' + i18nText('sysAppTitle');
				            }
				        } else {
				            document.title = contentName + ' | ' + i18nText('sysAppTitle');
				        }
				        /* set end log */
				        SetEndLog(contentID);
				    }
				});
    }


};
/* Flip Previous Page Transition */
Transition.prototype.flipPreviousPage = function () {
    var w = $('#main').attr('width');
    removeObject();

    if (getContent().hasPreviousPage()) {
        context_main.clearRect(0, 0, canvas_main.width, canvas_main.height);
        $('#main').animate(
				{ left: w + 'px' },
				{
				    duration: "slow",
				    complete: function () {
				        $('#main').css('left', -w + 'px');
				        $('#main').animate(
							{ left: marginX + 'px' },
							{ duration: 'slow',
							    complete: function () {
							        isFirstLoad = true;
							        screenFit();
							    }
							});

				        //change pageIndex and image bookmark
				        getContent().previousPage();
				        initImageBookmark();
				        checkExistNextPrePage();
				        changeSlider(getContent().pageIndex);
				        /* init image had draw */
				        initDisplayMarking();
				        /* change title of page */
				        if (dataPageTitle[getContent().pageIndex]) {
				            if (dataPageTitle[getContent().pageIndex] != '') {
				                document.title = contentName + '_' + dataPageTitle[getContent().pageIndex] + ' | ' + i18nText('sysAppTitle');
				            } else {
				                document.title = contentName + ' | ' + i18nText('sysAppTitle');
				            }
				        } else {
				            document.title = contentName + ' | ' + i18nText('sysAppTitle');
				        }

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

/* Flip  Page Transition */
Transition.prototype.flipToPage = function (index) {
    var w = $('#main').attr('width');

    if (index == getContent().pageIndex) {
        /* init image had draw */
        initDisplayMarking();
    } else if (index < getContent().pageIndex) {
        context_main.clearRect(0, 0, canvas_main.width, canvas_main.height);
        removeObject();
        $('#main').animate(
				{ left: w + 'px' },
				{
				    duration: "slow",
				    complete: function () {
				        $('#main').css('left', -w + 'px');
				        $('#main').animate(
							{ left: marginX + 'px' },
							{ duration: 'slow',
							    complete: function () {
							        isFirstLoad = true;
							        screenFit();
							    }
							});
				        //change pageIndex and image bookmark
				        getContent().toPage(index);
				        initImageBookmark();
				        checkExistNextPrePage();
				        changeSlider(index);
				        /* init image had draw */
				        initDisplayMarking();
				        /* change title of page */
				        if (dataPageTitle[index]) {
				            if (dataPageTitle[index] != '') {
				                document.title = contentName + '_' + dataPageTitle[index] + ' | ' + i18nText('sysAppTitle');
				            } else {
				                document.title = contentName + ' | ' + i18nText('sysAppTitle');
				            }
				        } else {
				            document.title = contentName + ' | ' + i18nText('sysAppTitle');
				        }
				        /* set end log */
				        SetEndLog(contentID);
				    }
				}
			 );
    } else {
        context_main.clearRect(0, 0, canvas_main.width, canvas_main.height);
        removeObject();
        $('#main').animate(
				{ left: '-' + w + 'px' },
				{
				    duration: "slow",
				    complete: function () {
				        $('#main').css('left', w + 'px');
				        $('#main').animate(
							{ left: marginX + 'px' },
							{ duration: 'slow',
							    complete: function () {
							        isFirstLoad = true;
							        screenFit();
							    }
							});
				        //change pageIndex and image bookmark
				        getContent().toPage(index);
				        initImageBookmark();
				        checkExistNextPrePage();
				        changeSlider(index);
				        /* init image had draw */
				        initDisplayMarking();
				        /* change title of page */
				        if (dataPageTitle[index]) {
				            if (dataPageTitle[index] != '') {
				                document.title = contentName + '_' + dataPageTitle[index] + ' | ' + i18nText('sysAppTitle');
				            } else {
				                document.title = contentName + ' | ' + i18nText('sysAppTitle');
				            }
				        } else {
				            document.title = contentName + ' | ' + i18nText('sysAppTitle');
				        }
				        /* set end log */
				        SetEndLog(contentID);
				    }
				});
    }
};

/* 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 */
    }

    hideDialog();

    /* play background audio */
    playAllAudio();

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


/* Initialize PageViewer Component */
function initializeViewerComponent(viewId) {

    /* add some tags we need.*/
    $('#' + viewId).prepend(
		'<canvas id="main"></canvas>' +
		'<canvas id="offscreen"></canvas>' +
		'<canvas id="draw_canvas"></canvas>' +
		'<canvas id="marker_canvas"></canvas>' +
		'<div id="playvideo"></div>' +
		'<div id="playaudio" style="width:0px; height:0px;"></div>' +
		'<div id="playaudiopage" style="width:0px; height:0px;"></div>' +
		'<div id="playaudioallpage" style="width:0px; height:0px;"></div>' +
		'<div id="text"></div>'
		);

    /* apply css style */
    $('#main').css(
		{

		    'position': 'absolute',
		    'top': marginY + 'px',
		    'left': marginX + 'px',
		    'box-shadow': '3px 3px 14px #333',
		    'background-color': 'rgba(153, 153, 153, 0.7)',
		    'border-radius': '4px'
		}
	);
    $('#offscreen').css(
		{
		    'visibility': 'hidden',
		    'display': 'none'
		}
	);

    $('#marker_canvas').css(
		{
		    'display': 'none',
		    'position': 'absolute',
		    'cursor': 'default'

		}
	);

    $('#draw_canvas').css(
		{
		    'display': 'none',
		    'position': 'absolute',
		    'cursor': 'default'
		}
	);

    $('#playvideo').css(
		{
		    'position': 'fixed',
		    'top': marginY + 'px',
		    'left': marginX + 'px'
		}
	);

    //set default event
    setDefaultEvent();

    /*init canvas value */
    canvas_marker = document.getElementById('marker_canvas');
    context_marker = canvas_marker.getContext('2d');
    canvas_draw = document.getElementById('draw_canvas');
    context_draw = canvas_draw.getContext('2d');
    canvas_main = document.getElementById('main');
    context_main = canvas_main.getContext('2d');
    canvas_offscreen = document.getElementById('offscreen');
    context_offscreen = canvas_offscreen.getContext('2d');
};

function onClick_CanvasMain(event) {
    if (!cancelClick) {

        //change coordinates 
        var imagePt = screenToImage(event.pageX, event.pageY);
        var canvasWidth = $('#offscreen').width();
        posXPopupMemo = event.pageX;
        posYPopupMemo = event.pageY;

        if ((event.pageX - marginX) >= destRect.left && (event.pageX - marginX) <= destRect.right) {
            /* click add memo */
            if (ClientData.IsAddingMemo() == true) {

                if (!ClientData.memo_copyText()) {
                    AddMemo(contentID, changePageIndex(getPageIndex()), $('#divDialogMemo'), event.pageX, event.pageY, function () {
                        //set flag change memo 
                        ClientData.isChangedMemo(true);
                        ClientData.IsAddingMemo(false);

                        /* refresh draw memo */
                        drawMemoOnScreen();


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

                            /* refresh draw memo */
                            drawMemoOnScreen();


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

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

                            /* refresh draw memo */
                            drawMemoOnScreen();

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

            } else {

                var isClickMemo = false;

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

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

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

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

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

                            }

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

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

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

                        }
                    }
                }

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

                    /* check exist object in mouse position */
                    var hitPageObj = getContent().currentPage.hitTest(imagePt.x, imagePt.y);

                    if (hitPageObj) {
                        //console.log("PageObject Hit!! Id: " + hitPageObj.id);								
                        hitPageObj.action();
                    } else {

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

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

                        if (isClickLinkList == false && ClientData.IsAddingMarking() == false) {
                            /* area next and prev page */
                            var cwMain = $('#main').width();
                            if (event.pageX > 0 && event.pageX < 300) {
                                prevPage_click();
                            } else if (event.pageX > (cwMain - 300) && event.pageX < cwMain) {
                                nextPage_click();
                            }
                        }

                    }
                }
            }

        } else {
            if (ClientData.IsAddingMarking() == false && isCopyMemo == false) {
                var cwMain = $('#main').width();
                if (event.pageX > 0 && event.pageX < 300) {
                    prevPage_click();
                } else if (event.pageX > (cwMain - 300) && event.pageX < cwMain) {
                    nextPage_click();
                }
            }
        }
    }
    cancelClick = false;
};

function mouseMove_canvasMain(event) {
    event.preventDefault();
    /* base image move when userScale over 1 */
    if (moveFlag && userScale != 1) {
        $('#main').css('cursor', 'pointer');

        cancelClick = true;
        var mx;
        var my;
        // calc mouse moving distance
        if (avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android") {
            mx = event.pageX - px;
            my = event.pageY - py;
        } else {
            mx = event.targetTouches[0].pageX - px;
            my = event.targetTouches[0].pageY - py;
        }

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


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




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


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

        // redraw
        flip();

        zoomVideo();

        closeDialogPopUpText();
    }

    var cwMain = $('#main').width();
    var chMain = $('#main').height();
    /* handle image prev on canvas */
    if (getContent().hasPreviousPage()) {
        $('#button_pre_canvas').mousemove(function () {
            if (getContent().hasPreviousPage()) {

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

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

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

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

function mouseDown_CanvasMain(event) {
    moveFlag = true;
    if (isTouchDevice() != true) {
        event.preventDefault();
    }
    $('#main').css('cursor', 'default');
    /*if(event.originalEvent) {
    if(event.originalEvent.targetTouches) {
    if(event.originalEvent.targetTouches[0].pageX) {
    px = event.originalEvent.targetTouches[0].pageX;	
    }
    }			
    }*/

    // if(event.originalEvent.targetTouches[0].pageY){
    // py = event.originalEvent.targetTouches[0].pageY;
    // }

    //py = Number(event.originalEvent.targetTouches[0].pageY);
    if (avwUserEnvObj.os != "ipad" && avwUserEnvObj.os != "android") {
        px = event.pageX;
        py = event.pageY;
    } else {
        px = event.targetTouches[0].pageX;
        py = event.targetTouches[0].pageY;
    }

    // document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
    // lastX = event.offsetX || (event.pageX - canvas_main.offsetLeft);
    // lastY = event.offsetY || (event.pageY - canvas_main.offsetTop);
    // dragStart = context_main.transformedPoint(lastX,lastY);

};

function mouseUp_CanvasMain(event) {
    moveFlag = false;
    $('#main').css('cursor', 'default');
};


/* View Component setDefaultEvent */
function setDefaultEvent() {
    document.getElementById('main').addEventListener('click', onClick_CanvasMain, false);
    document.getElementById('divCheckExistMarking').addEventListener('click', onClick_CanvasMain, false);
    if (isTouchDevice() == true) {
        document.getElementById('main').addEventListener('touchstart', mouseDown_CanvasMain, false);
        document.getElementById('main').addEventListener('touchmove', mouseMove_canvasMain, false);
        document.getElementById('main').addEventListener('touchend', mouseUp_CanvasMain, false);
    } else {
        document.getElementById('main').addEventListener('mousedown', mouseDown_CanvasMain, false);
        document.getElementById('main').addEventListener('mousemove', mouseMove_canvasMain, false);
        document.getElementById('main').addEventListener('mouseup', mouseUp_CanvasMain, false);

        document.getElementById('divCheckExistMarking').addEventListener('mousedown', mouseDown_CanvasMain, false);
        document.getElementById('divCheckExistMarking').addEventListener('mousemove', mouseMove_canvasMain, false);
        document.getElementById('divCheckExistMarking').addEventListener('mouseup', mouseUp_CanvasMain, false);

        $('#main').mouseout(function (event) {
            if (moveFlag) {
                moveFlag = false;
            }

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

    /*$('#main').bind("click",onClick_CanvasMain);	
    $('#main').bind("mousemove touchmove",mouseMove_canvasMain);	
    $('#main').bind("mousedown touchstart",mouseDown_CanvasMain);
    $('#main').bind("mouseup touchend",mouseUp_CanvasMain);
	
	
    document.getElementById('main').addEventListener('click',onClick_CanvasMain,false);
    document.getElementById('main').addEventListener('touchstart',mouseDown_CanvasMain,false);
    document.getElementById('main').addEventListener('mousedown',mouseDown_CanvasMain,false);
    document.getElementById('main').addEventListener('mousemove touchmove',mouseMove_canvasMain,false);
    document.getElementById('main').addEventListener('mouseup touchend',mouseUp_CanvasMain,false);*/




};

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

    $('#listindex').bind('click', showListPageIndex);
    $('#listindex').removeClass();

    $('#copytext').bind('click', showCopyText);
    $('#copytext').removeClass();

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

    /*$('#firstpage').bind('click',firstPage_click);
    $('#firstpage').removeClass();
    $('#prevpage').bind('click',prevPage_click);
    $('#prevpage').removeClass();
    $('#nextpage').bind('click',nextPage_click);
    $('#nextpage').removeClass();
    $('#lastpage').bind('click',lastPage_click);
    $('#lastpage').removeClass();*/
    $("#slider_page").slider("option", "disabled", false);
    enable('#txtSearch', '#txtSlider');

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

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

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

        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;
};

/* grab viewer content object */
function getContent() {
    return content;
};

/* create page */
function createPage(pageNumber, pageImage, pageObjects, onCompleteFunc) {
    var page = new ContentPage(pageNumber, pageImage);
    /* add page Object */
    page.addPageObjects(pageObjects);

    /* load page */
    page.load(onCompleteFunc);

    return page;
};


/* Adjust page size */
function adjustPage(width, height) {
    /*$("#offscreen").attr('height', getContent().currentPage.image.height);
    $("#offscreen").attr('width', getContent().currentPage.image.width);	*/

    drawCanvas();

};
/* draw Canvas  */
function drawCanvas() {
    var canvas = document.getElementById('offscreen');
    var context = canvas.getContext('2d');

    context.clearRect(0, 0, canvas.width, canvas.height);

    /* draw canvas */
    draw(context);

    /*screen to image */
    //flip(); 
};

/* draw memo */
function drawMemoOnScreen() {
    var canvas = document.getElementById('offscreen');
    var context = canvas.getContext('2d');

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

        /*get data memo */
        var memoData = ClientData.MemoData();

        for (var nIndex = 0; nIndex < memoData.length; nIndex++) {
            if (memoData[nIndex].contentid == contentID
			&& memoData[nIndex].pageNo == changePageIndex(getPageIndex())) {
                /* create object of memo */
                var memoObject = null;

                if (memoData[nIndex].posY > heightEachPage - 50) {
                    memoData[nIndex].posY = heightEachPage - 50;
                }

                if (memoData[nIndex].posX > widthEachPage - 50) {
                    memoData[nIndex].posX = widthEachPage - 50;
                }
                memoObject = new memo(
					nIndex,
					memoData[nIndex].Text,
					memoData[nIndex].posX,
					memoData[nIndex].posY,
					36,
					47,
					"img/memo.png"
				);

                memoObjects.push(memoObject);
                memoObject.drawMemo(context);
            }
        }
    }
};

/* get all memo on page */
function getAllMemoOfPage() {
    if (ClientData.IsDisplayMemo() == true) {
        memoObjects = [];

        /*get data memo */
        var memoData = ClientData.MemoData();

        for (var nIndex = 0; nIndex < memoData.length; nIndex++) {
            if (memoData[nIndex].contentid == contentID
			&& memoData[nIndex].pageNo == changePageIndex(getPageIndex())) {
                /* create object of memo */
                var memoObject = null;

                if (memoData[nIndex].posY > heightEachPage - 50) {
                    memoData[nIndex].posY = heightEachPage - 50;
                }

                if (memoData[nIndex].posX > widthEachPage - 50) {
                    memoData[nIndex].posX = widthEachPage - 50;
                }
                memoObject = new memo(
					nIndex,
					memoData[nIndex].Text,
					memoData[nIndex].posX,
					memoData[nIndex].posY,
					50,
					50,
					"img/memo.png"
				);

                memoObjects.push(memoObject);
            }
        }
    }
};

/* draw webGetContent4 */
function drawGetWebContent4(context) {
    webGetContentType4Objects = [];
    for (var nIndex = 0; nIndex < dataJsonType4.length; nIndex++) {
        /* get data belong current page*/
        if (changePageIndex(getPageIndex()) == dataJsonType4[nIndex].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
				);
                webGetContentType4Objects.push(dataObject);
                dataObject.drawObject(context);

            }
        }
    }
};

/* draw marking */
function drawMarkingOnScreen() {

    var canvas = document.getElementById('offscreen');
    var context = canvas.getContext('2d');
    var canvasWidth = $('#offscreen').width();
    var canvasHeight = $('#offscreen').height();
    var indexMarking;

    if (ClientData.IsAddingMarking() == false && ClientData.IsDisplayMarking() == true) {
        var 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 == changePageIndex(getPageIndex())) {
                /*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();
                    /* set flag */
                    isExistDrawing = true;
                    /* draw memo */
                    drawMemoOnScreen();
                };
                img.src = dataMarking[nIndex].content;
                indexMarking = nIndex;
            }
        }

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

/*draw canvas*/
function draw(context) {
    context.save();

    /* draw page objects */
    getContent().currentPage.drawPage(context);

    /* draw memo */
    //drawMemoOnScreen();

    context.restore();

    initImageCheckMarking();
};

/* init image if exist marking in page */
function initImageCheckMarking() {
    /* set draw image if exist */
    var dataMarking = ClientData.MarkingData();

    var isExistMarking = false;

    for (var nIndex = 0; nIndex < dataMarking.length; nIndex++) {
        if (dataMarking[nIndex].contentid == contentID
		&& dataMarking[nIndex].pageNo == changePageIndex(getPageIndex())) {
            isExistMarking = true;
            break;
        }
    }

    /* init image display or not */
    if (ClientData.IsAddingMarking() == true) {
        $('#divCheckExistMarking').hide();
    } else {
        if (isExistMarking == true) {
            $('#divCheckExistMarking').show();
        } else {
            $('#divCheckExistMarking').hide();
        }
    }
};


var leftCanvas = 0;
var topCanvas = 0;
var count = 0;
/* display to screen */
function flip() {
    var canvas = document.getElementById('main');
    var offscreen = document.getElementById('offscreen');
    var context = canvas.getContext('2d');
    var contextOffscreen = offscreen.getContext('2d');
    // init rect
    if (srcRect.width == 0) {
        srcRect = new Rect(0, 0, offscreen.width, offscreen.height);
    }

    // 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;
        /*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 (userScale != 1 && width < canvas.width) {

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

    } else if (userScale != 1 && height < canvas.height) {

        height = height * userScale;

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

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

};

/* mediaType = 1 and actionType = 0 linkURL object*/
var imageNoAction = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
        //no action
    };
};
imageNoAction.prototype = new PageObject();

/* mediaType=1  Video object : extends PageObject */
var videoType1 = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, mediaFile, media) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
        if (media != '') {
            /* stop all audio on page */
            stopAllAudio();

            createVideoFulScreen(mediaFile, id);

            $("#btnCloseVideo").click(function (e) {
                hideDialog();

                /* play audio  */
                playAllAudio();
            });

            showDialog(true);
        }
    };
};
videoType1.prototype = new PageObject();

/* mediaType=1 and actionType = 2  Audio object : extends PageObject */
var audioType1 = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, audioFile) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
        createAudio(audioFile, "0")
    };
};
audioType1.prototype = new PageObject();

/* mediaType = 1 and actionType = 3 linkURL object*/
var linkURL = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, actionFunction, linkUrl, browserType) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, actionFunction, null);
    this.action = function () {
        window.open(linkUrl, "_blank", "new window");
    };
};
linkURL.prototype = new PageObject();

/* mediaType = 1 and actionType = 4 imagePreview object*/
var imagePreview = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, imagePreview) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {

        createImagePreview();

        showImagePreview($('#divImagePreview'), imagePreview);

        $("#btnClose").live('click', hideDialog);


        showDialog(true);
    };
};
imagePreview.prototype = new PageObject();

function showDialog(modal) {
    $("#overlay").show();
    $("#dialog").fadeIn(300);

    if (modal) {
        $("#overlay").unbind("click");
    }
    else {
        $("#overlay").click(function (e) {
            hideDialog();
        });
    }
};

function hideDialog() {
    $("#overlay").hide();
    $("#dialog").fadeOut(300);
    $('#dialog').children().remove();
};

function createImagePreview() {
    $('#dialog').prepend(
		'<h1 style="height:25px;background:url(./img/viewer/pophdbg.png) 0 0 repeat" >' +
		'<img src="img/viewer/x.png" style="margin:3px 3px 0px 21px" id="btnClose" class="align_right" ></img>' +
		'</h1>' +
		'<div id="divImagePreview" class="content_image_preview">' +
		'</div>'
	);
    $('#dialog').css('box-shadow', '0px 0px 3px 1px #666');
    $('#dialog').css('border', 'solid 1px #666');

    $('#dialog').draggable({ handle: "h1" });
};

/* mediaType = 1 and actionType = 5 jumpPage object*/
var jumpPage = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, jumpPage) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
        if ((Number(jumpPage) - 1) != getPageIndex()) {
            changePage(Number(jumpPage) - 1);
        }
    };
};
jumpPage.prototype = new PageObject();

/* mediaType = 1 and actionType = 6 send mail object*/
var sendMail = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, emailSubject, emailAddress) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
        MailTo(emailAddress, emailSubject);
    };
};
sendMail.prototype = new PageObject();

/* mediaType = 1 and actionType = 8 open popup object*/
var openPopUp = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, content) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
        isOpenPopUpText = true;
        var pt1 = imageToScreen(x, y + h / 2);

        if (userScale > 1) {
            OpenPopupText(posXPopupMemo, posYPopupMemo, content, $('#dialogPopUp'), $('#arrow'));
        } else if ($("#header_toolbar").is(":hidden")) {
            OpenPopupText(pt1.x, pt1.y - 65, content, $('#dialogPopUp'), $('#arrow'));
        } else {
            OpenPopupText(pt1.x, pt1.y, content, $('#dialogPopUp'), $('#arrow'));
        }
    };
};
openPopUp.prototype = new PageObject();


/* mediaType = 1 and actionType = 10 move to Content object*/
var moveToContent = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, contentId, pageNo) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
        /* set end log */
        SetEndLog(contentID);
        RegisterLog();

        ClientData.common_preContentId(contentId);
        ClientData.common_prePageNo(pageNo);

        /* store old page */
        var oldContent = { oldContentID: contentID, oldPageIndex: getPageIndex() };

        var dataJump = ClientData.JumpQueue();

        dataJump.push(oldContent);

        ClientData.JumpQueue(dataJump);

        avwScreenMove(ScreenIds.ContentView)
    };
};
moveToContent.prototype = new PageObject();

/* mediaType=2  Video object : extends PageObject */
var videoType2 = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, mediaFile, media, embed) {

    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, embed);
    this.action = function () {
        /*stop audio on page */
        stopAllAudio();
        if (embed == "1") {
            showVideoObject(x, y, w, h, mediaFile, false);
        } else {
            if (media != '') {
                $('#playvideo').children().remove();

                createVideoFulScreen(mediaFile, id);

                $("#btnCloseVideo").click(function (e) {
                    hideDialog();
                    /*play audio if exist */
                    playAllAudio();
                });

                showDialog(true);
            }
        }
    };
};
videoType2.prototype = new PageObject();

/* create video on page */
function createVideoFulScreen(video, id) {
    $('#dialog').css('box-shadow', '0px 0px 3px 1px #666');
    $('#dialog').css('border', 'solid 1px #666');
    $('#dialog').draggable({ handle: "h1" });

    $('#dialog').children().remove();
    if (ClientData.userOpt_videoMode() == "1") {/* loop video */
        $('#dialog').html(
			'<h1 style="height:25px;background:url(./img/viewer/pophdbg.png) 0 0 repeat">' +
			'	<img src="img/viewer/x.png" style="margin:3px 3px 0px 21px" id="btnCloseVideo" class="align_right" ></img>' +
			'</h1>' +
			'		<div id="videoMedia' + id + '">' +
			'			<video style="height:90%; width:100%;" class="mov" id="videoOnPopUp" autoplay controls loop>' +
			'			 <source src="' + video + '" type="video/mp4"> ' +
	  		'    </video>' +
			'		</div>'
			);
    } else {
        $('#dialog').html(
			'<h1 style="height:25px;background:url(./img/viewer/pophdbg.png) 0 0 repeat">' +
			'	<img src="img/viewer/x.png" style="margin:3px 3px 0px 21px" id="btnCloseVideo" class="align_right" width=25px" ></img>' +
			'</h1>' +
			'		<div id="videoMedia' + id + '">' +
			'			<video style="height:90%; width:100%;" id="videoOnPopUp" class="mov" autoplay controls>' +
			'			 <source src="' + video + '" type="video/mp4"> ' +
	  		'    </video>' +
			'		</div>'
			);
    }
    $('#videoOnPopUp').css('height', ($('#dialog').height() - 25) + "px");
    //showControlsVideo($('#videoOnPopUp'));
};

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

};

/* mediaType=3  Audio object : extends PageObject */
var audioType3 = function (mediaType, actionType, id, imageUrl, x, y, w, h, visible, audioFile, playType) {

    if (playType == "0") {
        this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, null, null);
        this.action = function () {
            createAudio(audioFile, playType);
        };
    } else {
        createAudio(audioFile, playType);
        this.setup(mediaType, actionType, id, null, x, y, w, h, visible, null, null);
        this.action = function () {

        };
    }
};
audioType3.prototype = new PageObject();


/* 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) {
            document.getElementById("play_audio_0").pause();
        }

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

        if (document.getElementById("play_audio_2") != undefined) {
            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;

/* create audio on page */
function createAudio(audio, type) {
    // if(avwUserEnvObj.browser == 'firefox'){
    // audio =  audio.replace("webResourceDownload/", "webResourceDownload");
    // }

    if (audio != '') {
        if (type == "0") { /* play when click */
            stopAllAudio();

            TypeAudio0 = type;
            srcAudioType0 = audio;

            if (ClientData.userOpt_musicMode() == "1") {
                if (avwUserEnvObj.browser == 'firefox') {
                    $('#playaudio').html(
						'	 <embed id="play_audio_0" src="' + audio + '&key=' + (new Date()).toIdString() + '" autostart="true" loop="true" hidden="true"> </embed>'
					);
                } else if (avwUserEnvObj.os == "ipad") {
                    $('#playaudio').html(
						'	<audio  id="play_audio_0" loop="loop"  >' +
						'		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
						'	</audio>'
						);
                } else {
                    $('#playaudio').html(
						'	<audio  id="play_audio_0" loop="loop"  autoplay ="autoplay">' +
						'		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
						'	</audio>'
					);
                }

            } else {
                if (avwUserEnvObj.browser == 'firefox') {
                    $('#playaudio').html(
						'	 <embed id="play_audio_0" src="' + audio + '&key=' + (new Date()).toIdString() + '" autostart="true" hidden="true"> </embed>'
					);
                } else if (avwUserEnvObj.os == "ipad") {
                    $('#playaudio').html(
						'	<audio  id="play_audio_0">' +
						'		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
						'	</audio>'
						);
                } else {
                    $('#playaudio').html(
						'	<audio  id="play_audio_0" autoplay ="autoplay">' +
						'		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
						'	</audio>'
					);
                }

            }

            if (avwUserEnvObj.os == "ipad") {
                document.getElementById("play_audio_0").load();
                document.getElementById("play_audio_0").play();
            }

        } else if (type == "1") { /* play all page */
            if (document.getElementById("play_audio_1") != undefined) {

                if (ClientData.userOpt_musicMode() == "1") {
                    if (avwUserEnvObj.browser == 'firefox') {
                        $('#playaudioallpage').html(
							'	 <embed id="play_audio_1" src="' + audio + '&key=' + (new Date()).toIdString() + '" autostart="true" loop="true"  hidden="true"> </embed>'
						);
                    } else {
                        document.getElementById("play_audio_1").play();
                    }
                } else {
                    if (avwUserEnvObj.browser == 'firefox') {
                        $('#playaudioallpage').html(
							'	 <embed id="play_audio_1" src="' + audio + '&key=' + (new Date()).toIdString() + '" autostart="true" hidden="true"> </embed>'
						);
                    } else {
                        document.getElementById("play_audio_1").play();
                    }
                }
            } else {
                TypeAudio1 = type;
                srcAudioType1 = audio;

                if (ClientData.userOpt_musicMode() == "1") {
                    if (avwUserEnvObj.browser == 'firefox') {
                        $('#playaudioallpage').html(
							'	 <embed id="play_audio_1" src="' + audio + '&key=' + (new Date()).toIdString() + '" autostart="true" loop="true"  hidden="true"> </embed>'
						);

                    } else if (avwUserEnvObj.os == "ipad") {
                        $('#playaudioallpage').html(
							 '	<audio  id="play_audio_1" loop="loop" >' +
							 '		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
							 '	</audio>'
						 );
                    } else {
                        $('#playaudioallpage').html(
							 '	<audio  id="play_audio_1" loop="loop" autoplay="autoplay" >' +
							 '		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
							 '	</audio>'
						 );
                    }
                } else {
                    if (avwUserEnvObj.browser == 'firefox') {
                        $('#playaudioallpage').html(
							'	 <embed id="play_audio_1" src="' + audio + '&key=' + (new Date()).toIdString() + '" autostart="true" hidden="true"> </embed>'
						);
                    } else if (avwUserEnvObj.os == "ipad") {
                        $('#playaudioallpage').html(
							 '	<audio  id="play_audio_1" >' +
							 '		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
							 '	</audio>'
						 );
                    } else {
                        $('#playaudioallpage').html(
							 '	<audio  id="play_audio_1" autoplay = "autoplay"  >' +
							 '		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
							 '	</audio>'
						 );
                    }
                }
                // Check to play BGM on ipad
                if (avwUserEnvObj.os == "ipad") {
                    // Show confim message to play background music
                    $("#bgmConfirm_dspCancel").unbind('click');
                    $("#bgmConfirm_dspCancel").click(function () {
                        $("#bgmConfirm").hide();
                    });
                    $("#bgmConfirm_dspOK").unbind('click');
                    $("#bgmConfirm_dspOK").click(function () {
                        document.getElementById('play_audio_1').load();
                        document.getElementById('play_audio_1').play();
                        $("#bgmConfirm").hide();
                    });
                    $("#bgmConfirm").show();
                    $("#bgmConfirm").center();
                }
            }
        }
        else if (type == "2") { /* play on page */
            if (document.getElementById("play_audio_2") == undefined) {
                stopAllAudio();

                TypeAudio2 = type;
                srcAudioType2 = audio;

                if (ClientData.userOpt_musicMode() == "1") {
                    if (avwUserEnvObj.browser == 'firefox') {
                        $('#playaudiopage').html(
								'	 <embed id="play_audio_2" src="' + audio + '&key=' + (new Date()).toIdString() + '" autostart="true" loop="true" hidden="true"> </embed>'
							);
                    } else if (avwUserEnvObj.os == "ipad") {
                        $('#playaudiopage').html(
							'	<audio  id="play_audio_2" loop="loop" >' +
							'		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
							'	</audio>'
						);
                    } else {
                        $('#playaudiopage').html(
							'	<audio  id="play_audio_2" loop="loop" autoplay ="autoplay">' +
							'		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
							'	</audio>'
						);
                    }
                } else {
                    if (avwUserEnvObj.browser == 'firefox') {
                        $('#playaudiopage').html(
								'	 <embed id="play_audio_2" src="' + audio + '&key=' + (new Date()).toIdString() + '" autostart="true" hidden="true"> </embed>'
							);
                    } else if (avwUserEnvObj.os == "ipad") {
                        $('#playaudiopage').html(
							'	<audio  id="play_audio_2" >' +
							'		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
							'	</audio>'
						);
                    } else {
                        $('#playaudiopage').html(
							'	<audio  id="play_audio_2" autoplay ="autoplay">' +
							'		 <source src="' + audio + '&key=' + (new Date()).toIdString() + '" type="audio/mpeg" />' +
							'	</audio>'
						);
                    }
                }

                // Check to play BGM on ipad
                if (avwUserEnvObj.os == "ipad") {
                    // Show confim message to play background music
                    $("#bgmConfirm_dspCancel_page").unbind('click');
                    $("#bgmConfirm_dspCancel_page").click(function () {
                        $("#bgmConfirm_page").hide();
                    });
                    $("#bgmConfirm_dspOK_page").unbind('click');
                    $("#bgmConfirm_dspOK_page").click(function () {
                        document.getElementById('play_audio_2').load();
                        document.getElementById('play_audio_2').play();
                        $("#bgmConfirm_page").hide();
                    });
                    $("#bgmConfirm_page").show();
                    $("#bgmConfirm_page").center();
                }
            }
        }
    } else {
        stopAllAudio();
    }

};

/* mediaType=4  list image object : extends PageObject */
var listImage = function (mediaType, id, imageUrl, x, y, w, h, visible, imageObjects, triggerType) {
    this.setup(mediaType, null, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
        if (triggerType == '1') {
            mediaType4_changeImage++;

            /* check index bigger than length object */
            if (mediaType4_changeImage > (imageObjects.length - 1)) {
                mediaType4_changeImage = 0;
            }

            /* draw image */
            var imageObj = new Image();
            imageObj.onload = function () {
                var canvasObject = document.getElementById("offscreen");
                var contextObject = canvasObject.getContext("2d");
                contextObject.drawImage(imageObj, x, y, w, h);
                flip();
            };
            imageObj.src = imageObjects[mediaType4_changeImage].fileName;
        }
    };
};
listImage.prototype = new PageObject();

/* mediaType=5 Replace Video object : extends PageObject */
var listVideo = function (mediaType, id, imageUrl, x, y, w, h, visible, videoObjects) {
    this.setup(mediaType, null, id, imageUrl, x, y, w, h, visible, null, null);
    this.action = function () {
    };
};
listVideo.prototype = new PageObject();

/* mediaType=6 Trigger object : extends PageObject */
var trigger = function (mediaType, actionType, id, imageUrl, x, y, w, h, index, target, visible, actionFunction) {
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, actionFunction, null);
    this.action = function () {
        // draw object		
        /*if(isObjType4 == true){			
        for(var nIndex = 0; nIndex < objType4.imageObjects.length; nIndex++) {
        if(objType4.imageObjects[nIndex].index == index){	
        alert(target);		
        changeImageType4(objType4,nIndex);	
        break;				
        }
        }
        }else if(isObjType5 == true){			
        for(var nIndex = 0; nIndex < objType5.videoObjects.length; nIndex++) {				
        if(objType5.videoObjects[nIndex].index == index){	
													
        showVideoObject(objType5.x, objType5.y, objType5.width, objType5.height,objType5.videoObjects[nIndex].fileName,false);
					
        break;					
        }
        }
        }*/
        for (var nIndex = 0; nIndex < objType4_5.length; nIndex++) {
            for (var nIndex1 = 0; nIndex1 < objType4_5[nIndex].dataObjects.length; nIndex1++) {
                if (objType4_5[nIndex].dataObjects[nIndex1].index == index
					&& objType4_5[nIndex].id == target) {
                    if (objType4_5[nIndex].mediaType == '4') {	/*image*/
                        changeImageType4(objType4_5, nIndex, nIndex1);
                    } else {   /* video */
                        stopAllAudio();
                        showVideoObject(objType4_5[nIndex].x, objType4_5[nIndex].y, objType4_5[nIndex].width, objType4_5[nIndex].height, objType4_5[nIndex].dataObjects[nIndex1].fileName, false);
                    }
                    break;
                }
            }
        }
    };
};
trigger.prototype = new PageObject();

/* 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");
        contextObject.drawImage(imageObj, objTarget[nIndex].x, objTarget[nIndex].y, objTarget[nIndex].width, objTarget[nIndex].height);
        flip();
    };
    imageObj.src = objTarget[nIndex].dataObjects[nIndex1].fileName;
};

/* mediaType = 7 write text object*/
var text = function (mediaType, actionType, id, x, y, w, h, visible, actionFunction, content) {
    //var imageUrl = displayText(x,y,w,h,id,content);
    var imageUrl = getTextObjectImage(w, h, content);
    this.setup(mediaType, actionType, id, imageUrl, x, y, w, h, visible, actionFunction, null);
    this.action = function () {
    };
};
text.prototype = new PageObject();

/*
var pxText;
var pyText;
*/
/* display text on canvas*/
/*
function displayText(x, y, width, height,id,content) {
	
var canvasObject = document.getElementById("offscreen");
var contextObject = canvasObject.getContext("2d");
var dataHtml = "<div align='center'><font face='ＭＳ Ｐゴシック' style='LETTER-SPACING:-0.2px;LINE-HEIGHT:120%;FONT-SIZE:11px' color='#333333' letterspacing='0' kerning='1'><font style='LETTER-SPACING:-0.2px;LINE-HEIGHT:120%;FONT-SIZE:16px' color='#cc0000'><u>TEXT</u></font></font></div><div align='center'><font face='ＭＳ Ｐゴシック' style='LETTER-SPACING:-0.2px;LINE-HEIGHT:120%;FONT-SIZE:11px' color='#333333' letterspacing='0' kerning='1'><font style='LETTER-SPACING:-0.2px;LINE-HEIGHT:120%;FONT-SIZE:16px' color='#cc0000'><u>TEXT</u></font></font></div>";
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='196' height='261'>" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
dataHtml +
"</div>" +
"</foreignObject>" +
"</svg>";
var DOMURL = self.URL || self.webkitURL || self;
//var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);	  

return url;
};
*/

function imageToScreen(x, y) {

    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 * (x - srcRect.left)) + destRect.left + marginX;
    pt.y = Math.round(sy * (y - srcRect.top)) + destRect.top + marginY;

    return pt;
};

/* Adjust Component size */
function sizingNotFull(width, height) {
    //adjust size of canvas using for draw		
    if (isTouchDevice() == true) {
        $("#main").css('top', marginY);
        $("#main").attr('height', height - (marginY * 2))
		  .attr('width', width - (marginX * 2));

    } else {
        $("#main").attr('height', height - (marginY * 2))
			  .attr('width', width - (marginX * 2))
			   .css('top', marginY);
    }

    $("#draw_canvas").css('cursor', 'default');
    $("#marker_canvas").css('cursor', 'default');

    if (userScale != 1) {
        changeScale(userScale);
        flip();
    }

    /* move image check marking*/
    $('#divCheckExistMarking').css('top', '70px');
    $('#divCheckExistMarking').show();
};

/* Adjust Component size */
function sizingFullSize(width, height) {
    // adjust size of body
    if (isTouchDevice() == true) {
        $("#main").css('top', '0px');
        $("#main").attr('height', height)
				   .attr('width', width - (marginX * 2));
    } else {
        $("#main").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();
    }

    /* move image check marking*/
    $('#divCheckExistMarking').css('top', '5px');
    if (ClientData.IsAddingMarking() == true) {
        $('#divCheckExistMarking').hide();
    } else {
        $('#divCheckExistMarking').show();
    }
};

/* zoom video */
var pxVideo;
var pyVideo;
var wVideo;
var hVideo;
var videoScale;

function getPosVideo(px, py, width, height, scale) {
    pxVideo = px;
    pyVideo = py;
    wVideo = width;
    hVideo = height;
    videoScale = scale;
};

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);
        /*$('#playvideo').html('<video class="mov" src="' + src + '" ' +
        'width="' + (pt2.x - pt1.x) + '" ' +
        'height="' + (pt2.y - pt1.y) + '" ' +
        'autoplay controls></video>');
        */
    }
};

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


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

        /* 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;
    moveX = 0;
    moveY = 0;

    flip();

    /* zoom video */
    zoomVideo();

    checkDisableButtonZoom();

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


/* change Scale screen*/
function changeScale(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;
};

/* 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;
};

function encode(data) {
    var str = String.fromCharCode.apply(null, data);
    return btoa(str).replace(/.{76}(?=.)/g, '$&\n');
};


/* ----------------------------------- Create memo --------------------------------*/

var memoObjects = [];

/* constructor */
var MemoObject = function (id, text, x, y, width, heigth, imageUrl, action) {

};

/* setup each properties */
MemoObject.prototype.setup = function (id, text, x, y, w, h, imageUrl) {
    this.text = text;
    this.id = id;
    this.x = x;
    this.y = y;
    this.width = w;
    this.height = h;
    this.imageUrl = imageUrl;
};

/* prototype hitTest */
MemoObject.prototype.hitTest = function (px, py) {
    if (this.x <= px && px <= (this.x + this.width)) {
        if (this.y <= py && py <= (this.y + this.height)) {
            return true;
        }
    }
    return false;
};

/* draw Memo */
MemoObject.prototype.drawMemo = function (context) {
    var posX = this.x;
    var posY = this.y;
    var objWidth = this.width;
    var objHeigth = this.height;
    var imageObj = new Image();

    imageObj.onload = function () {
        context.drawImage(imageObj, posX, posY, objWidth, objHeigth);
        flip();
    };
    imageObj.src = this.imageUrl;

};

/* create memo object */
var memo = function (id, text, x, y, w, h, imageUrl) {
    this.setup(id, text, x, y, w, h, imageUrl);
    this.action = function () {
        EditMemo(id, 0, 0, $('#divDialogMemo'), function () {
            /*set flag change memo */
            ClientData.isChangedMemo(true);
        });

    };
};
memo.prototype = new MemoObject();

/*click showEditMemo() */
function showEditMemo() {
    objEditMemo.action();
};

/*click copyMemo() */
function copyMemo() {
    //isCopyMemo = true;
    ClientData.memo_copyText(objEditMemo.text);
    //disableControlsCopyMemo();
    $("#pop_up_memo").hide();
};


/* ----------------------------------- End create memo -----------------------------*/

/* ----------------------------------- Create webGetContentType4 --------------------------------*/

var webGetContentType4Objects = [];

/* constructor */
var WebGetContentTyp4Object = function (id, x, y, width, heigth, imageUrl, action) {

};

/* setup each properties */
WebGetContentTyp4Object.prototype.setup = function (id, x, y, w, h, imageUrl) {
    this.id = id;
    this.x = x;
    this.y = y;
    this.width = w;
    this.height = h;
    this.imageUrl = imageUrl;
};

/* prototype hitTest */
WebGetContentTyp4Object.prototype.hitTest = function (px, py) {
    if (this.x <= px && px <= (this.x + this.width)) {
        if (this.y <= py && py <= (this.y + this.height)) {
            return true;
        }
    }
    return false;
};

/* draw Memo */
WebGetContentTyp4Object.prototype.drawObject = function (context) {
    var posX = this.x;
    var posY = this.y;
    var objWidth = this.width;
    var objHeigth = this.height;
    var imageObj = new Image();
    imageObj.onload = function () {
        context.globalAlpha = 0.4;

        context.drawImage(imageObj, posX, posY, objWidth, objHeigth);
        flip();

        context.globalAlpha = 1;
    };
    imageObj.src = this.imageUrl;

};

/* create memo object */
var webContentType4 = function (id, x, y, w, h, imageUrl, linkKind, destURI, destPageNumber) {
    this.setup(id, x, y, w, h, imageUrl);
    this.action = function () {
        if (linkKind == "1") {
            window.open(destURI, "_blank", "new window");
        } else if (linkKind == "0") {
            changePage(changePageNo(destPageNumber));
        }
    };
};
webContentType4.prototype = new WebGetContentTyp4Object();

/* ----------------------------------- End create webGetContentType4 -----------------------------*/

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

    window.onbeforeunload = null;

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

};

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

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

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

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

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

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

function click_liAddMemo(event) {
    typeSelectMemo = 1;

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

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

function click_liCopyMemo() {
    typeSelectMemo = 2;

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

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

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

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

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

