/*! Module Name : common_module
      version : 1.0
    Developer : daniel Park
    Description
    : 공통 기능수행 모듈 라이브러리...
*/

var ViewCount = 6;
var ViewPageCount = 5;
var SearchPoiAddressLength = 20;

var SUCCESS_CODE = 200;

var mapObj = null;
var mapController = null;
var mapObserverEvent = null;
var pointmarkId = 0;
var pointlineId =0;
var startPoint = null;
var endPoint = null;
var objPoiLink = null;	// 선그리기 객체
var distanceObj = null;	// 거리재기 객체

var points = 0;

var MENU_POI_SEARCH = 'search';
var MENU_CAR_SEARCH = 'carSearch';
var MENU_TRAFFIC_SEARCH = 'busSearch';

var currMenu;
var prevMenu;
var mapLang;
var eventTypes = ['resize','scroll','click','dblclick',
                    'mousedown','mouseup','mousemove','mouseover',
                    'mouseout','mouseenter','mouseleave'];

var carStartRouteControl = null;
var busStartRouteControl = null;

var initSX = null;
var initSY = null;
var initEX = null;
var initEY = null;
var initSName = null;
var initEName = null;
var initExecute = false;
var areaModule = null;

/// [이전메뉴] 공유 정보
var prevInfo = null;
var poiInfo = null;

/**
 * click Event Declear....
 */

//initMap('<%=szLanguage %>', '<%=szLong %>', '<%=szLat %>', '<%=szMenu %>', '<%=szLevel %>');">" +

function initMap(_language, x, y, _menu, _level, sX, sY, eX, eY, sName, eName, poiX, poiY){
    /**
     * Map Init....
     */
    prevInfo = new prevMenuInformation();
    mapObserverEvent = new ObserverEvent();
    mapLang = _language;
    mapController = new MapController();
    mapObj = new SMap(document.getElementById('mapContainer'));
    var longitude = null;
    var latitude = null;
    var mapMenu = null;
    var mapLevel = null;

    if(_language!=null)
        mapLang = _language;
    else
        mapLang = 'kor';

    if(x!=null)
        longitude = x;
    else
        longitude = 126.97872766;

    if(y!=null)
        latitude = y;
    else
        latitude = 37.5660686;

    if(_menu!=null)
        mapMenu = covertMenu(_menu);
    else
        mapMenu = 'search';

    if(_level!=null)
        mapLevel = _level;
    else
        mapLevel = 1;

    if (sX!=null){
        initSX = sX;
    }
    if (sY!=null){
        initSY = sY;
    }
    if (eX!=null){
        initEX = eX;
    }
    if (eY!=null){
        initEY = eY;
    }
    if (!sName || sName!='null'){
        initSName = sName;
    }
    if (!eName || eName!='null'){
        initEName = eName;
    }

    if (poiX!='null' && poiY!='null'){
        makePoi_Init(poiX, poiY);
    }
    mapObj.setZoom(parseInt(_level));

    i18NObj = new InternationalService({'map': mapObj});
    _mapLang(mapLang);
    mapObj.setCenter(new SPoint(longitude, latitude, 'WGS84_Degree'));

    changeLanguage(mapLang, mapMenu);

    var zc = new SZoomControl();
    mapObj.addControler(zc);

    mapObj.setDrag(true);
    mapObj.ZoomWheel(true);

    var mm = new SMiniMap();
    mapObj.addControler(mm);

//	var mousepointer = new SMousePointer();
//	mapObj.addControler(mousepointer);

    $("#Image30").attr("src", "images/index/lang_kor_p.gif");
    $("#Image30").unbind("mouseout", MM_swapImgRestore);
    $("#Image31").bind("mouseout", MM_swapImgRestore);
    $("#Image32").bind("mouseout", MM_swapImgRestore);
    $("#Image33").bind("mouseout", MM_swapImgRestore);
    $("#Image34").bind("mouseout", MM_swapImgRestore);
    $('#map_error > a').html(i18NObj.getTextValue('question'));

    areaModule = new AreaModule(mapObj);
    areaModule.execute();
};

/**
 * 지역 정보 가져오기
 * @param map
 */
AreaModule = function(map){
    this.map = map;
    this.centerPoint = null;
    this.init();
};

AreaModule.prototype = {
    init: function(){
        SEvent.mapEventHandler('mouseup', this.execute, this);
        SEvent.mapEventHandler('redraw', this.execute, this);
    },
    execute: function(){
        var eventCoord = this.map.getCenter();

        if(!this.centerPoint){
            this.centerPoint = eventCoord;
        }
        else{
            if(this.centerPoint.equals(eventCoord)){
                return;
            }

            this.centerPoint = eventCoord;
        }

        this.ajaxLoad();
    },
    ajaxLoad: function(){
        var paramF = 'json';
        var paramKey = '';
        var paramRq = 'reversegeocoding';
        var paramLang = mapLang;
        var wgs84Cooord = TMtoWGS84(this.centerPoint.x, this.centerPoint.y);
        var paramPoint = wgs84Cooord.x + ',' + wgs84Cooord.y;

        var paramInfo = 'f=' + paramF // + '&key=' + paramKey
        +
        '&rq=' +
        paramRq +
        '&lang=' +
        paramLang +
        '&point=' +
        paramPoint;

        var resultAddressName = '';
        var thisObject = this;

        $.ajax({
            type: "POST",
            url: AJAX_MAP_OPEN_API,
            data: "svcCode=uTourOnion&" + paramInfo,
            async: true,
            dataType: "json",
            success: function(data){
                thisObject.returnReverseGeocoding.call(thisObject, data);
            }
        });
    },
    returnReverseGeocoding: function(data){
        var resultData = "";

        if (!data){
            return;
        }

        if (!data.Mapot.Response.ReverseGeocoding.Placemark.name){
            return;
        }

        var resultData = data.Mapot.Response.ReverseGeocoding.Placemark.name.substring(data.Mapot.Response.ReverseGeocoding.Placemark.name.indexOf(",") +1);

		if(mapLang=='eng'){
			var tempResultData = resultData.split('>');
			resultData = '';
			
			for(var i=tempResultData.length; i>0; i--){
				if(i==1)
					resultData += tempResultData[i-1];
				else
					resultData += tempResultData[i-1] + ',';  
			}
		}
		else{
	        resultData = ReplaceAll(resultData, ',', ' > ');
	        resultData = ReplaceAll(resultData, 'null', ' > ');
		}
		
//    	if (resultData.length > SearchPoiAddressLength)
//        	resultData = resultData.substring(0, SearchPoiAddressLength) + '..';

        this.viewResult(resultData);
    },
    viewResult: function(data){
        //$('#redbar > div').html(data);
        $('#blackbar > div').html(data);
    }
};

function changeLanguage(_lang, _menu){
    var tempMenu = '';
    debugger;
    if(_menu!=null)
        tempMenu = _menu;
    else
        tempMenu = currMenu;

    i18NObj.setLang(_lang);
    LoadMenu(tempMenu);
}


function changeGo(_lang){
    var Rq = null;
    var coord = mapObj.getCenter('WGS84_Degree');
    var lv = mapObj.getZoom();
    Rq = RecovertMenu(currMenu);

    location.href='/index.jsp?lang=' + _lang + '&Rq='+ Rq
                   + '&centerX=' + coord.x
                   + '&centerY=' + coord.y
                   + '&mapLevel='+ lv;
}



function _mapLang(_lang){
    mapLang = _lang;
    mapObj.setI18N(i18NConvertService(_lang));
    $('#mapLang').attr('value', _lang);
}

/**
 * Map Controller
 * @param _mapObj
 */
MapController = function(_mapObj){
    //this.mapObj=_mapObj;
    this.onResizeTimer = null;
    this.onResizeFlag = false;
    this.eventBinding();
    this.init();
};

MapController.prototype = {
    init: function(){
        this.onResizing();
        this.eventBinding();
    },
    onResizing: function(){
        var resizeDivWidthObject = ["mapContainer", "blackbar", "copyright"];
        var resizeDivHeightobject = ["mapContainer", "infoback", "map_error", "copyright"];

        var windowWidht = $(window).width();
        var windowHeight = $(window).height();
        var rightWidth = 289;
        var rightHeight = 119;

        var index1;
        var index2;

        for (index1 in resizeDivWidthObject) {
            var divInfo = $('#' + resizeDivWidthObject[index1]);
            divInfo.width(windowWidht - rightWidth);
        };

        for (index2 in resizeDivHeightobject) {
            var divInfo = $('#' + resizeDivHeightobject[index2]);
            if (resizeDivHeightobject[index2] == 'map_error' || resizeDivHeightobject[index2] == 'copyright')
                divInfo.offset.top = windowHeight - divInfo.height();
            else
                divInfo.height(windowHeight - rightHeight);
        };
            },
    eventBinding: function(){
        $(window).bind('resize', this.onResizing);
    }
};

/**
 * 검색/PoiSearch Display/Hidden 창
 * @param _visible
 * @return
 */
function displaySearchPoiPannel(_visible){
    if (_visible) {
        $('#ifr_sch_result').show();
        $('#searchleftinfo').hide();
    }
    else {
        $('#ifr_sch_result').hide();
        $('#searchleftinfo').show();
    }
}

/**
 * 메뉴 선택...
 * @param {Object} _varMenu
 */
function LoadMenu(_varMenu){
    var _tempMenu = _varMenu;
    $("#leftMenu").empty();

    LoadMenu_Common(_varMenu);

    // 1.1 [이전메뉴] 상태 저장.
    prevMenu = currMenu;

    switch (_tempMenu) {
        case MENU_POI_SEARCH:
            unLoadCarModule();
            unLoadBusModule();
            unLoadTrafficModule();
            LoadMenu_Category();
            currMenu = MENU_POI_SEARCH;
            break;
        case MENU_CAR_SEARCH:
            prevMenuCoordSave(_varMenu);
            unLoadCarModule();
            unLoadBusModule();
            unLoadTrafficModule();
            LoadMenu_CarSearch();
            currMenu = MENU_CAR_SEARCH;
            break;
        case MENU_TRAFFIC_SEARCH:
            prevMenuCoordSave(_varMenu);
            unLoadCarModule();
            unLoadBusModule();
            unLoadTrafficModule();
            LoadMenu_TrafficSearch();
            currMenu = MENU_TRAFFIC_SEARCH;
            break;
        default:
            LoadMenu_Category();
            currMenu = MENU_POI_SEARCH;
            break;
    }
}

// [이전 메뉴] 좌표 정보 공유하기.
function prevMenuCoordSave(nextMenu){
    prevInfo.reset();

    if(prevMenu == MENU_CAR_SEARCH &&
            nextMenu == MENU_TRAFFIC_SEARCH){
        if(!carStartRouteControl)
          return;

        if(carStartRouteControl.startPointCoord!=null){
            prevInfo.setStartPoint(carStartRouteControl.startPointCoord);
            prevInfo.startText = carStartRouteControl.TextBoxModule.getStartBoxValue();
        }

        if(carStartRouteControl.endPointCoord!=null){
            prevInfo.setEndPoint(carStartRouteControl.endPointCoord);
            prevInfo.endText = carStartRouteControl.TextBoxModule.getEndBoxValue();
        }
    }
    else if(prevMenu == MENU_TRAFFIC_SEARCH &&
            nextMenu == MENU_CAR_SEARCH){
        if(!busStartRouteControl)
          return;

        if(busStartRouteControl.startPointCoord!=null){
            prevInfo.setStartPoint(busStartRouteControl.startPointCoord);
            prevInfo.startText = busStartRouteControl.TextBoxModule.getStartBoxValue();
        }

        if(busStartRouteControl.endPointCoord!=null){
            prevInfo.setEndPoint(busStartRouteControl.endPointCoord);
            prevInfo.endText = busStartRouteControl.TextBoxModule.getEndBoxValue();
        }
    }
};

// [이전 메뉴] 정보 객체..
prevMenuInformation = function(){
    this.startPoint = new SPoint(0,0);
    this.endPoint = new SPoint(0,0);
    this.startText = null;
    this.endText = null;
};
prevMenuInformation.prototype = {
    reset: function(){
        this.startPoint.set(0,0);
        this.endPoint.set(0,0);
        this.startText = null;
        this.endText = null;
    },
    setStartPoint: function(_paramStart){
        this.startPoint.set(_paramStart.x, _paramStart.y);

    },
    setEndPoint: function(_paramEnd){
        this.endPoint.set(_paramEnd.x, _paramEnd.y);
    },
    isInitStartValue: function(){
        if(this.startPoint.x==0 && this.startPoint.y==0)
            return true;
        else
            return false;
    },
    isInitEndValue: function(){
        if(this.endPoint.x==0 && this.endPoint.y==0)
            return true;
        else
            return false;
    }
};


/**
 * 자동차 길찾기 검색 Html Loading...
 */
function CarSearchModuleView(_view){
        $mapClick = $("#map_click");
        if(_view)
            $mapClick.show();
        else
            $mapClick.hide();
}

/**
 * 자동차 길찾기 검색 Html Loading...
 */
function LoadMenu_CarSearch(){
    // Car Search Unload...
    //CarSearchModuleView(true);

    executeAjaxDetail('/include/'+ mapLang +'/carSearch_LeftMenu.htm', false, function(data){
        deleteAllPoiResult();
        $('#leftMenu').html(data);

        carStartRouteControl = new CarRouteServiceModule({
              map: mapObj,
            mapLayerId: 'mapContainer',
            startPlag: new CarRouteSearchControl({
                divId:'map_click',
                buttonId:'click_start',
                inputBoxId:'carSearchStartTxt'
            }),
            endPlag: new CarRouteSearchControl({
                divId:'map_click',
                buttonId:'click_end',
                inputBoxId:'carSearchEndTxt'
            }),
            inputStartTxtId: 'carSearchStartTxt',
            searchStartBtnId: 'searchStartCarBtn',
            inputEndTxtId: 'carSearchEndTxt',
            searchEndBtnId: 'searchEndCarBtn',
            routeBtnId: 'carroutebtn',
            carResetBtnId: 'carResetBtn',
            pageNumId: 'pageNum',
            languageId: 'mapLang',
            unLoadId: 'car_result'
        });
    });

    // 초기값 설정하기...
    if(!initExecute){
        initExecute = true;

        if(!initEX || !initEY || !initSName|| !initEName)
            return;

        // 바로 실행하기
        carStartRouteControl.initExecute(initSX , initSY ,initEX ,initEY, initSName, initEName);
    }

    // [이전 메뉴 정보]가 세팅되어 있다면 초기값 전달 수행...
    if(!prevInfo.isInitStartValue()){
        carStartRouteControl.initStartParam(prevInfo.startPoint.x, prevInfo.startPoint.y, prevInfo.startText);
    }

    if(!prevInfo.isInitEndValue()){
        carStartRouteControl.initEndParam(prevInfo.endPoint.x, prevInfo.endPoint.y, prevInfo.endText);
    }
}

/**
 * 대중교통 길찾기 검색 Html Loading...
 */
function LoadMenu_TrafficSearch(){
    executeAjaxDetail('/include/'+ mapLang +'/trafficSearch_LeftMenu.htm', false, function(data){
        deleteAllPoiResult();
        $('#leftMenu').html(data);

        busStartRouteControl = new BusRouteServiceModule({
              map: mapObj,
            mapLayerId: 'mapContainer',
            startPlag: new BusRouteSearchControl({
                divId:'map_click',
                buttonId:'click_start',
                inputBoxId:'busSearchStartTxt'
            }),
            endPlag: new BusRouteSearchControl({
                divId:'map_click',
                buttonId:'click_end',
                inputBoxId:'busSearchEndTxt'
            }),
            inputStartTxtId: 'busSearchStartTxt',
            searchStartBtnId: 'searchStartBusBtn',
            inputEndTxtId: 'busSearchEndTxt',
            searchEndBtnId: 'searchEndBusBtn',
            routeBtnId: 'busroutebtn',
            busResetBtnId: 'busResetBtn',
            pageNumId: 'pageNum',
            languageId: 'mapLang',
            unLoadId: 'bus_result'
        });
    });

    // 초기값 설정하기...
    if(!initExecute){
        initExecute = true;

        if(!initEX || !initEY || !initSName|| !initEName)
            return;

        // 바로 실행하기
        busStartRouteControl.initExecute(initSX , initSY ,initEX ,initEY, initSName, initEName);
    }

    // [이전 메뉴 정보]가 세팅되어 있다면 초기값 전달 수행...
    if(!prevInfo.isInitStartValue()){
        busStartRouteControl.initStartParam(prevInfo.startPoint.x, prevInfo.startPoint.y, prevInfo.startText);
    }

    if(!prevInfo.isInitEndValue()){
        busStartRouteControl.initEndParam(prevInfo.endPoint.x, prevInfo.endPoint.y, prevInfo.endText);
    }
}


// Top HTML Loading...
function LoadMenu_Common(_varMenu){
    executeAjaxDetail('/include/'+ mapLang +'/common_TopMenu.htm', false, function(data){
        $('#mainmenu').empty();
        $('#mainmenu').html(data);

        var imgSrc = '';
        var tempImgSrc = '';

        switch (_varMenu) {
            case MENU_POI_SEARCH:
                hiddenPlagPoint();
                pushImgSrc = $('#searchbtn').attr('push');
                $('#searchbtn > a > img').attr('src', pushImgSrc);
                break;
            case MENU_CAR_SEARCH:
                viewPlagPoint();
                pushImgSrc = $('#carbtn').attr('push');
                $('#carbtn > a > img').attr('src', pushImgSrc);
                break;
            case MENU_TRAFFIC_SEARCH:
                viewPlagPoint();
                pushImgSrc = $('#bus').attr('push');
                $('#bus > a > img').attr('src', pushImgSrc);
                break;
        }
    });
}

function changeBus(_varKey) {
    $('#busleftinfo').show();
    deleteAllLineResult();
    $("#busnumber_result").empty();
    $("#busname_result").empty();

    switch (_varKey) {
        case 'no':
            $('#busSearchKey > a').text(i18NObj.getTextValue('inputBusNumberTitle'));
            $('#busSelectKey').attr('value', '1'); // 버스 번호 선택 값 1
            $('#busSearchTxt').attr('value', i18NObj.getTextValue('searchWordNoInputText')); // 버스 번호를 입력하세요 문구
            $('#busValueInit').attr('value', '0');
            $('#busleftinfo > img').attr('src', '/images/index2/'+ mapLang +'/bus_number_leftinfo.jpg');
            break;
        case 'name':
            $('#busSearchKey > a').text(i18NObj.getTextValue('inputBusStopNameTitle'));
            $('#busSelectKey').attr('value', '2');	// 정류장명 선택 값 2
            $('#busSearchTxt').attr('value', i18NObj.getTextValue('searchWordNameInputText')); // 정류장명을 입력하세요 문구
            $('#busValueInit').attr('value', '0');
            $('#busleftinfo > img').attr('src', '/images/index2/'+ mapLang +'/bus_name_leftinfo.jpg');
            break;
    }
}


/**
 * 카테고리 검색 페이지
 */
function LoadMenu_Category(){
    //CarSearchModuleView(false);

    executeAjaxDetail('/include/'+ mapLang +'/poiSearch_LeftMenu.htm', false, function(data){
        $('#leftMenu').html(data);
        deleteAllPoiResult();
        //categoryStyleCSS();
        resetFormField('form1');
        poiSearchStyleCSS();
        //SearchCategory1Depth(mapLang, '', false);
    });

    displaySearchPoiPannel(false);
}

// Language toggle..
function toggleLanguage(){
    var togglKey = $('#setLang').attr('key');

    if(togglKey=='1'){
        $('#setLang').show();
        $('#setLang').attr('key', '2');
    }else{
        $('#setLang').hide();
        $('#setLang').attr('key', '1');
    }
}

//bus key toggle..
function toggleBus(){
    var togglKey = $('#bussearchlist').attr('key');

    if(togglKey=='1'){
        $('#bussearchlist').show();
        $('#bussearchlist').attr('key', '2');
    }else{
        $('#bussearchlist').hide();
        $('#bussearchlist').attr('key', '1');
    }
}

ObserverEvent = function(){
};
ObserverEvent.prototype = {
    addEvent: function(_src, _type, _handler, _parent){
        var $src = _src;
        var eventType = _type;
        var parent = _parent;
        var handler = _handler

        $src.bind(eventType, function(event){
            handler.apply(parent, arguments);
        })
    },

    removeEvent: function(_src, _type){
           var $src = _src;
        $src.unbind(_type);
    }
}

function loadingJSModule(loadjs){
    $.getScript(loadjs);
}

function convertTrafficLang(_param){
    var lang = '';

    switch (_param) {
        case 'kor':
            lang = '0';
            break;
        case 'eng':
            lang = '1';
            break;
        case 'jan':
            lang = '2';
            break;
        case 'china_g':
            lang = '3';
            break;
        case 'china_b':
            lang = '4';
            break;
        default:
            lang = '0';
            break;
    }
    return lang;
}

function i18NConvertService(_param){
    var lang = '';

    switch (_param) {
        case 'kor':
            lang = 'ko';
            break;
        case 'eng':
            lang = 'en';
            break;
        case 'jan':
            lang = 'ja';
            break;
        case 'china_g':
            lang = 'zh-CN';
            break;
        case 'china_b':
            lang = 'zh-TW';
            break;
        default:
            lang = 'ko';
            break;
    }
    return lang;
}

function RecovertMenu(){
    var menu = null;

    switch (currMenu) {
        case MENU_POI_SEARCH:
            menu = 'searchPoi';
            break;
        case MENU_CAR_SEARCH:
            menu = 'searchRoute';
            break;
        case MENU_TRAFFIC_SEARCH:
            menu = 'searchTraffic';
            break;
        default:
            menu = 'searchPoi';
            break;
    }

    return menu;
}

function covertMenu(_menu){
    var menu = '';

    switch (_menu) {
        case 'searchPoi':
            menu = MENU_POI_SEARCH;
            break;
        case 'searchRoute':
            menu = MENU_CAR_SEARCH;
            break;
        case 'searchTraffic':
            menu = MENU_TRAFFIC_SEARCH;
            break;
        default:
            menu = MENU_POI_SEARCH;
            break;
    }
    return menu;
}
function ReplaceAll(Source, stringToFind, stringToReplace){
    var temp = Source;
    var index = temp.indexOf(stringToFind);
    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }
    return temp;
}

function ReplaceTrimAll(src){
    if(!src)
        return src;

     return src.replace(/\s/g,'');
}

/**
 * Loading Html...
 * @param {Object} id
 * @param {Object} url
 */
function loadHtml(id, url, callBackFunc){
    $('#'+ id).load(url, null, callBackFunc);
    return;
}

/**
 * Form Field Reset
 * @return
 */
function resetFormField(id){
    $('#'+id).each(function(){
        this.reset();
    });
}

/**
 * 1 픽셀 당 실제 맵 거리
 * @param _pixel
 * @return
 */
function MapPixelPerPoint(_pixel){
    var dp  = mapObj.spec.distancePerPixel(mapObj.getZoom());
    return dp*_pixel;
}

/**
 * 자동차 길찾기 모듈 해제하기
 * @return
 */
function unLoadCarModule(){
    if(carStartRouteControl!=null){
        carStartRouteControl.unLoadModule();
        carStartRouteControl = null;
    }
}

/**
 * 대중교통 길찾기 모듈 해제하기
 * @return
 */
function unLoadBusModule(){
    if(busStartRouteControl!=null){
        busStartRouteControl.unLoadModule();
        busStartRouteControl = null;
    }
}

/**
 * 버스번호/정류장명 검색 모듈 해제하기..
 * @return
 */
function unLoadTrafficModule(){
    deleteAllLineResult();
}

/**
 * 깃발 보이기
 */
function viewPlagPoint(){
    hiddenPlagPoint();
    $('#plag_click').append("<div style='position: absolute; top: 0pt; left: 0pt; z-index: 10; -moz-user-select: none;'></div>")
                    .children()
                    .append("<ul id='map_click' class='map_click' style='display'>")
                    .children()
                    .append("<li id='click_start' class='mclk_start' tag='mclk_start'/></li><li id='click_end' class='mclk_end' tag='mclk_end'/></li>");
}


/**
 * 깃발 숨기기
 */
function hiddenPlagPoint(){
    $('#plag_click').empty();
}

/**
 * 화면 최적화 시키기
 */
function setPoiLevelAndFitting(_screenX, _screenY, _minCoordX, _maxCoordX, _minCoordY, _maxCoordY){
    var level = 1;
    var pixelToCoordX = 0;
    var pixelToCoordY = 0;

    var centerCoord = new SPoint((_minCoordX+_maxCoordX)/2, (_minCoordY+_maxCoordY)/2);
    var distanceX = (_maxCoordX - _minCoordX)*1.1;
    var distanceY = (_maxCoordY - _minCoordY)*1.1;

    for(var index=mapObj.spec.minLevel; index<=mapObj.spec.maxLevel; index++)
    {
        pixelToCoordX = mapObj.spec.distancePerPixel(index)* _screenX;
        pixelToCoordY = mapObj.spec.distancePerPixel(index)* _screenY;

        if (distanceX<=pixelToCoordX && distanceY<=pixelToCoordY){
                level = index;
                break;
        }
    }

    mapObj.setCenterAndZoom(centerCoord, level);
    return level;
}


function periodLengthStart() {
    periodLengthInit(); // 초기화

    mapChangeCursor('/images/cursor/point_start.cur');  // 커서 바꾸기

    objPoiLink = new SPolyline();

    objPoiLink.opacity=0.5;
    objPoiLink.color='blue';
    objPoiLink.setWeight(5);

    mapObj.addOverlay(objPoiLink);

    // 맵 클릭 이벤트 호출
    SEvent.mapEventHandler('click', drawPoiClickEvent);


}

function periodLengthInit() {
    for (var idx=0; idx<pointmarkId;idx++) {
        mapObj.clearOverlay('poimark'+ idx);
    }

    for (idx=0; idx<pointlineId;idx++) {
        mapObj.clearOverlay('poiline'+ idx);
    }

    if (objPoiLink!=null)
        objPoiLink.unload();

    pointmarkId = 0;
    pointlineId = 0;
    startPoint = null;
    endPoint = null;

    SEvent.mapEventRemoveById('click', drawPoiClickEvent);

}

function drawPoiClickEvent(event) {
    drawSearchPoiView('poimark'+ (pointmarkId++), event.x, event.y, 25, 31, 'http://gis.mapot.co.kr:8080/images/index/i_mks_b.gif', 'top');
    SEvent.mapEventHandler('mousemove', drawPoiMoveEvent);
}

function drawPoiMoveEvent(event) {
       objPoiLink.setPoint(pointmarkId-1, new SPoint(event.x, event.y));
}


function drawSearchPoiView(_markId, _paramX, _paramY, _imageSizeX, _imageSizeY, _imageUrl, _align, _title){
    if (_align == null)
        _align = 'center';

    // 맵 아이콘 표시를 위한 설정값 세팅
    var poiPoint = new SPoint(_paramX, _paramY);   // 좌표 설정
    var poiImgSize = new SSize(_imageSizeX, _imageSizeY); // 이미지 크기 설정
    var poiCont = new SContent(_imageUrl, 'image', poiPoint, poiImgSize, true, _align, false);  // 아이콘 생성 객체 만들기
    var len = 0;

    endPoint = new SPoint(_paramX, _paramY);
    if(startPoint == null) {
        startPoint = new SPoint(_paramX, _paramY);
        len = 0;
    } else {
        len = COMMIFYKM(returnDistancePoi(startPoint, endPoint));
        startPoint = new SPoint(_paramX, _paramY);
    }

    // 입력 Content 영역..

    poiCont.setInfoContent(
            "<table border='0' cellspacing='0' cellpadding='0'>" +
            "<tr>" +
            "<td style='border:1px solid #565656;font-size:10px;background-color:#ffffff;'>" + len + "km</td>" +
            "</tr>" +
            "</table>"
    );

    var infowindow = new SInfoWindow();
    infowindow.set(poiPoint);


    if(points == 0) {
        mapObj.addOverlay(poiCont, true, false, _markId);
        points++;
        alert('1');
    } else {
        poiCont.SMark.setPoint(poiPoint);
    }

    objPoiLink.addPoints(new SPoint(startPoint.x, startPoint.y));

}

function mapChangeCursor(img) {
    var $mapObj = $('#mapContainer');
    if (!img) {
        $mapObj.children('div').css("cursor", "default");
    }
    else {
        $mapObj.children('div').css("cursor", "url('" + img + "'),default");
    }
}

function returnDistancePoi(_poiA, _poiB){
    var distanceValue = Math.sqrt((_poiA.x - _poiB.x) * (_poiA.x - _poiB.x)
             + (_poiA.y - _poiB.y) * (_poiA.y - _poiB.y));

    return parseInt(distanceValue);
}

function goGuide(){
    var popLeft = Math.floor($(window).width()/3);

    window.showModalDialog("/include/"+ mapLang +"/help/help_main.htm", 'helpPage',"center:1; dialogwidth:630px; dialogheight:580px; dialogleft:"+ popLeft +"px; dialogtop:250px; scroll:yes; resizable:yes; status:no;");
}

function goVoc(){
    var centerXY = mapObj.getCenter();
    var lang = mapLang;
    var popLeft = Math.floor($(window).width()/3);

    var param = 'centerX='+ centerXY.x + '&centerY=' + centerXY.y + '&lang=' + lang;

    window.showModalDialog("/voc/umap_voc.jsp?"+ param, "helpPage","center:1; dialogwidth:560px; dialogheight:500px; dialogleft:"+ popLeft +"px; dialogtop:250px; scroll:yes; resizable:yes; status:no;");
}

function goHome(){
    location.href='/index.jsp?lang='+ mapLang;
}

function goPrint(){
    var centerXY = mapObj.getCenter();
    var lang = mapLang;
    var popLeft = Math.floor($(window).width()/3);

    var param = 'centerX='+ centerXY.x + '&centerY=' + centerXY.y + '&lang=' + lang;

    window.showModalDialog("/print/map_print.jsp?"+ param, "helpPage","center:1; dialogwidth:730px; dialogheight:600px; dialogleft:"+ popLeft +"px; dialogtop:250px; scroll:yes; resizable:yes; status:no;");
}

function goSave(){
    var paramBound = mapObj.getBound();
    var paramLevel = mapObj.getZoom();
    var paramLang = mapLang;
    var paramImageType = 'png';


    var paramInfo = '?rq=imgsave&svcCode=uTourOnion&lang=' + paramLang +
                    '&mapLevel=' + paramLevel +
                    '&minx=' + parseInt(paramBound[0]) +
                    '&miny=' + parseInt(paramBound[3]) +
                    '&maxx=' + parseInt(paramBound[2]) +
                    '&maxy=' + parseInt(paramBound[1]) +
                    '&imgtype=' + paramImageType;

    if($('#pm5').children().is('iframe')){
        $('#pm5').empty();
    }

    $('<iframe></iframe>').appendTo('#pm5')
                          .attr({
                                'height':'0px',
                                'width':'0px',
                                'id':'saveBtnFrm',
                                'name':'saveBtnFrm'
                          })
                          .css('display', 'none');
    $('#saveBtnFrm').attr('src', AJAX_MAP_SAVE_OPEN_API + paramInfo);
}

function goDistance(){
    if(!distanceObj){
        distanceObj = new DistanceTool(mapObj);
    }

    distanceObj.execute();
}

function DistanceTool(map){
    this.map = map;
    this.status = DistanceTool.NO_ACTIVITY;

    this.distancePolyLineInfo = null;
    this.distanceInfoWindow = null;
    this.pointClickObj = null;	// 2차원 배열
    this.mainDiv = null;

    this.realPolyLine = null;

    this.init();
    this.indexArray = 0;
    this.pointClickObjIndex=0;
}

DistanceTool.NO_ACTIVITY = 0;
DistanceTool.ACTIVITY = 1;


DistanceTool.POINT_IE_RADIUS_OF_CIRCLE = 11;
DistanceTool.POINT_IE_WIDTH_OF_STROKE = 2;
DistanceTool.POINT_FF_RADIUS_OF_CIRCLE = 7;
DistanceTool.POINT_FF_WIDTH_OF_STROKE = 5;
DistanceTool.POINT_COLOR_OF_STROKE = 'red';
DistanceTool.POINT_FILLCOLOR_OF_STROKE = 'white';

DistanceTool.ADD_POINT_Y = -30;
DistanceTool.CURSOR = '/distance/scale.cur';

DistanceTool.prototype = {
    init: function(){
        this.distancePolyLineInfo = [];
        this.distanceInfoWindow = [];
        this.pointClickObj = [];
    },
    execute: function(){
        if (this.getStatus()==DistanceTool.NO_ACTIVITY){
            this.distancePolyLineInfo[this.indexArray] = new DistancePolyLine(this);
            this.distanceInfoWindow[this.indexArray] = new DistanceInfoWindow(this);
            this.pointClickObj[this.indexArray] = [];
            this.pointClickObjIndex=0;

            this.setStatus(DistanceTool.ACTIVITY);
            this._setCursor(true);

            if (this.mainDiv == null) {
                this.mainDiv = this.map.mkDiv(100);
            }

            SEvent.mapEventHandler('click', this.click, this);
            SEvent.mapEventHandler('rclick', this.end, this);
        }
    },
    click: function(eventName, eventCoord){
        this.distancePolyLineInfo[this.indexArray].addPoint(eventCoord);
        this.distanceInfoWindow[this.indexArray].addInfo(eventCoord);

        this._makeCircle(eventCoord);
    },
    _makeCircle: function(_point){
        if (enum_BrowserType.IE){
            this.pointClickObj[this.indexArray][this.pointClickObjIndex] = new SCircle(_point, DistanceTool.POINT_IE_RADIUS_OF_CIRCLE);
            this.pointClickObj[this.indexArray][this.pointClickObjIndex].setLineWeight(DistanceTool.POINT_IE_WIDTH_OF_STROKE );
        }
        else{
            this.pointClickObj[this.indexArray][this.pointClickObjIndex] = new SCircle(_point, DistanceTool.POINT_FF_RADIUS_OF_CIRCLE);
            this.pointClickObj[this.indexArray][this.pointClickObjIndex].setLineWeight(DistanceTool.POINT_FF_WIDTH_OF_STROKE );
        }
        this.pointClickObj[this.indexArray][this.pointClickObjIndex].setLineColor(DistanceTool.POINT_COLOR_OF_STROKE);
        this.pointClickObj[this.indexArray][this.pointClickObjIndex].setFillColor(DistanceTool.POINT_FILLCOLOR_OF_STROKE);
        this.map.addOverlay(this.pointClickObj[this.indexArray][this.pointClickObjIndex]);
        this.pointClickObjIndex++;
    },
    end: function(eventName, eventCoord){
        this.setStatus(DistanceTool.NO_ACTIVITY);
        SEvent.mapEventRemoveById('click', this.click);
        SEvent.mapEventRemoveById('mousemove', this.move);
        SEvent.mapEventRemoveById('rclick', this.end);

        this._makeCircle(eventCoord);
        this.distancePolyLineInfo[this.indexArray].addPoint(eventCoord);
        this.distancePolyLineInfo[this.indexArray].removeMovePolyLineLayer();
        this.distanceInfoWindow[this.indexArray].endInfo();


        this._setCursor(false);
        this.indexArray++;
    },
    setStatus: function(flag){
        this.status = flag;
    },
    getStatus: function(){
        return this.status;
    },
    move: function(eventName, eventCoord){
        this.distancePolyLineInfo[this.indexArray].setMovePoint(eventCoord);
        this.distanceInfoWindow[this.indexArray].moveInfo(eventCoord);
    },
    _setCursor: function(_flag){
        var $mapObj = $('#mapContainer');
        if (!_flag) {
            $mapObj.children('div').css("cursor", "default");
        }
        else {
            $mapObj.children('div').css("cursor", "url('" + DistanceTool.CURSOR + "'),default");
        }
    },
    unBindAll: function(){
        for(var i=0; i<this.indexArray; i++){
            this.unBind(i);
        }

        this.distancePolyLineInfo = null;
        this.distanceInfoWindow = null;
        this.pointClickObj = null;

        this.map = null;
    },
    unBind: function(_index){
        this.distancePolyLineInfo[_index].unBind();
        this.distancePolyLineInfo[_index] = null;

        this.distanceInfoWindow[_index].unBind();
        this.distanceInfoWindow[_index]=null;

        for(var i=0; i<this.pointClickObj[_index].length; i++){
            this.pointClickObj[_index][i].unload();
            this.map.clearOverlays(this.pointClickObj[_index][i]);
        }
        this.pointClickObj[_index] = null;
    }
}

function DistanceInfoWindow(parentObj){
    this.parentObj = parentObj;
    this.map = parentObj.map;

    this.currPoint = null;
    this.prevPoint = null;

    this.resultInfo = null;
    this.resultTextObj = null;
    this.tempTotalDistance = 0;

    this.startInfo = null;
    this.walkInfo = [];
    this.walkInfoArray = 0;

    this.init();
}

DistanceInfoWindow.OFFSET_POINT_X = 0;
DistanceInfoWindow.OFFSET_POINT_Y = 9;
DistanceInfoWindow.OFFSET_POINT_MINUS_Y = -25;
DistanceInfoWindow.OFFSET_POINT_MINUS_2_Y = -35;

DistanceInfoWindow.OFFSET_RESULT_POINT_X = 60;
DistanceInfoWindow.OFFSET_RESULT_POINT_Y = -50;

DistanceInfoWindow.WALK_AVERAGE_DISTANCE = 4000;

DistanceInfoWindow.prototype = {
    init: function(){
        this.resultTextObj = {
            totalDistance: 0,
            walkingTime: null
        };

        this.resultInfo = new SInfoWindow();
        this.resultInfo.setOffset(
                new SSize(DistanceInfoWindow.OFFSET_RESULT_POINT_X,
                        DistanceInfoWindow.OFFSET_RESULT_POINT_Y));
        this.map.addOverlay(this.resultInfo, this.parentObj, this.map.pathLayer);
    },
    moveInfo: function(_point){
        this.currPoint = _point;

        this.resultInfo.setPoint(_point);
        this._computeDistance();
        this._resultTempInfoSetting();
    },
    addInfo: function(_point){
        if (!this.prevPoint){
            this.prevPoint = new SPoint(_point.x, _point.y);
            this.currPoint = new SPoint(_point.x, _point.y);
            this._startInfoWindow();
            this.resultInfo.showWindow();
        }
        else{
            this._addInfoWindow(_point);
        }
    },
    endInfo: function(){
        this._resultInfoSetting();
        this.resultInfo.setOffset(
                new SSize(DistanceInfoWindow.OFFSET_POINT_X,
                        DistanceInfoWindow.OFFSET_POINT_MINUS_2_Y));
        this.resultInfo.redraw();
    },
    _resultTempInfoSetting: function(){
        this.resultInfo.setContent('<div class="scaleboxResult">'+ i18NObj.getTextValue("resultDistance") +': ' + (this.tempTotalDistance/1000).toFixed(2) + 'km<br/>' +
                                    i18NObj.getTextValue("walkName") +': ' + this.resultTextObj.walkingTime + '</div>');
    },
    _resultInfoSetting: function(){
        var resultId = 'scaleboxResult'+ this.parentObj.indexArray;
        var resultCss = null;
        var thisObject = this;

        this.resultTextObj.totalDistance = this.tempTotalDistance;
        this.resultInfo.setContent('<div id="'+ resultId +'" class="scaleboxResult">'+ i18NObj.getTextValue("resultDistance") +': ' + (this.resultTextObj.totalDistance/1000).toFixed(2)  + 'km<br/>' +
                                    i18NObj.getTextValue("walkName") +': ' + this.resultTextObj.walkingTime + '</div>');

        if (enum_BrowserType.IE)
            resultCss = 'scaleboxClose';
        else
            resultCss = 'scaleboxCloseFF';


        $('<div></div>').appendTo('#'+ resultId)
                        .addClass(resultCss)
                        .append('<img></img>')
                        .children()
                            .attr('src', '/distance/close_btn.gif')
                            .attr('resultId', thisObject.parentObj.indexArray)
                            .css('cursor', 'pointer')
                            .click(function(){
                                var parentIndex = parseInt($(this).attr('resultId'));
                                thisObject.parentObj.unBind(parentIndex);
                            });
    },
    _startInfoWindow: function(){
        this.startInfo = new SInfoWindow();
        this.startInfo.setOffset(
                new SSize(DistanceInfoWindow.OFFSET_POINT_X,
                        DistanceInfoWindow.OFFSET_POINT_MINUS_Y));

        this.map.addOverlay(this.startInfo, this.parentObj, this.map.pathLayer);
        this.startInfo.showWindow();
        this.startInfo.setContent('<div class="scalebox">'+ i18NObj.getTextValue('start') +'</div>');
        this.startInfo.setPoint(this.currPoint);
    },
    _addInfoWindow: function(_point){
        this.resultTextObj.totalDistance = this.tempTotalDistance;
        this._computeDistance();

        this.walkInfo[this.walkInfoArray] = new SInfoWindow();

        if(this.prevPoint.y <= this.currPoint.y){
             this.walkInfo[this.walkInfoArray].setOffset(
                new SSize(DistanceInfoWindow.OFFSET_POINT_X,
                        DistanceInfoWindow.OFFSET_POINT_Y));
        }
        else{
            this.walkInfo[this.walkInfoArray].setOffset(
                new SSize(DistanceInfoWindow.OFFSET_POINT_X,
                        DistanceInfoWindow.OFFSET_POINT_MINUS_Y));
        }

        this.prevPoint = this.currPoint;
        this.currPoint = _point;

        this.map.addOverlay(this.walkInfo[this.walkInfoArray], this.parentObj, this.map.pathLayer);
        this.walkInfo[this.walkInfoArray].showWindow();

        this.walkInfo[this.walkInfoArray].setContent('<div class="scalebox">'+ (this.resultTextObj.totalDistance/1000).toFixed(2) +'km </div>');
        this.walkInfo[this.walkInfoArray].setPoint(this.currPoint);
        this.walkInfoArray++;
    },
    _computeDistance: function(){
        var totalDistance = Math.floor(this.resultTextObj.totalDistance +
                                (this.prevPoint.distance(this.currPoint)));


        var walkTime = (totalDistance/DistanceInfoWindow.WALK_AVERAGE_DISTANCE)*60;
        if(walkTime>60){
            var walkHour = Math.floor(walkTime/60);
            var walkMin = Math.floor(walkTime%60);
            if(mapLang=='eng'){
                if(walkMin>1)
                    this.resultTextObj.walkingTime = walkHour +
                                                i18NObj.getTextValue('hour') + walkMin + i18NObj.getTextValue('min(s)');
                else
                    this.resultTextObj.walkingTime = walkHour +
                                                i18NObj.getTextValue('hour') + walkMin + i18NObj.getTextValue('min');
            }
            else{
                this.resultTextObj.walkingTime = walkHour +
                                                i18NObj.getTextValue('hour') + walkMin + i18NObj.getTextValue('min');
            }
        }
        else{
            var walkMin = Math.floor(walkTime%60);
            if(mapLang=='eng'){
                if(walkMin>1)
                    this.resultTextObj.walkingTime = walkMin + i18NObj.getTextValue('min(s)');
                else
                    this.resultTextObj.walkingTime = walkMin + i18NObj.getTextValue('min');
            }
            else{
                this.resultTextObj.walkingTime = walkMin + i18NObj.getTextValue('min');
            }
        }

        this.tempTotalDistance = totalDistance;
    },
    unBind: function(){
        this.startInfo.unload();
        this.map.clearOverlays(this.startInfo);

        this.resultInfo.unload();
        this.map.clearOverlays(this.resultInfo);

        for(var i=0;i<this.walkInfo.length;i++){
            this.walkInfo[i].unload();
            this.map.clearOverlays(this.walkInfo[i]);
        }

        this.map = null;
    }
}

function DistancePolyLine(parentObj){
    this.parentObj = parentObj;
    this.map = parentObj.map;

    this.currPoint = null;
    this.prevPoint = null;

    this.realPolyLine = null;
    this.movePolyLine = null;

    this.distanceText = null;
    this.init();
}


DistancePolyLine.POLYLINE_COLOR = 'red';
DistancePolyLine.POLYLINE_REAL_OPACITY = 0.7;
DistancePolyLine.POLYLINE_MOVE_OPACITY = 0.3;
DistancePolyLine.POLYLINE_WEIGHT = 3;


DistancePolyLine.prototype = {
    init: function(){
        this.realPolyLine = new SPolyline();
        this.realPolyLine.drawArrow();
        this.realPolyLine.opacity=DistancePolyLine.POLYLINE_REAL_OPACITY;
        this.realPolyLine.color=DistancePolyLine.POLYLINE_COLOR;
        this.realPolyLine.setWeight(DistancePolyLine.POLYLINE_WEIGHT);

        this.map.addOverlay(this.realPolyLine);

        this.movePolyLine = new SPolyline();
        this.movePolyLine.drawArrow();
        this.movePolyLine.opacity=DistancePolyLine.POLYLINE_MOVE_OPACITY;
        this.movePolyLine.color=DistancePolyLine.POLYLINE_COLOR;
        this.movePolyLine.setWeight(DistancePolyLine.POLYLINE_WEIGHT);

        this.map.addOverlay(this.movePolyLine);
    },
    addPoint: function(_point){
        this.prevPoint = this.currPoint;
        this.currPoint = _point;

        this.realPolyLine.addPoints(_point);

        if (!this.prevPoint){
            this.movePolyLine.addPoints(_point.copy());
            this.movePolyLine.addPoints(_point.copy());

            SEvent.mapEventHandler('mousemove', this.parentObj.move, this.parentObj);
        }
        else{
            this.movePolyLine.setPoint(0, _point.copy());
        }
    },
    setMovePoint: function(_point){
        this.movePolyLine.setPoint(1, _point);
    },
    removeMovePolyLineLayer: function(){
        this.map.removeOverlay(this.movePolyLine);
        this.movePolyLine = null;
    },
    removeFixPolyLineLayer: function(){
        this.map.removeOverlay(this.realPolyLine);
        this.realPolyLine = null;
    },
    unBind: function(){
        if (this.realPolyLine!=null){
            this.removeFixPolyLineLayer();
        }

        if (this.movePolyLine!=null){
            this.removeMovePolyLineLayer();
        }

        this.map = null;
        this.parentObj = null;
    }
}

function resetMenu(){
    if(distanceObj!=null){
        distanceObj.unBindAll();
        distanceObj = null;
    }
    LoadMenu(currMenu);

    if(poiInfo!=null){
        mapObj.clearOverlays('point_POI_MARK');
    }
    poiInfo = null;
}

function makePoi_Init(x, y){
    var _align = 'top';

    var testPoint = new SPoint(x, y, 'WGS84_Degree');
    var testSize = new SSize(14, 37);
    poiInfo = new SContent('/sample/img/point.png', 'image', testPoint, testSize, true, _align, false);
    mapObj.addOverlay(poiInfo, false, false, 'point_POI_MARK');
}
