var srchWrdViewRange = 450;   //인기검색어 화면에 보이는 범위 (180px) : #header_search > div > div > div.txt
var srchWrdElmtSize = 0;  // 전체 인기검색어 size
var srchList = new Array();

$(document).ready(function () {

    loadTotalSearchWordSummaryList();

    $("#btnPrevFavorite").on("click", function() {
        fnMovePrev();
    });

    $("#btnNextFavorite").on("click", function() {
        fnMoveNext();
    });

});
function loadTotalSearchWordSummaryList() {

    $.ajax({
        url : $("#contextPath").val() + "/statics/home/json/totsrchwrdsmryList.json",
        cache : false,
        data : {},
        contentType : "application/x-www-form-urlencoded;charset=utf-8",
        type : "GET",
        async: true,
        beforeSend : function(xhr, opts) {
            //com.showProgressBar();
        },
        success : function(list) {
            //com.hideProgressBar();
            if (com.isNotEmpty(list)) {
                for (var i=0; i<list.length; i++) {
                    srchList.push(list[i]);
                }
            }
            fnRollToSrchwrd();
        },
        error : function(request, status, errorData) {
            //com.hideProgressBar();

            console.error("error code : " + request.status + "\n"
                + "message : " + request.responseText + "\n"
                + "error : " + errorData);
        }
    });

}

function fnRollToSrchwrd() {
    if (typeof srchList == 'undefined') {
        return;
    }
    if (srchWrdElmtSize == 0) {
        fnSrchWrdElDisplay();
    }
}
function fnSrchWrdElDisplay(){
    //1.0 node 제거
    $("#totsrchwrdsmryList").empty();

    //1.1. html 추가
    $.each(srchList, function(index,item){
        $("#totsrchwrdsmryList").append("<span><a href=\"javascript:void(0);\" onclick=\"fnTotalSearch('" + item.kwrd + "');\" title=\"" + item.kwrd + "에 대해 통합검색\">" + item.kwrd + "</a></span>");
    });

    //1.2. 인기검색어 화면에 보이는 범위 지정
    fnSpanOverWidthHide();
}
function fnMovePrev(){
    if(srchWrdElmtSize <= srchWrdViewRange){
        return;
    }
    srchList.unshift(srchList.pop());
    fnSrchWrdElDisplay();
}
function fnMoveNext(){
    if(srchWrdElmtSize <= srchWrdViewRange){
        return;
    }
    srchList.push(srchList.shift());
    fnSrchWrdElDisplay();
}
function fnSpanOverWidthHide(){
    var elmtSize = 0; //loop

    $("#totsrchwrdsmryList").children("span").each( function(idx){
        elmtSize += $(this).outerWidth();
        if( srchWrdViewRange < elmtSize){
            $(this).hide();
        }
    });
    srchWrdElmtSize = elmtSize;  //체크용
}

function fnTotalSearch(kwrd) {
    $("#totSearchValue").val(kwrd);
    $("#totalSearchForm").submit();
}