//유틸
function $(divId) {
        return document.getElementById(divId);
}

function stripTags(txt) {
        return txt.replace(/<[^>]+>/g, '');
}

function truncate(div, startIdx) {
        if (!startIdx) startIdx=0;
        if (!div) return;
        if (div.tagName == 'TABLE') {
                while (div.rows.length > startIdx)
                        div.deleteRow(startIdx);
        }else if (div.tagName == 'SELECT'){
                while (div.options.length > startIdx)
                        div.remove(startIdx);
        }else{
                while (div.childNodes.length > startIdx)
                        div.removeChild(div.childNodes[startIdx]);
        }
}

function appendNew(parent, tag, html, className, prepend) {
        if (!parent) return null;
        var el=document.createElement(tag);
        if (prepend) {
                if (parent.firstChild)
                        parent.insertBefore(el, parent.firstChild);
                else
                        parent.appendChild(el);
        }else
                parent.appendChild(el);
        if (html) {
                if (tag == 'IMG')
                        el.src=html;
                else
                        el.innerHTML=html;
        }
        if (className)
                el.className=className;
        return el;
}

function addEvent(element, event, callback) {
        if (_isIE)      element.attachEvent('on'+event, callback);
        else            element.addEventListener(event, callback, false);
}

function eventSrc(e) {
        return (_isIE)?e.srcElement:e.target;
}

function oFindParentByClassName(node, className) {
        if (!node || !className) return null;
        while (node && node.tagName != 'BODY') {
                if (node.className == className) return node;
                node=node.parentNode;
        }
        return null;
}

function numberFormat(nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
}

//휠로 줌 조정
function mapZoomByWheel(e) {
        if (!e || !gmap) return;
        if (e.wheelDelta >= 120)
                gmap.map.zoomIn();
        else if (e.wheelDelta <= -120)
                gmap.map.zoomOut();
}

//매쉬업 맵 객체
var MashMap_={};
function MashMap(mapDivID) {
        //지도사 표시될 element의 ID
        this.mapDiv=$(mapDivID);

        //인스턴스 체크를 위한 ID
        this.id='MASHMAP'+Math.round(Math.random()*100000);
        MashMap_[this.id]=this;

        this.timer;
        this.timer2;

        this.markerDokdo;
        this.markerBaekdu;
        this.paning=false;

        //구글맵 초기화
        this.map=new GMap2(this.mapDiv);
                this.map.enableDragging();
                this.map.enableInfoWindow();
                this.map.enableContinuousZoom();
                this.map.setCenter(new GLatLng(37.539133, 126.929169), 4);

                //지도 타입 선택
                //this.map.setMapType(gmap.getMapTypes()[2]);

                //콘트롤 등록
                this.map.addControl(new GLargeMapControl());
                this.map.addControl(new GMapTypeControl());
                //this.map.addControl(new GSmallMapControl());
                //this.map.addControl(new GScaleControl());

                //이번트 등록

                //휠 -> 줌 이벤트
                //addEvent(mapDiv, 'mousewheel', mapZoomByWheel);

                var id=this.id;
                GEvent.addListener(this.map, 'moveend', function () {
                        MashMap_[id].timer2=setTimeout('MashMap_["'+id+'"].hidePlane();', 50);
                });
                GEvent.addListener(this.map, 'movestart', function () {
                        MashMap_[id].showPlane();
                });

        //지점
        this.pointStart=this.pointEnd=new GLatLng(airports['ICN'].x, airports['ICN'].y);

        //마커
        this.markerStart=new GMarker(this.pointStart);
                var clickFunc1='MashMap_["'+this.id+'"].showInfo("start")';
                GEvent.addListener(this.markerStart, 'click', function () {
                        setTimeout(clickFunc1, 0);
                });
        this.markerEnd=new GMarker(this.pointEnd);
                var clickFunc2='MashMap_["'+this.id+'"].showInfo("end")';
                GEvent.addListener(this.markerEnd, 'click', function () {
                        setTimeout(clickFunc2, 0);
                });

        //뽀나쓰
        //독도
        this.markerDokdo=new GMarker(new GLatLng(37.501079, 130.859528));
                var clickFunc3='MashMap_["'+this.id+'"].showInfo("dokdo")';
                GEvent.addListener(this.markerDokdo, 'click', function () {
                        setTimeout(clickFunc3, 0);
                });
        //백두산
        this.markerBaekdu=new GMarker(new GLatLng(42.002621, 128.050976));
                var clickFunc4='MashMap_["'+this.id+'"].showInfo("baekdu")';
                GEvent.addListener(this.markerBaekdu, 'click', function () {
                        setTimeout(clickFunc4, 0);
                });
        this.map.addOverlay(this.markerDokdo);
        this.map.addOverlay(this.markerBaekdu);

        this.selectedAirport='';

        //이동
        this.go = function(end) {
                if (!airports[end]) return;

                if (this.selectedAirport == end) {
                        if (!this.moveMapIng)
                                this.map.panTo(this.pointEnd);
                        return;
                }
                this.selectedAirport=end;
                //오버레이들 삭제
                this.map.clearOverlays();
                this.map.addOverlay(this.markerDokdo);
                this.map.addOverlay(this.markerBaekdu);

                //끝지점
                this.pointEnd=new GLatLng(airports[end].x, airports[end].y, true);

                //항로 그리기(직항만..)
                if (airports[end].country == '미국')
                        this.map.addOverlay(new GPolyline([this.pointEnd, this.pointStart], '#ff0000', 8));
                else
                        this.map.addOverlay(new GPolyline([this.pointStart, this.pointEnd], '#ff0000', 8));

                //시작 마커 표시
                this.markerStart.setPoint(this.pointStart);
                this.map.addOverlay(this.markerStart);

                //끝 마커 표시
                this.markerEnd.setPoint(this.pointEnd);
                this.map.addOverlay(this.markerEnd);

                //시작 지점으로 이동
                this.map.setCenter(this.pointStart, 4);

                //지도 이동 준비
                this.moveMapIng=true;
                this.moveMapStep=0;
                this.moveMapFrame=airports[end].frame?airports[end].frame:100;
                this.timer=setTimeout('MashMap.moveMap("'+this.id+'");', 10);

                //this.moveMapCancel();
        };

        //마커 인포 윈도우 보이기
        this.showInfo = function(pos) {
                switch (pos) {
                        case 'start':
                                this.markerStart.openInfoWindowHtml('<div class="info">출발지역<br>'+airports['ICN'].country+' : '+airports['ICN'].title+'</div>');
                        break;
                        case 'end':
                                if (!this.selectedAirport) return;
                                var end=this.selectedAirport;
                                this.markerEnd.openInfoWindowHtml('<div class="info">도착지역<br>'+airports[end].country+' : '+airports[end].title+'</div>');
                        break;
                        case 'dokdo':
                                this.markerDokdo.openInfoWindowHtml('<div class="info"><b>독도는 우리땅</b></div>');
                        break;
                        case 'baekdu':
                                this.markerBaekdu.openInfoWindowHtml('<div class="info"><b>백두산은 우리땅</b></div>');
                        break;
                }
        };

        //비행기 및 관련
        this.plane=appendNew(this.mapDiv.parentNode, 'DIV', '<img src="img/plane.gif">', 'planeicon');
        this.plane.style.display='none';
        this.showPlane = function() {
                if (this.moveMapIng) {
                        clearTimeout(this.timer2);
                        if (this.plane.style.display == 'none') {
                                this.plane.style.display='block';
                                this.plane.style.left=this.mapDiv.offsetLeft+(this.mapDiv.offsetWidth/2)+'px';
                        }
                        this.plane.style.top=this.mapDiv.offsetTop+(this.mapDiv.offsetHeight/2)-Math.round(Math.floor((this.moveMapStep > this.moveMapFrame/2)?this.moveMapFrame-this.moveMapStep:this.moveMapStep)/2)-this.plane.offsetHeight+'px';
                }
        };

        this.hidePlane = function() {
                this.plane.style.display='none';
        };

        //지도 이동 관련 변수
        this.moveMapIng=false;
        this.moveMapStep=0;
        this.moveMapFrame=0;

        //지도 이동 종료/취소
        this.moveMapCancel = function() {
                this.moveMapIng=false;
                this.moveMapStep=0;
                //this.map.removeOverlay(this.plane);
                this.map.panTo(this.pointEnd);
                this.showInfo('end');
        };

        /* AJAX */
        this.ajax=null;
        this.ajaxCallback;
        this.ajaxIng=false;
        this.ajaxPool=[];
        this.ajaxInit = function() {
                this.ajax = (window.XMLHttpRequest)?new XMLHttpRequest():(window.ActiveXObject?new ActiveXObject('Microsoft.XMLHTTP'):null);
        };

        //ajax 요청
        this.ajaxRequest = function(mode, postData, callback) {
                if (!this.ajax)
                        this.ajaxInit();
                if (!this.ajax)
                        return;

                if (this.ajaxIng) {
                        this.ajaxPool.push([mode, postData, callback]);
                        return;
                }

                this.ajaxCallback=callback;
                if (!postData) postData='';
                postData+='&mode='+mode+'&dummy='+Math.random();
                this.ajaxIng=true;
                this.ajax.open('POST', 'ajax.html', true);
                this.ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                this.ajax.setRequestHeader('Content-Length', postData.length);
                var id=this.id;
                this.ajax.onreadystatechange=function() {MashMap_[id].ajaxResponse();};
                this.ajax.send(postData);
        };

        //요청 대기중인 ajax 풀 진행
        this.ajaxPoolContinue = function() {
                var request=this.ajaxPool.shift();
                if (request) {
                        this.ajax.abort();
                        this.ajaxRequest(request[0], request[1], request[2]);
                }
        };

        //ajax 요청 완료 체크
        this.ajaxSuccess = function() {
                if (this.ajax && this.ajax.readyState == 4) {
                        this.ajaxIng=false;
                        if (this.ajax.status == 200 || this.ajax.status == 202)
                                return true;
                        else
                                setTimeout('MashMap_["'+this.id+'"].ajaxPoolContinue();', 10);
                }
                return false;
        };

        //ajax 응답 처리
        this.ajaxResponse = function() {
                if (!this.ajaxSuccess()) return;

                var tree={};
                if (this.ajax && this.ajax.responseXML && this.ajax.responseXML.documentElement) {
                        var root=this.ajax.responseXML.documentElement;
                        for (var node=root.firstChild; node; node=node.nextSibling) {
                                var data=this.ajaxGetTree(node);
                                if (node.nodeName == '#text') continue;
                                if (tree[node.nodeName])
                                        tree[node.nodeName].push(data);
                                else
                                        tree[node.nodeName]=[data];
                        }
                }

                if (this.ajaxCallback)
                        this.ajaxCallback(tree);
                this.ajaxCallback=null;
                this.ajaxPoolContinue();
        };

        //xml dom을 트리로 만들기
        this.ajaxGetTree = function(node) {
                if (!node) return null;
                var ret={};
                var data;
                for (var i=0; i < node.childNodes.length; i++) {
                        if (node.childNodes[i].hasChildNodes() && node.childNodes[i].firstChild.hasChildNodes())
                                data=this.ajaxGetTree(node.childNodes[i]);
                        else{
                                if (_isIE)
                                        data=node.childNodes[i].text;
                                else if (_isSafari) {
                                        if (node.childNodes[i].firstChild)
                                                data=node.childNodes[i].firstChild.nodeValue;
                                }else{
                                        var found=false;
                                        if (node.childNodes[i].hasChildNodes()) {
                                                for (var p=0; p < node.childNodes[i].childNodes.length; p++) {
                                                        if (node.childNodes[i].childNodes[p].nodeName != '#text' && node.childNodes[i].childNodes[p].nodeName != '#cdata-section') {
                                                                data=this._getTree(node.childNodes[i]);
                                                                found=true;
                                                                break;
                                                        }
                                                }
                                        }
                                        if (!found)
                                                data=node.childNodes[i].textContent;
                                }
                        }

                        var name=node.childNodes[i].nodeName;//.toLowerCase();
                        if (name == '#text') {
                                continue;
                                ret=data;
                        }else{
                                if (ret[name])
                                        ret[name].push(data);
                                else
                                        ret[name]=[data];
                        }
                }
                return ret;
        };
}

//지도 이동
MashMap.moveMap = function (id) {
        var instance=MashMap_[id];
        if (!instance) return;
        if (!instance.moveMapIng) return;

        clearTimeout(instance.timer);
        if (instance.moveMapStep >= instance.moveMapFrame) {
                instance.moveMapCancel();
                return;
        }
        instance.timer=setTimeout('MashMap.moveMap("'+id+'")', 0);

        instance.moveMapStep++;

        var start=instance.pointStart;
        var end=instance.pointEnd;

        var x=(end.lat()-start.lat())/(instance.moveMapFrame);
        var y=(end.lng()-start.lng())/(instance.moveMapFrame);

        //지도 이동
        var point=new GLatLng(start.lat()+(x*instance.moveMapStep), start.lng()+(y*instance.moveMapStep));
        instance.map.panTo(point);
}

//다음 할인항공권 API가 제공하는 공항의 목록과 좌표들
var airports={
        //대한민국
        ICN:{
                        x: 37.471605,
                        y: 126.455662,
                        title: '인천',
                        country: '대한민국'
                },
        //일본
        NGO:{
                        x: 35.25528,
                        y: 136.924438,
                        title: '나고야',
                        country: '일본',
                        frame: 30
                },
        TYO:{
                        x: 35.762053,
                        y: 140.379234,
                        title: '도쿄',
                        country: '일본',
                        frame: 30
                },
        OSA:{
                        x: 34.432017,
                        y: 135.243732,
                        title: '오사카',
                        country: '일본',
                        frame: 30
                },
        HND:{
                        x: 35.556667,
                        y: 139.767227,
                        title: '하네다',
                        country: '일본',
                        frame: 30
                },
        FUK:{
                        x: 33.586388,
                        y: 130.449997,
                        title: '후쿠오카',
                        country: '일본',
                        frame: 30
                },
        //중국
        CAN:{
                        x: 23.184444,
                        y: 113.265556,
                        title: '광주',
                        country: '중국',
                        frame: 30
                },
        PEK:{
                        x: 40.080276,
                        y: 116.585281,
                        title: '북경',
                        country: '중국',
                        frame: 30
                },
        SHA:{
                        x: 31.198055,
                        y: 121.336388,
                        title: '상해',
                        country: '중국',
                        frame: 30
                },
        SHE:{
                        x: 41.639999,
                        y: 123.48333,
                        title: '심양',
                        country: '중국',
                        frame: 30
                },
        SZX:{
                        x: 22.639166,
                        y: 113.811386,
                        title: '심천',
                        country: '중국',
                        frame: 30
                },
        CGQ:{
                        x: 43.906666,
                        y: 125.201385,
                        title: '장춘',
                        country: '중국',
                        frame: 30
                },
        TAO:{
                        x: 36.263332,
                        y: 120.376663,
                        title: '청도',
                        country: '중국',
                        frame: 30
                },
        TSN:{
                        x: 39.124168,
                        y: 117.34639,
                        title: '텐진',
                        country: '중국',
                        frame: 30
                },
        //필리핀
        MNL:{
                        x: 14.508611,
                        y: 121.019447,
                        title: '마닐라',
                        country: '필리핀',
                        frame:50
                },
        //싱가포르
        SIN:{
                        x: 1.356917,
                        y: 103.988419,
                        title: '싱가포르',
                        country: '싱가포르',
                        frame:50
                },
        //말레이시아
        KUL:{
                        x: 2.745578,
                        y: 101.709917,
                        title: '쿠알라룸프르',
                        country: '말레이시아',
                        frame:50
                },
        //타이완
        TPE:{
                        x: 25.079526,
                        y: 121.23635,
                        title: '타이페이',
                        country: '타이완',
                        frame:50
                },
        //홍콩
        HKG:{
                        x: 22.310502,
                        y: 113.918668,
                        title: '홍콩',
                        country: '홍콩',
                        frame:50
                },
        //미국
        NYC:{
                        x: 40.639531,
                        y: -73.774239,
                        title: '뉴욕',
                        country: '미국',
                        frame:200
                },
        LAX:{
                        x: 33.942886,
                        y: -118.411714,
                        title: '로스앤젤레스',
                        country: '미국',
                        frame:300
                },
        SFO:{
                        x: 37.618889,
                        y: -122.374725,
                        title: '샌프란시스코',
                        country: '미국',
                        frame:300
                },
        SEA:{
                        x: 47.448982,
                        y: -122.309311,
                        title: '시애틀',
                        country: '미국',
                        frame:300
                },
        CHI:{
                        x: 41.883056,
                        y: -87.766111,
                        title: '시카고',
                        country: '미국',
                        frame:300
                },
        AKL:{
                        x: 37.72139,
                        y: -122.220833,
                        title: '오클랜드',
                        country: '미국',
                        frame:300
                },
        //캐나다
        YVR:{
                        x: 49.19389,
                        y: -123.184448,
                        title: '벤쿠버',
                        country: '캐나다',
                        frame:300
                },
        //뉴질랜드
        CHC:{
                        x: -43.486668,
                        y: 172.53334,
                        title: '크라이스트처치',
                        country: '뉴질랜드',
                        frame:200
                },
        //영국
        LON:{
                        x: 51.47139,
                        y: -0.454444,
                        title: '런던',
                        country: '영국',
                        frame:200
                },
        //이탈리아
        ROM:{
                        x: 41.80201,
                        y: 12.246603,
                        title: '로마',
                        country: '이탈리아',
                        frame:200
                },
        MIL:{
                        x: 45.448366,
                        y: 9.277919,
                        title: '밀라노',
                        country: '이탈리아',
                        frame:200
                },
        //에스파냐
        MAD:{
                        x: 40.472023,
                        y: -3.562636,
                        title: '마드리드',
                        country: '에스파냐',
                        frame:200
                },
        //러시아
        MOW:{
                        x: 55.9725,
                        y: 37.414165,
                        title: '모스크바',
                        country: '러시아',
                        frame:200
                },
        //오스트리아
        VIE:{
                        x: 48.111207,
                        y: 16.576414,
                        title: '빈',
                        country: '오스트리아',
                        frame:200
                },
        //네덜란드
        AMS:{
                        x: 52.307777,
                        y: 4.7625,
                        title: '암스테르담',
                        country: '네덜란드',
                        frame:200
                },
        //스위스
        ZRH:{
                        x: 47.460725,
                        y: 8.554683,
                        title: '쮜리히',
                        country: '스위스',
                        frame:200
                },
        //프랑스
        PAR:{
                        x: 48.724998,
                        y: 2.368483,
                        title: '파리',
                        country: '프랑스',
                        frame:200
                },
        //독일
        FRA:{
                        x: 50.031113,
                        y: 8.576667,
                        title: '프랑크푸르트',
                        country: '독일',
                        frame:200
                },
        //오스트레일리아
        MEL:{
                        x: -37.673332,
                        y: 144.843613,
                        title: '멜버른',
                        country: '오스트레일리아',
                        frame:200
                },
        BNE:{
                        x: -27.386381,
                        y: 153.12285,
                        title: '브리즈번',
                        country: '오스트레일리아',
                        frame:200
                },
        SYD:{
                        x: -33.940755,
                        y: 151.174333,
                        title: '시드니',
                        country: '오스트레일리아',
                        frame:200
                }
};