var g_onlyHtmlDebug = false;
var g_item_id_all = -1;
var g_current_album = g_item_id_all;
var g_itemMovment = null;
var g_headerHeight = 89;
//var g_bShowPreviewBtn = true;
//var g_btnPreviewClicked = false;
function languageFontFamily(language)
{
    if (language == 'Korean') {
        //console.log('hh');
        return 'Arial Unicode MS,굴림,바탕,Malgun Gothic';
    }
    return null;
}
function resetTranslateObj(obj,str)
{
    var ff = languageFontFamily(parent.dataFromMain('language'));
    if (ff != null) obj.style.fontFamily = ff;
    obj.innerText = str;
}
function resetMultLauage() {
    if (g_onlyHtmlDebug) return;
    var list = document.getElementsByClassName('ts_element');
    for (i = 0; i < list.length; i++) {
        var ele = list[i];
        resetTranslateObj(ele, parent.dataFromMain('translation', ele.getAttribute('key')));
    }
    updateSelectAllText();
}
var g_maskIterCnt = 0;
function handleMaskPause(obj) {
    if (obj.classList.contains('before')) {
        //var mask = document.getElementById('mask_container');
        //mask.style.width = ((g_current_album != g_item_id_all) ? '100%' : '0px');
        //mask.style.height = ((g_current_album != g_item_id_all) ? '100%' : '0px');
        g_maskIterCnt++;
        var after = document.getElementById('cover_after');
        var mask = document.getElementById('mask');
        if ((g_maskIterCnt % 4) === 3) {
            obj.classList.remove('photo');
            obj.classList.add('album');
            after.classList.remove('photo');
            after.classList.add('album');
            mask.classList.remove('photo');
            mask.classList.add('album');            
            pasueAnimation(obj, true);            
            pasueAnimation(after, true);
        } else if ((g_maskIterCnt % 2) === 1) {
            obj.classList.add('photo');
            obj.classList.remove('album');
            after.classList.add('photo');
            after.classList.remove('album');
            mask.classList.add('photo');
            mask.classList.remove('album');
            setTimeout(function () {
                refreshAlbum(g_current_album);
                doSwith2Album();
            }, 80);
        } 
    }
}
//function previewPaused(obj) {
//    pasueAnimation(obj, true);
//    setTimeout(function () {
//        var bMain = false;
//        if (obj.classList.contains('willShow')) {
//            bMain = true;
//        }
//        var main = document.getElementById(bMain ? 'main' : 'preview');
//        main.style.left = main.style.left;
//        if (bMain) {
//            load();
//        }
//    }, 80);
//}
function listentContentEvt(list) {
    for (i = 0; i < list.length; i++) {
        var content = list[i];
        content.addEventListener('animationstart', function () {
        });
        content.addEventListener('animationend', function () {
            //animationEnd(window.event.target);
        });
        content.addEventListener('animationiteration', function () {
            var e = window.event;
            var obj = window.event.target;
            if (obj.classList.contains('cover')) {
                handleMaskPause(obj);
            } /*else if (obj.classList.contains('main')) {
                previewPaused(e.target);
            } */else {
                pasueAnimation(e.target, true);
            }
        });
    }
}
function prepareImgThubnail(albumIdx, photoIdx) {
    if (g_onlyHtmlDebug) {
        changeThumbnail(albumIdx, photoIdx);
    } else {
        do {
            var it = document.getElementById(makeItemID('item', albumIdx, photoIdx));
            if (null == it) break;
            //console.log('prepare thumbnail:' + albumIdx + '-' + photoIdx);
            if (!itemIsVisual(albumIdx, photoIdx)) break;
            //console.log('=============');
            parent.jsAction('tryGetThumbnail', albumIdx, photoIdx);
        } while (0);
    }
}
var debugAlbumCnt = 100;
function itemIsVisual(albumIdx, photoIdx)
{
    var it = document.getElementById(makeItemID('item', albumIdx, photoIdx));
    if (it == null) return false;
    var content = document.getElementById(g_current_album == g_item_id_all ? 'content_album' : 'content_photo');
    var scrollTop = content.scrollTop;
    var scrollBottom = scrollTop + content.clientHeight;
    //console.log('st:' + scrollTop + ' sb:' + scrollBottom + ' y:' + it.offsetTop + ' h:' + it.clientHeight);
    return (scrollTop <= (it.offsetTop + it.clientHeight)) && (scrollBottom >= it.offsetTop);
}
var g_lastItem = 0;
function cleanItemImag(curIdx) {
    var lastStart = Math.max(0, g_lastItem - g_contentItemcounts);
    var lastArray = new Array();
    for (var i = lastStart; i < g_lastItem; i++) {
        lastArray.push(i);
    }
    var curStart = Math.max(0, curIdx - g_contentItemcounts);
    var cleanArray = new Array();
    for (var i = curStart; i < curIdx; i++) {
        var idx = lastArray.indexOf(i);
        if (-1 == idx) continue;
        cleanArray.push(i);
    }

    for (var i = 0; i < cleanArray.length; i++) {
        var idx = cleanArray[i];
        console.log(idx);
        var albumIdx = ((g_current_album == g_item_id_all) ? idx : g_current_album);
        var photoIdx = ((g_current_album == g_item_id_all) ? g_item_id_all : idx);
        var it = document.getElementById(makeItemID('item', albumIdx, photoIdx));
        if (null == it) continue;
        it.style.backgroundImage = "";
        var filter = itemFilter(it);
        filter.style.backgroundImage = "";
    }
}
function prepareContentItem(content, albumIdx, photoIdx) {
    var it = document.getElementById(makeItemID('item', albumIdx, photoIdx));
    if (it != null) return;
    it = createMainItem(albumIdx, photoIdx, false);
    it.classList.add('transform');
    content.appendChild(it);
    showItem(it, true);
    var cnt = debugAlbumCnt;
    if (!g_onlyHtmlDebug) {
        cnt = parent.dataFromMain('albumCount', albumIdx);
    }
    updateItemCnt(albumIdx, cnt);
}
function resetLastItem(content)
{
    var contentItemCounts = 0;
    var albumIdx = ((g_current_album == g_item_id_all) ? 0 : g_current_album);
    var photoIdx = ((g_current_album == g_item_id_all) ? g_item_id_all : 0);
    var it = document.getElementById(makeItemID('item', albumIdx, photoIdx));
    do{
        if (null == it) break;
        var itWidth = it.clientWidth + 16;
        var itHeight = it.clientHeight + 16;
        var oneRowItemCnt = parseInt((content.clientWidth - 21) / itWidth);
        var rows = (content.clientHeight / itHeight) + 2;
        //console.log(content.scrollTop);
        contentItemCounts = parseInt(oneRowItemCnt * (rows + 1));
        var startIdx = Math.max(parseInt(content.scrollTop / itHeight) - 1, 0) * oneRowItemCnt;
        var lastItem = startIdx + rows * oneRowItemCnt - 1;
        lastItem = Math.max(parseInt(lastItem), 0);
        //console.log('startIdx:' + startIdx + ' lastItem:' + lastItem);
        //cleanItemImag(lastItem);
        g_lastItem = lastItem;
    } while (0);
    return contentItemCounts;
}
function onResetItemBackgroundImage(content)
{
    var startIdx = Math.max(0, g_lastItem - g_contentItemcounts);
    for (var i = startIdx; i < g_lastItem; i++) {
        var albumIdx = ((g_current_album == g_item_id_all) ? i : g_current_album);
        var photoIdx = ((g_current_album == g_item_id_all) ? g_item_id_all : i);
        var it = document.getElementById(makeItemID('item', albumIdx, photoIdx));
        if (it == null || it.style.backgroundImage != '') continue;
        prepareImgThubnail(albumIdx, photoIdx);
    }
}
function prepareAlbumContent() {
    var cnt = 0;
    var content = document.getElementById('content_album');
    content.onscroll = function () {
        g_contentItemcounts = resetLastItem(content);
        onResetItemBackgroundImage(this);
    }
    if (g_onlyHtmlDebug)
        cnt = debugAlbumCnt;
    else {
        cnt = parent.dataFromMain('albumCount', g_item_id_all);
        content.setAttribute('count',cnt);
    }
    for (i = 0; i < cnt; i++) {
        prepareContentItem(content, i, g_item_id_all);
        prepareImgThubnail(i, g_item_id_all);
    }
}
//var g_addAlbumPhotoTimer = 0;
var g_contentItemcounts = 0;
function preparePhotoContent(albumIdx) {
    var content = document.getElementById('content_photo');
    var cnt = 0;
    content.onscroll = function () {
        g_contentItemcounts = resetLastItem(content);
        setTimeout(function () {
            onResetItemBackgroundImage(content);
        }, 1000); 
    }
    if (g_onlyHtmlDebug)
        cnt = debugAlbumCnt;
    else {
        cnt = parent.dataFromMain('albumCount', albumIdx);
    }
    content.setAttribute('count', cnt);
    var idx = 0;
    var invalidCnt = 0;
    if (content.hasChildNodes) {
        for (i = 0; i < content.childNodes.length; i++) {
            if (!content.childNodes[i].classList) invalidCnt++;
            else break;
        }
        idx = content.childNodes.length - invalidCnt;
    }
    var photoIdx = Math.max(idx - 1, 0);
    var it = document.getElementById(makeItemID('item', albumIdx, photoIdx));
    if (null != it && itemIsVisual(albumIdx, photoIdx)) {
        prepareImgThubnail(albumIdx, photoIdx);
    }
    if (idx >= cnt) return;
    //{
    //    console.log('idx:' + idx);
    //    onResetItemBackgroundImage(content);
    //    return;
    //}
    setTimeout(function () {
        prepareContentItem(content, albumIdx, idx);
    }, 20);
}
function previewBackgroundImg()
{
    var src = "image/1.png";
    if (!g_onlyHtmlDebug) {
        src = parent.dataFromMain('previewImage');
    }
    var preview = document.getElementById('preview');
    preview.style.backgroundImage = 'url(' + src + ')';
    return src;
}
function startPreviewAnimation(bShow, bSend)
{
    var sMain = document.getElementById(bShow ? 'main' : 'preview');
    var hMain = document.getElementById(!bShow ? 'main' : 'preview');
    var factor = 100 / (340 / 20);
    if (bShow) {
        sMain.style.left = "-100%";
        hMain.style.left = "0%";
        var privewInterval = setInterval(function () {
            var sCur = parseFloat(sMain.style.left);
            sCur += factor;
            if (sCur >= 0) {
                clearInterval(privewInterval);
                sCur = 0;
                load();
            }
            sMain.style.left = sCur + '%';
            var hCur = parseFloat(hMain.style.left);
            hCur += factor;
            if (hCur >= 100) {
                hCur = 100;
            }
            hMain.style.left = hCur + '%';
        }, 20);
    } else {
        sMain.style.left = "100%";
        hMain.style.left = "0%";
        var privewInterval = setInterval(function () {
            var sCur = parseFloat(sMain.style.left);
            sCur -= factor;
            if (sCur <= 0) {
                clearInterval(privewInterval);
                sCur = 0;
                if (!g_onlyHtmlDebug && bSend) {
                    parent.jsAction('backPreview');
                }
                if (!g_onlyHtmlDebug) {
                    preview.setAttribute('src', '');
                }
            }
            sMain.style.left = sCur + '%';
            var hCur = parseFloat(hMain.style.left);
            hCur -= factor;
            if (hCur <= -100) {
                hCur = -100;
            }
            hMain.style.left = hCur + '%';
        }, 20);
    }
 
}
function willShowPreview() {
    var src = previewBackgroundImg();
    //var preview = document.getElementById('preview');
    //var main = document.getElementById('main');
    //if (preview.classList.contains('willHide')) {
    //    preview.classList.remove('willHide');
    //    //console.log('prevew class contains!');
    //}
    //if (main.classList.contains('willShow')) {
    //    main.classList.remove('willShow');
    //    //console.log('main class contains!');
    //}
    var b = (src.length > 0);
    if (!b) {
        main.style.left = '0px';
        preview.style.left = '100%';
        return;
    } else {
        startPreviewAnimation(true, false);
    }
    //else {
    //    preview.style.left = '0px';
    //    main.style.left = '-100%';
    //}
    ////document.getElementById('previewImg').setAttribute('src', src);
    //preview.style.backgroundImage = src;
    //preview.classList.add('willHide');
    //pasueAnimation(preview, false);
    //main.classList.add('willShow');
    //pasueAnimation(main, false);
}
function createMovmentItem()
{
    if (g_itemMovment) return;
    g_itemMovment = createMainItem(-1, -1, true);
    g_itemMovment.classList.add('move');
    g_itemMovment.style.position = 'absolute';
    pasueAnimation(g_itemMovment, true);
    showItem(g_itemMovment, false);
    var main = document.getElementById('main');
    main.appendChild(g_itemMovment);
    g_itemMovment.removeChild(itemFilter(g_itemMovment));
}
function showItem(obj, b)
{
    obj.classList.remove(b ? 'hide' : 'show');
    obj.classList.add(b ? 'show' : 'hide');
}
function doSwith2Album()
{
    var photo = document.getElementById('content_photo');
    var album = document.getElementById('content_album');
    if (g_current_album == g_item_id_all) {
        photo.style.visibility = 'hidden';
        album.style.visibility = 'visible';
    } else {
        album.style.visibility = 'hidden';
        photo.style.visibility = 'visible';
    }
    if (!g_onlyHtmlDebug) {
        parent.jsAction('updateSelectAllCheckState', g_current_album);
        //parent.jsAction('updateChildrenCheckState', g_current_album);
    }
}
function pasueAnimation(obj, b) {
    if (b) {
        obj.classList.add('paused');
    } else {
        obj.classList.remove('paused');
    }
    if (obj.classList.contains('cover')) {
        var mask = document.getElementById('mask_container');
        showItem(mask, !b);
    }
}
function showHidePreview()
{
    var bShowPreviewBtn = true;    
    if (g_onlyHtmlDebug) {
        willShowPreview();
        var preview = document.getElementById('preview');
        preview.onclick = function () { willShowPreview(); }
    } else {
        bShowPreviewBtn = parent.dataFromMain('willShowPreviewBtn');
    }
    var previewBtn = document.getElementById('previewBtn');
    //console.log('btn:' + previewBtn + ' willShow:' + bShowPreviewBtn);
    showItem(previewBtn, bShowPreviewBtn);
}
function createSndHeaderItem()
{
    var firstFrm = document.getElementById('item_frame');
    var frm = firstFrm.cloneNode(true);
    document.getElementById('main').appendChild(frm);
    var offset = new Number(firstFrm.clientHeight);
    var marginTop = '-webkt-calc(-100% + ';
    marginTop += offset.toString();
    marginTop += ')';
    frm.style.marginTop = marginTop;
    frm.style.marginRight = firstFrm.clientWidth;
    frm.style.float='left';
}
var g_isLoaded = false;
function load() {
    resetFirstHeaderItem();
    resetMultLauage();
    setTimeout(function () {
        prepareAlbumContent();
    }, 80);
    if (!g_onlyHtmlDebug) showHidePreview();
    createMovmentItem();
    listentContentEvt(document.getElementsByClassName('content_tab'));
    listentContentEvt(document.getElementsByClassName('cover'));
    listentContentEvt(document.getElementsByClassName('item_frame_second'));
    //createSndHeaderItem();
    g_isLoaded = true;
}
window.onload = function () {
    listentContentEvt(document.getElementsByClassName('main'));
    var src = previewBackgroundImg();
    if (g_onlyHtmlDebug) {
        showHidePreview();
    } else {
        if (src.length > 0) return;
        load();
    }
}
function makeItemID(prefix,albumIdx, itemIdx) {
    var albumID = Number(albumIdx);
    var itemID = Number(itemIdx);
    var id = prefix + '_' + albumID.toString() + '_' + itemID.toString();
    return id;
}
//function animationEnd(obj)
//{
//    if (obj.getAttribute('id') == 'main' /*&& g_btnPreviewClicked*/) {
//        if (!g_onlyHtmlDebug) {
//            parent.jsAction('backPreview');
//        }
//    } else if (obj.getAttribute('id') == 'preview') {
//        var preview = document.getElementById('preview');
//        if (!g_onlyHtmlDebug) {
//            preview.setAttribute('src', '');
//        }
//        obj.classList.remove('willHide');
//    }
//}
function updatePreview() {
    var src = previewBackgroundImg();
    var b = (src.length > 0);
    showHidePreview();
    if (parent.showHeader) parent.showHeader(!b);

}
function updatePercent(percent)
{
    var progress = document.getElementById('progress');
    showItem(progress,((percent > 0) && (percent < 100)));
    var n = new Number(percent)
    var pbar = document.getElementById('progress_bar');
    pbar.style.width = parseFloat(n) + '%';
}
function updateAlbumCnt(albumIdx, photoCount)
{
    var content = document.getElementById('content_album');
    prepareContentItem(content, albumIdx, g_item_id_all);
    prepareImgThubnail(albumIdx, g_item_id_all);
    updateItemCnt(albumIdx, photoCount);
}
function resize(width,height)
{
    //window.document.body.clientWidth = width;
    //window.document.body.clientHeight = height;
    window.resizeTo(width, height);
}
window.onresize = function () {
    //var previewImg = document.getElementById('previewImg');
    //previewImg.style.width = window.document.body.clientWidth;
    //previewImg.style.height = window.document.body.clientHeight;
    if (!g_isLoaded) return;
    var content = document.getElementById(g_current_album == g_item_id_all ? 'content_album' : 'content_photo');
    g_contentItemcounts = resetLastItem(content);
    onResetItemBackgroundImage(content);
    if (!g_itemMovment||(g_current_album == g_item_id_all)) return;
    var albumIdx = g_itemMovment.getAttribute('albumIdx');
    var itemIdx = g_itemMovment.getAttribute('itemIdx');
    changeItemMovePath(albumIdx, itemIdx);
}
function reloadPage()
{
    window.location.reload();
}