/*! Module Name : poi_search.js
      version : 1.0
    Developer : daniel Park
    Description
    : poi 검색 기능수행.
*/

function goSearchResultPage(pageNum){
    $("#pageNum").attr('value', pageNum);
    SearchPOI();
}

function deletePoiSearchHtml(){
    $("#resultInfo").empty();
    $("#pageNavigation").empty();
    deleteAllPoiResult();
}

function searchPoiActionKeyPress(){
     if(event.keyCode == 13){
         searchPoiAction();
     }
    return false;
}

// search validation.
function searchPoiAction(){
    if ($('#poiSearchWord').attr('init')=='0'){
        alert(i18NObj.getTextValue('searchRequireText'));		// 검색어를 입력해 주세요
        return false;
    }

    if(!$("#poiSearchWord").val() || $("#poiSearchWord").val()==''){
        alert(i18NObj.getTextValue('searchRequireText'));		// 검색어를 입력해 주세요
        return false;
    }

    if ($('#poiSearchWord').val().length<2){
        alert(i18NObj.getTextValue('twoWordLengthRequire'));		// 2자 이상 입력 요청.
        return false;
    }

    if($("#mapArea").attr('checked')){
        var tempMbr = mapObj.getBound();
        var minXY = TMtoWGS84(tempMbr[0], tempMbr[3]);
        var maxXY = TMtoWGS84(tempMbr[2], tempMbr[1]);

        $("#mbr").attr('value', minXY.x + ',' + minXY.y + ',' + maxXY.x + ',' + maxXY.y);
    }
    else{
        $("#mbr").attr('value','');
    }

    $("#language").attr('value', mapLang);
    $("#pageNum").attr('value', 1);
    $("#cateName").attr('value', '');
    $("#searchOpt").attr('value', '0');
    displaySearchPoiPannel(true);
    SearchPOI();
}
//
//// Category POI Search...
//function searchCategoryAction(_category){
//	$("#searchOpt").attr('value', '1');
//	$("#pageNum").attr('value', 1);
//	$("#poiSearchWord").attr('value', '');
//	$("#cateName").attr('value', _category);
//	$("#language").attr('value', mapLang);
//	displaySearchPoiPannel(true);
//    SearchPOI();
//}

// POI검색  MAIN
function SearchPOI(){
    var varRq='poi';
    var varAdmin='';
    var varF='json';
    var varLang=$("#language").val();
    var varPage=$("#pageNum").val()+','+ViewCount;
    var varName=$("#poiSearchWord").val();

    var varParameter =  'f=' + varF
                       +'&rq=' + varRq
                       + '&lang=' + varLang
                       + '&page=' + varPage;

    if (varAdmin != '') {
        varParameter += '&name=' + varAdmin + ',' + varName;
    }
    else{
        varParameter += '&name=' + varName;
    }

     // [Loading...] start
    poiSearchLoadingAjax(true);
    executeAjaxArgument(true, varParameter, returnPoiSearch);
}

//POI 검색 - 결과
function returnPoiSearch(data){
    var resultCode = 0;
    var address;

     // [Loading...] Stop
    poiSearchLoadingAjax(false);

    deleteAllPoiResult();

    if (!data || !data.Mapot.Response.Poi.Placemark) {
        viewResultTotalCount(0);
        poiSearchNoData();
        return;
    }

    var totalCnt = data.Mapot.Response.Poi.Page.totalCnt;
    // Total Count view
    viewResultTotalCount(totalCnt);

    // Content View <div><ul>
    $("#resultInfo").append("<div id='sch_place' class='sch_place' style='background: transparent none repeat scroll 0% 0%" +
               " -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;'></div>");

    $('<ul></ul>').appendTo($("#sch_place"))
                    .attr('id', 'sch_place_sub')
                    .addClass('search_result');

    // Content Loop
    if (data.Mapot.Response.Poi.Placemark.length > 0) {
        $.each(data.Mapot.Response.Poi.Placemark, function(index, value){
            if (!value.address){
                tempAddress = '-';
            }else{
                var tempAddress = value.address.substring(value.address.indexOf(",")+1);

                if(mapLang=="china_g" || mapLang=="china_b")
                    tempAddress = trimAll(tempddress);
                else
                    tempAddress = ReplaceAll(tempAddress, ',', ' ');

                tempAddress = ReplaceAll(tempAddress, 'null', ' ');
            }

            viewPoiResultDetail(index, value.name, tempAddress, new SPoint(value.Point.coordinate[0], value.Point.coordinate[1], 'WGS84_Degree'));
        });
    }

    // Page Display
    viewPaging($('#pageNum').val(), totalCnt);
}

function poiSearchNoData(){
    $link = $("#resultInfo");
        $link.append("<div class='search_result'><ul><li>" + i18NObj.getTextValue('searchNotResult') + "</li></ul></div>");

}

function poiSearchLoadingAjax(flag){
    if (flag)
        $('#ajaxLoading').show();
    else
        $('#ajaxLoading').hide();
}

// Total Count Display
function viewResultTotalCount(_totalCount){
    deletePoiSearchHtml();
    var searchTxt = '';
    var tempTxt = '';

    if($("#searchOpt").val() == 0)
        searchTxt = $("#poiSearchWord").val();
    else{
        tempTxt = $("#cateName").val().split(',');
        searchTxt = tempTxt[1];
    }

    $link = $("#resultInfo");
    $link.append("<div class='result_title'>" +
            "<strong>'"+ searchTxt +"' "+ i18NObj.getTextValue('searchResultTitle') +
            " ("+ i18NObj.getTextValue('searchResultCountHead') + _totalCount + " " + i18NObj.getTextValue('searchResultCount') + ")</strong></div>");
}

// Poi View Delete...
function deleteAllPoiResult(){
    for (var idx=0; idx<ViewCount;idx++)
        mapObj.clearOverlay('searchResultPoi'+ idx);
}

// Row Data Display.
function viewPoiResultDetail(_idx, _poiName, _poiAddress, _poiPoint){
    $link = $("#sch_place_sub");

    $('<dl></dl>').attr('id', 'searchResultdl_'+ _idx)
                    .appendTo($link)
                    .append('<dd></dd>').children()
                        .html(_poiName).parent()
                    .append('<dd></dd>').children('dd:eq(1)')
                        .html(_poiAddress);

    $("#searchResultdl_"+ _idx).wrap("<li class='rst_list"+ (_idx+1) +"'></li>");
    $("#searchResultdl_"+ _idx).attr('coordX', _poiPoint.x)
                            .attr('coordY', _poiPoint.y);

    $clickInfo = $("#searchResultdl_"+ _idx);
    $clickInfo.css('cursor', 'pointer');
    $clickInfo.bind('click', function(){
        mapObj.setCenter(new SPoint($(this).attr('coordX'), $(this).attr('coordY')));
        return false;
    });

    var displayTitle = '';
    if (!_poiName || _poiName == '')
        displayTitle = _poiAddress;
    else
        displayTitle = _poiName;

    //Poi Viewing..
    makeSearchPoiView('searchResultPoi'+ _idx, _poiPoint.x, _poiPoint.y, 26, 33, '/images/mapPin/pin_s_'+ (_idx+1) +'.gif', 'top', displayTitle);
}

// Paging Display.
function viewPaging(_currentPage, _totalItemCount){
    var totalPage = Math.ceil(_totalItemCount/ViewCount);              // 총 페이징 갯수

    var currentStep = Math.ceil(_currentPage/ViewPageCount);           // 현 위치 Step
    var totalStep = Math.ceil(totalPage/ViewPageCount);                // 총 Step

    var prevPageMax = (currentStep-1)*ViewPageCount;
    var currPageMin = prevPageMax+1;
    var nextPageMin = (currentStep*ViewPageCount)+1;
    $link = $("#pageNavigation");
    $link.empty();

    // Prev Action
    if(currentStep>1){
        $('<a></a>').attr({
            'class': 'arrow_pre',
            'onfocus': 'this.blur()',
            'href': 'javascript:goSearchResultPage('+ prevPageMax +')'
        }).append("<img src='/images/index2/n_local_btn_32.gif' border='0' />")
          .appendTo($link);
    }


    // Real Item Display
    for(var index=0;
           index<ViewPageCount && currPageMin+index <= totalPage ;
           index++){
        if (_currentPage == (currPageMin+index)){
            $('<span></span>').addClass('current')
                             .html(currPageMin+index)
                             .appendTo($link)
                             .html((currPageMin+index));
        }
        else{
            $('<a></a>').attr({
                'onfocus': 'this.blur()',
                'href': 'javascript:goSearchResultPage('+ (currPageMin+index) +')'
            }).html(currPageMin+index)
             .appendTo($link);
        }
    }

    // Next Action.
    if (currentStep<totalStep){
        $('<a></a>').attr({
            'class': 'arrow_next',
            'onfocus': 'this.blur()',
            'href': 'javascript:goSearchResultPage('+ nextPageMin +')'
        }).append("<img src='/images/index2/n_local_btn_33.gif' border='0' />")
          .appendTo($link);
    }
}

//-------------------------------------------------------------------------------------------------//
//POI 단일 출력
function makeSearchPoiView(_markId, _paramX, _paramY, _imageSizeX, _imageSizeY, _imageUrl, _align, _title){
    mapObj.clearOverlays(_markId);

    if (_align == null)
        _align = 'bottom';

    var testPoint = new SPoint(_paramX, _paramY);
    var testSize = new SSize(_imageSizeX, _imageSizeY);
    var testCont = new SContent(_imageUrl, 'image', testPoint, testSize, true, _align, false);

    // Content 영역..
    testCont.setInfoContent(
            "<table border='0' cellspacing='0' cellpadding='0' align='center'>" +
            "<tr>" +
            "<td width='4'><img src='/images/index2/popup_left.gif' width='4' height='24'></td>" +
            "<td background='/images/index2/popup_side.gif'><div align='center'><font color='#FFFFFF' size='-1'>"+ _title +"</font></div></td>" +
            "<td width='4'><img src='/images/index2/popup_right.gif' width='4' height='24'></td>" +
            "</tr>" +
             "</table>" +
            "<table border='0' cellspacing='0' cellpadding='0' align='center'>" +
               "<tr>" +
            "<td><img src='/images/index2/popup_arrow.gif'></td>" +
            "</tr>" +
            "</table>"
//            '<div >' +
//            '<div style="display:inline;height:24px;">' +
//            '<span style="float:left;width:4px;height:24px;background-image:url(/images/index2/popup_left.gif);"></span>' +
//            '<span style="float:left;height:24px;background-image:url(/images/index2/popup_side.gif);"><div style="padding:5 5 5 4;font-size:12px; text-align:center; color:#FFFFFF;">'+ _title +'</div></span>' +
//            '<span style="float:left;width:4px;height:24px;background-image:url(/images/index2/popup_right.gif);"></span>' +
//            '</div>' +
//            '<div style="width:100%; text-align:center;"><img src="/images/index2/popup_arrow.gif"></div>' +
//            '</div>'
    );

    var infowindow = new SInfoWindow();
    infowindow.set(testPoint)

    mapObj.addOverlay(testCont, true, false, _markId);


    return testCont;
}
//-------------------------------------------------------------------------------------------------//

function poiSearchStyleCSS(){
    /**
     * Search View Setting
     */
    $('#poiSearchWord').attr('init', '0');
    $('#poiSearchWord').bind('focus', function(){
        $('#poiSearchWord').attr('init', '1');
        $('#poiSearchWord').attr('value', '');
        $('#poiSearchWord').unbind('focus');
    });
}

/*! Module Name : poi_search.js
      version : 1.0
    Developer : daniel Park
    Description
    : poi 검색 기능수행.
*/

function goSearchResultPage(pageNum){
    $("#pageNum").attr('value', pageNum);
    SearchPOI();
}

function deletePoiSearchHtml(){
    $("#resultInfo").empty();
    $("#pageNavigation").empty();
    deleteAllPoiResult();
}

function searchPoiActionKeyPress(){
     if(event.keyCode == 13){
         searchPoiAction();
     }
    return false;
}

// search validation.
function searchPoiAction(){
    if ($('#poiSearchWord').attr('init')=='0'){
        alert(i18NObj.getTextValue('searchRequireText'));		// 검색어를 입력해 주세요
        return false;
    }

    if(!$("#poiSearchWord").val() || $("#poiSearchWord").val()==''){
        alert(i18NObj.getTextValue('searchRequireText'));		// 검색어를 입력해 주세요
        return false;
    }

    if ($('#poiSearchWord').val().length<2){
        alert(i18NObj.getTextValue('twoWordLengthRequire'));		// 2자 이상 입력 요청.
        return false;
    }

    if($("#mapArea").attr('checked')){
        var tempMbr = mapObj.getBound();
        var minXY = TMtoWGS84(tempMbr[0], tempMbr[3]);
        var maxXY = TMtoWGS84(tempMbr[2], tempMbr[1]);

        $("#mbr").attr('value', minXY.x + ',' + minXY.y + ',' + maxXY.x + ',' + maxXY.y);
    }
    else{
        $("#mbr").attr('value','');
    }

    $("#language").attr('value', mapLang);
    $("#pageNum").attr('value', 1);
    $("#cateName").attr('value', '');
    $("#searchOpt").attr('value', '0');
    displaySearchPoiPannel(true);
    SearchPOI();
}
//
//// Category POI Search...
//function searchCategoryAction(_category){
//	$("#searchOpt").attr('value', '1');
//	$("#pageNum").attr('value', 1);
//	$("#poiSearchWord").attr('value', '');
//	$("#cateName").attr('value', _category);
//	$("#language").attr('value', mapLang);
//	displaySearchPoiPannel(true);
//    SearchPOI();
//}

// POI검색  MAIN
function SearchPOI(){
    var varRq='poi';
    var varAdmin='';
    var varF='json';
    var varLang=$("#language").val();
    var varPage=$("#pageNum").val()+','+ViewCount;
    var varName=$("#poiSearchWord").val();

    var varParameter =  'f=' + varF
                       +'&rq=' + varRq
                       + '&lang=' + varLang
                       + '&page=' + varPage;

    if (varAdmin != '') {
        varParameter += '&name=' + varAdmin + ',' + varName;
    }
    else{
        varParameter += '&name=' + varName;
    }

     // [Loading...] start
    poiSearchLoadingAjax(true);
    executeAjaxArgument(true, varParameter, returnPoiSearch);
}

//POI 검색 - 결과
function returnPoiSearch(data){
    var resultCode = 0;
    var address;

     // [Loading...] Stop
    poiSearchLoadingAjax(false);

    deleteAllPoiResult();

    if (!data || !data.Mapot.Response.Poi.Placemark) {
        viewResultTotalCount(0);
        poiSearchNoData();
        return;
    }

    var totalCnt = data.Mapot.Response.Poi.Page.totalCnt;
    // Total Count view
    viewResultTotalCount(totalCnt);

    // Content View <div><ul>
    $("#resultInfo").append("<div id='sch_place' class='sch_place' style='background: transparent none repeat scroll 0% 0%" +
               " -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;'></div>");

    $('<ul></ul>').appendTo($("#sch_place"))
                    .attr('id', 'sch_place_sub')
                    .addClass('search_result');

    // Content Loop
    if (data.Mapot.Response.Poi.Placemark.length > 0) {
        $.each(data.Mapot.Response.Poi.Placemark, function(index, value){
            if (!value.address){
                tempAddress = '-';
            }else{
                var tempAddress = value.address.substring(value.address.indexOf(",")+1);

                if(mapLang=="china_g" || mapLang=="china_b")
                    tempAddress = ReplaceAll(tempAddress, ',', '');
                else
                    tempAddress = ReplaceAll(tempAddress, ',', ' ');

                tempAddress = ReplaceAll(tempAddress, 'null', ' ');
            }

            viewPoiResultDetail(index, value.name, tempAddress, new SPoint(value.Point.coordinate[0], value.Point.coordinate[1], 'WGS84_Degree'));
        });
    }

    // Page Display
    viewPaging($('#pageNum').val(), totalCnt);
}

function poiSearchNoData(){
    $link = $("#resultInfo");
        $link.append("<div class='search_result'><ul><li>" + i18NObj.getTextValue('searchNotResult') + "</li></ul></div>");

}

function poiSearchLoadingAjax(flag){
    if (flag)
        $('#ajaxLoading').show();
    else
        $('#ajaxLoading').hide();
}

// Total Count Display
function viewResultTotalCount(_totalCount){
    deletePoiSearchHtml();
    var searchTxt = '';
    var tempTxt = '';

    if($("#searchOpt").val() == 0)
        searchTxt = $("#poiSearchWord").val();
    else{
        tempTxt = $("#cateName").val().split(',');
        searchTxt = tempTxt[1];
    }

    $link = $("#resultInfo");
    $link.append("<div class='result_title'>" +
            "<strong>'"+ searchTxt +"' "+ i18NObj.getTextValue('searchResultTitle') +
            " ("+ i18NObj.getTextValue('searchResultCountHead') + _totalCount + " " + i18NObj.getTextValue('searchResultCount') + ")</strong></div>");
}

// Poi View Delete...
function deleteAllPoiResult(){
    for (var idx=0; idx<ViewCount;idx++)
        mapObj.clearOverlay('searchResultPoi'+ idx);
}

// Row Data Display.
function viewPoiResultDetail(_idx, _poiName, _poiAddress, _poiPoint){
    $link = $("#sch_place_sub");

    $('<dl></dl>').attr('id', 'searchResultdl_'+ _idx)
                    .appendTo($link)
                    .append('<dd></dd>').children()
                        .html(_poiName).parent()
                    .append('<dd></dd>').children('dd:eq(1)')
                        .html(_poiAddress);

    $("#searchResultdl_"+ _idx).wrap("<li class='rst_list"+ (_idx+1) +"'></li>");
    $("#searchResultdl_"+ _idx).attr('coordX', _poiPoint.x)
                            .attr('coordY', _poiPoint.y);

    $clickInfo = $("#searchResultdl_"+ _idx);
    $clickInfo.css('cursor', 'pointer');
    $clickInfo.bind('click', function(){
        mapObj.setCenter(new SPoint($(this).attr('coordX'), $(this).attr('coordY')));
        return false;
    });

    var displayTitle = '';
    if (!_poiName || _poiName == '')
        displayTitle = _poiAddress;
    else
        displayTitle = _poiName;

    //Poi Viewing..
    makeSearchPoiView('searchResultPoi'+ _idx, _poiPoint.x, _poiPoint.y, 26, 33, '/images/mapPin/pin_s_'+ (_idx+1) +'.gif', 'top', displayTitle);
}

// Paging Display.
function viewPaging(_currentPage, _totalItemCount){
    var totalPage = Math.ceil(_totalItemCount/ViewCount);              // 총 페이징 갯수

    var currentStep = Math.ceil(_currentPage/ViewPageCount);           // 현 위치 Step
    var totalStep = Math.ceil(totalPage/ViewPageCount);                // 총 Step

    var prevPageMax = (currentStep-1)*ViewPageCount;
    var currPageMin = prevPageMax+1;
    var nextPageMin = (currentStep*ViewPageCount)+1;
    $link = $("#pageNavigation");
    $link.empty();

    // Prev Action
    if(currentStep>1){
        $('<a></a>').attr({
            'class': 'arrow_pre',
            'onfocus': 'this.blur()',
            'href': 'javascript:goSearchResultPage('+ prevPageMax +')'
        }).append("<img src='/images/index2/n_local_btn_32.gif' border='0' />")
          .appendTo($link);
    }


    // Real Item Display
    for(var index=0;
           index<ViewPageCount && currPageMin+index <= totalPage ;
           index++){
        if (_currentPage == (currPageMin+index)){
            $('<span></span>').addClass('current')
                             .html(currPageMin+index)
                             .appendTo($link)
                             .html((currPageMin+index));
        }
        else{
            $('<a></a>').attr({
                'onfocus': 'this.blur()',
                'href': 'javascript:goSearchResultPage('+ (currPageMin+index) +')'
            }).html(currPageMin+index)
             .appendTo($link);
        }
    }

    // Next Action.
    if (currentStep<totalStep){
        $('<a></a>').attr({
            'class': 'arrow_next',
            'onfocus': 'this.blur()',
            'href': 'javascript:goSearchResultPage('+ nextPageMin +')'
        }).append("<img src='/images/index2/n_local_btn_33.gif' border='0' />")
          .appendTo($link);
    }
}

//-------------------------------------------------------------------------------------------------//
//POI 단일 출력
function makeSearchPoiView(_markId, _paramX, _paramY, _imageSizeX, _imageSizeY, _imageUrl, _align, _title){
    mapObj.clearOverlays(_markId);

    if (_align == null)
        _align = 'bottom';

    var testPoint = new SPoint(_paramX, _paramY);
    var testSize = new SSize(_imageSizeX, _imageSizeY);
    var testCont = new SContent(_imageUrl, 'image', testPoint, testSize, true, _align, false);

    // Content 영역..
    testCont.setInfoContent(
            "<table border='0' cellspacing='0' cellpadding='0' align='center'>" +
            "<tr>" +
            "<td width='4'><img src='/images/index2/popup_left.gif' width='4' height='24'></td>" +
            "<td background='/images/index2/popup_side.gif'><div align='center'><font color='#FFFFFF' size='-1'>"+ _title +"</font></div></td>" +
            "<td width='4'><img src='/images/index2/popup_right.gif' width='4' height='24'></td>" +
            "</tr>" +
             "</table>" +
            "<table border='0' cellspacing='0' cellpadding='0' align='center'>" +
               "<tr>" +
            "<td><img src='/images/index2/popup_arrow.gif'></td>" +
            "</tr>" +
            "</table>"
//            '<div >' +
//            '<div style="display:inline;height:24px;">' +
//            '<span style="float:left;width:4px;height:24px;background-image:url(/images/index2/popup_left.gif);"></span>' +
//            '<span style="float:left;height:24px;background-image:url(/images/index2/popup_side.gif);"><div style="padding:5 5 5 4;font-size:12px; text-align:center; color:#FFFFFF;">'+ _title +'</div></span>' +
//            '<span style="float:left;width:4px;height:24px;background-image:url(/images/index2/popup_right.gif);"></span>' +
//            '</div>' +
//            '<div style="width:100%; text-align:center;"><img src="/images/index2/popup_arrow.gif"></div>' +
//            '</div>'
    );

    var infowindow = new SInfoWindow();
    infowindow.set(testPoint)

    mapObj.addOverlay(testCont, true, false, _markId);


    return testCont;
}
//-------------------------------------------------------------------------------------------------//

function poiSearchStyleCSS(){
    /**
     * Search View Setting
     */
    $('#poiSearchWord').attr('init', '0');
    $('#poiSearchWord').bind('focus', function(){
        $('#poiSearchWord').attr('init', '1');
        $('#poiSearchWord').attr('value', '');
        $('#poiSearchWord').unbind('focus');
    });
}

