<?php
//跨域
$origin = 'https://map.projectzomboid.com';
header('Access-Control-Allow-Origin:' . $origin);
//http 根目录
$Http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';  
$Http =  $Http.$_SERVER['HTTP_HOST'];
$Http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';  
$Http =  $Http.$_SERVER['HTTP_HOST'];
preg_match('#([^:]+)/index.php#',$_SERVER['PHP_SELF'],$m);
$Http .= $m[1];

?>
<!DOCTYPE html>
<html lang='zh-cmn-Hans'>

<head>
  <title>Project Zomboid Map</title>
  <meta charset="utf-8">
  <link href="plugins/jquery/jquery-ui.css" rel="stylesheet">
  <link href="plugins/bootstrap.min.css" rel="stylesheet">
  <link href="footer.css" rel="stylesheet">
  <link href="dashboard.css" rel="stylesheet">
  <link href="socialshareprivacy/stylesheets/jquery.socialshareprivacy.min.css" rel="stylesheet">
  <link href="style.css" rel="stylesheet">
  <link href="plugins/jquery/jquery.cookiebar.css" rel="stylesheet" type="text/css">
  <meta name="google" content="notranslate" />
  <meta name="msapplication-config" content="none" />
  <!-- Extra code so IE and Chrome don't 404 the server -->
  <link rel="apple-touch-icon" href="empty.png" />
  <!-- Same for Apple... -->

<script type='text/javascript'>
var http = '<?=$Http?>';
</script>
  <script type='text/javascript' src="plugins/jquery-1.9.1.js"></script>
  <script type='text/javascript' src="plugins/jquery-ui.js"></script>
  <script type="text/javascript" src="plugins/openseadragon.js"></script>
  <!--min.-->

  <script type="application/x-social-share-privacy-settings">{"path_prefix":"socialshareprivacy/","layout":"line","uri":"https://map.projectzomboid.com/","services":{"buffer":{"status":false},"delicious":{"status":false},"disqus":{"status":false},"fbshare":{"status":false},"hackernews":{"status":false},"linkedin":{"status":false},"mail":{"status":false},"pinterest":{"status":false},"reddit":{"status":false},"stumbleupon":{"status":false},"tumblr":{"status":false},"xing":{"status":false},"flattr":{"status":false,"uid":"blindcoder"}}}</script>
</head>

<body>
<div id="wrap">
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-3 col-md-2 sidebar">
        <div id="left">
                <ul class="nav">
                  <li class="">
                    
                  </li>
                  <li class="none" style="display:none">
                    <nobr>Cell: <a id='cellX'>0</a>x<a id='cellY'>0</a></nobr>
                  </li>
                  <li class="none" style="display:none">
                    <nobr>Rel: <a id='relX'>0</a>x<a id='relY'>0</a></nobr>
                  </li>
                  <li class="none" style="display:none">
                    <a>
                      <button id="btnLockCoords" data-toggle="button" class="btn-overlay btn w100 btn-info">Lock Coords</button>
                    </a>
                  </li>
                  <li class="">
                    <div>
                          <div>
                            隐:
                            <button class="qg-btn btn btn-info hide-all">All</button>
                            <button class="qg-btn btn btn-info hide-qg">Qg</button>
                            <button class="qg-btn btn btn-info hide-sys">Sys</button>
                          </div>
                          <select class="selectlevel" id="SurvivalLevelChooser" desc="SurvivalLevelChooser">
                            <option value="5">5层</option>
                            <option value="4">4层</option>
                            <option value="3">3层</option>
                            <option value="2">2层</option>
                            <option value="1">1层</option>
                            <option value="0" selected>0层</option>
                          </select>
                           <strong>坐标：</strong>
                           <nobr><a href="#" id='coords'>0x0</a></nobr><br>
                               X: <input type="text" name="qg_pois_x" style="width:75px" class="qg_pois"> Y: <input type="text" name="qg_pois_y"  style="width:75px" class="qg_pois">
                           <input type="hidden" name="pointID">
                           <br><strong>标题：</strong><br>
                            <input type="text" name="qg_pois_name" style="font-size:1rem;width:100%">
                           <br><strong>描述：</strong><br>
                            <textarea name="qg_pois_comment" style="font-size:1rem;width:100%;height:50px"></textarea>
                            <a id="qgAddPoint" class="btn-overlay btn btn-info">添加</a> 
                            <a id="qgEditPoint" class="btn-overlay btn btn-warning">编辑</a>
                            <a id="qgDeletePoint" class="btn-overlay btn btn-danger">删除</a>
                            <br><strong>城市：</strong><br>
                                <select id="qgCitysSelect" size="1" class="w100"><option></option></select>
                            <br>
                            <div>
                                <div id="qgPoint">
                                    <input value="" type="text" name="filter" placeholder="过滤" style="font-size:1rem;width:100%">
                                    <ul></ul>
                                </div>
                            </div>
                    </div>
                  </li>

                </ul>
        </div><!-- left -->        
      </div>
      <!-- sidebar -->
      <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
        <div id='map'></div>
      </div>
    </div>
  </div>

  <div id="push"></div>
</div>
<script type='text/javascript' src="./qg/js/json2.js"></script>
<script type='text/javascript' src="plugins/bootstrap.min.js"></script>
<script type='text/javascript' src="plugins/docs.min.js"></script>
<script type='text/javascript' src="plugins/jstorage.js"></script>
<script type="application/javascript" src="qgFunc.js"></script>
<script type="application/javascript" src="pzmap.js"></script>
<script type="text/javascript" src="plugins/jquery/jquery.cookiebar.js"></script>
<!-- CookieBar -->
<!--[[
<script type="text/javascript">
    $(document).ready(function() {
        $.cookieBar({
            message: '我们使用Cookie跟踪使用情况和私有兴趣点'
        });
    });
</script>
]]-->
<!-- /End CookieBar -->

<!-- Piwik -->
<!--[[
<script type="text/javascript">
    var _paq = _paq || [];
    _paq.push(['trackPageView']);
    _paq.push(['enableLinkTracking']);
    (function() {
        var u = "https://piwik.anderdonau.de/";
        _paq.push(['setTrackerUrl', u + 'piwik.php']);
        _paq.push(['setSiteId', 1]);
        var d = document,
            g = d.createElement('script'),
            s = d.getElementsByTagName('script')[0];
        g.type = 'text/javascript';
        g.async = true;
        g.defer = true;
        g.src = u + 'piwik.js';
        s.parentNode.insertBefore(g, s);
    })();
</script>
<noscript>
  <p><img src="https://piwik.anderdonau.de/piwik.php?idsite=1" style="border:0;" alt="" /></p>
</noscript>
]]-->
<!-- End Piwik Code -->

<!-- SocialSharePrivacy 社交分享 -->
<!--[[
<script type="text/javascript">
    (function() {
        var s = document.createElement('script');
        var t = document.getElementsByTagName('script')[0];
        s.type = 'text/javascript';
        s.async = true;
        s.src = 'socialshareprivacy/jquery.socialshareprivacy.min.autoload.js';
        t.parentNode.insertBefore(s, t);
    })();
</script>
]]-->
<!-- End SocialSharePrivacy -->

<!-- qg -->
<script type="text/javascript">
    $(document).ready(function(){
        $('#qgAddPoint').off();
        $('#qgEditPoint').off();
        $('#qgDeletePoint').off();
        $('.qg-btn').off();
        
        $('.hide-all').click(togglePOI);
        $('.hide-sys').click(togglePOISys);
        $('.hide-qg').click(togglePOIQg);
        
        $('#qgAddPoint').click(qgAddPoint);
        $('#qgEditPoint').click(qgEditPoint);
        $('#qgDeletePoint').click(qgDeletePoint);

        
        $('[name="filter"]').change(filterPoint);
        $('[name="filter"]').keypress(filterPoint);
        $('[name="filter"]').keyup(filterPoint);
        setTimeout(function(){
            qgStart();
        },2000);
    });
    


    function qgStart(){
        $('#btnAddOpen').remove();
        // 获取canvas元素
        var canvas = $('#map').find('canvas')

        // 绑定单击事件
        $(canvas).on("click", function(e){
        // 获取鼠标相对于canvas的坐标
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            qgPointXY();
        });
        qgBuildCitysSelect();
    }
    
    //单击canvas事件
    function qgPointXY(e){
        let coords = $('#coords').text();
        let area = coords.split('x');
        $('[name="qg_pois_x"]').val(area[0]);
        $('[name="qg_pois_y"]').val(area[1]);
    }
    
    //创建城市与节点列表
    function qgBuildCitysSelect(){
        let select = $('#qgCitysSelect');
        $.each(areas,function(i,area){
            select.append('<option value="'+area.id+'">'+area.name+'</option>');
        });
        select.change(function(e){
            updatePointUL();
        });
    }
    
    //更新 UL
    function updatePointUL(){
        let ul = $('#qgPoint>ul');
        let area_id=$("#qgCitysSelect").val();
        ul.empty();
        let area = getArea(area_id);
        $.each(allPois,function(i,poi){
            if(poi.qg==1 && poi.area_id == area_id){
				createPointLi(ul,poi);
            }
        });
        $.each(allPois,function(i,poi){
            if(empty(poi.qg) && poi.area_id == area_id){
                if(typeof(netFanyi[poi.id]) !='undefined' && netFanyi[poi.id].qg){
    				createPointLi(ul,poi);
                }
            }
        });
        $.each(allPois,function(i,poi){
            if(empty(poi.qg) && poi.area_id == area_id){
                if(typeof(netFanyi[poi.id]) =='undefined' || (typeof(netFanyi[poi.id]) !='undefined' && empty(netFanyi[poi.id].qg)) ){
    				createPointLi(ul,poi);
                }
            }
        });
    }
    
    //创建节点 li
    function createPointLi(ul,poi){
        let cssClass = poi.qg ? 'qg-li' : 'sys-li';
		let name = poi.name;
		let title = poi.name;
		if(typeof(netFanyi[poi.id]) !='undefined'){
			name = netFanyi[poi.id].name;
			if(netFanyi[poi.id].qg) cssClass = 'fanyi-li';
		}
        ul.append('<li data="'+poi.id+'" title="'+title+'" class="'+cssClass
                 +'"><a href="javascript:;" onclick="qgGotoPoint(\''+poi.id+'\')">'+name+'</a></li>');
    }

    //跳到节点
    function qgGotoPoint(id){
        //let overlay_id = id.indexOf('overlay-')==0 ? id : 'overlay-'+id;
        let poi = getPoi(id);
    	if (poi) {
			let x = poi.map.px + (poi.map.width / 2);
			let y = poi.map.py + (poi.map.height / 2);
			viewer.viewport.panTo(viewer.world._items[0].imageToViewportCoordinates(x, y));
            setPointColor(id);
            qgClickPoint(id);
    	}
    }
    //列表节点变色
    function setPointColor(id){
        $('#qgPoint>ul>li').removeClass('select');
        $('[data="'+id+'"]').addClass('select');
    }

    //点击节点
    function qgClickPoint(id){
        let res = id.match(/[-]?(\d+)/);
        let init_id = res[1];
        let overlay_id = id.indexOf('overlay-')==0 ? id : 'overlay-'+id;
        $('#qgPoint>ul>li').removeClass('select');
        $('[data="'+overlay_id+'"]').addClass('select');
        let poi = getPoi(init_id);
    	if (poi) {
			let name = poi.name;
			let comment = poi.comment;
			if(typeof(netFanyi[poi.id]) !='undefined'){
				name = netFanyi[poi.id].name;
			}
			if(typeof(netFanyi[poi.id]) !='undefined'){
				comment = netFanyi[poi.id].comment;
			}
            $('[name="pointID"]').val(poi.id);
            $('[name="qg_pois_name"]').val(name);
            $('[name="qg_pois_comment"]').val(comment.replace(/<br>/g,"\n"));
            $('[name="qg_pois_x"]').val(poi.x);
            $('[name="qg_pois_y"]').val(poi.y);
            $("#qgCitysSelect").val(poi.area_id);
            $("#qgCitysSelect").change();
            setPointColor(id);
    	}
    }



    //过滤兴趣点
    function filterPoint(e){
        let keyword = $('[name="filter"]').val();
        $('#qgPoint>ul>li').each(function(i,li){
            let exp = new RegExp(keyword,'ig');
            if($(li).text().search(exp)!=-1 || $(li).attr('title').search(exp)!=-1){
                $(li).show();
            }else{
                $(li).hide();
            }
        });
    }
    
    //新节点数据
    function newPointData(){
        let id= $('[name="pointID"]').val();
        let area_id=$("#qgCitysSelect").val();
        let name=$('[name="qg_pois_name"]').val();
        let comment=$('[name="qg_pois_comment"]').val();
        let x=$('[name="qg_pois_x"]').val();
        let y=$('[name="qg_pois_y"]').val();
        let nowStr = now();
        return {
            "action": '',
            "id": id * 1,
            "area_id": area_id * 1,
            "name": name,
            "created_at": nowStr,
            "updated_at": nowStr,
            "x": x,
            "y": y,
            "score": 0,
            "user_id": 63,
            "comment": comment,
            "approver_id": 2,
            "approved_at": nowStr
        };
    }
    
    //检测新节点数据
    function checkPointData(v){
        if(v.action=='add' || v.action=='edit'){
            if(v.action=='edit' && v.id==''){
                alert('请选择一个兴趣点');
                return false;
            }
            if(v.x.replace(/\s/,'')=='' || v.y.replace(/\s/,'')==''){
                alert('坐标 x 和 y - 不能为空');
                return false;
            }else if(v.name.replace(/\s/,'')==''){
                alert('标题 - 不能为空');
                return false;
            }else if(v.area_id=='' || v.area_id==0 || v.area_id==null){
                alert('城市 - 不能为空');
                return false;
            }
        }else if(v.action=='delete'){
            if(v.id==''){
                alert('请选择一个兴趣点');
                return false;
            }
            if(!confirm('确认要删除节点[ '+v.name+' ]吗?')){
                return false;
            }
        }
        return true;
    }
    
    //添加兴趣点
    function qgAddPoint(e){
        let newItem = newPointData();
        newItem.action = 'add';
        newItem.id = 0;
        if(checkPointData(newItem)){
            savePoint(newItem,function(res){
                if(res.error!=''){
                    alert(res.error);
                }else if(res.id){
                    newItem.id = res.id;
                    var p = getMapPoint(newItem);
                    addOverlay(p);
        			loadQgData();
        			updatePointUL();
        			qgGotoPoint(newItem.id);
                }
            });
        }
    }
    
    //编辑兴趣点
    function qgEditPoint(e){
        let newItem = newPointData();
        newItem.action = 'edit';
        if(checkPointData(newItem)){
            savePoint(newItem,function(res){
                console.log(res);
                var p = getMapPoint(newItem);
                //let id = p.id.replace("overlay-","");
                let id = newItem.id;
                let area = getArea(newItem.area_id);
                let tip = $('#'+id+'-tip');
                $(tip).find('p.title').html(newItem.name);
                $(tip).find('p.remark').html(newItem.comment.replace(/\n/,'<br>'));
                $(tip).find('p.city').html(area.name);
    			loadQgData();
    			updatePointUL();
    			qgGotoPoint(newItem.id);
            });
        }
    }
    
    //删除兴趣点
    function qgDeletePoint(e){
        let newItem = newPointData();
        newItem.action = 'delete';
        if(checkPointData(newItem)){
            savePoint(newItem,function(res){
                var p = getMapPoint(newItem);
                removerOverlay(p);
                delete allPois['_'+newItem.area_id+'_'+newItem.id];
    			loadQgData();
    			updatePointUL();
            });
        }
    }
    
    function addOverlay(p){
        var map = $("#map");
		let href=p.id.replace("overlay-","");
		if(p.qg){
			map.prepend("<a id='"+p.id+"' href='#"+href+"'><img src='images/qg_mapcirclered_"+circleSize()+".png'></a>");
		}else{
			map.prepend("<a id='"+p.id+"' href='#"+href+"'><img src='images/mapcircleblue_"+circleSize()+".png'></a>");
		}
        viewer.addOverlay(p);
        bindtooltip(href);
    }
    
    function removerOverlay(p){
        //viewer.world.removeAll();移除地图用
        $.each(viewer.currentOverlays,function(i,overlay){
            if(typeof overlay != 'undefined' && typeof overlay.element != 'undefined'){
                if(p.id == overlay.element.id){
                    viewer.currentOverlays[i]=overlay;
                    $(overlay.element).addClass('remove');
                    viewer.removeOverlay(overlay.element);
                }
            }
        });
    }
    
    //当前时间
    function now(){
        let now = new Date();
        let year = now.getFullYear();
        let month = ('0' + (now.getMonth() + 1)).slice(-2);
        let day = ('0' + now.getDate()).slice(-2); 
        let hour = ('0' + now.getHours()).slice(-2); 
        let minute = ('0' + now.getMinutes()).slice(-2);
        let second = ('0' + now.getSeconds()).slice(-2);
        let dateTimeString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
        return dateTimeString;
    }

    //保存节点
    function savePoint(newItem,callback){
    	$.ajax({
    		url: './qg/save.php',
    		data: newItem,
    		type: 'post',
    		dataType: 'json',
    		async: false,
    		success: function(res){
    			//window.location.reload();
    			callback(res);
    		},
    		error: function(a, b, c){
    			console.log(a,b,c);
    			alert('失败 - 保存节点');
    		}
    	});
    }//savePoint
</script>
</body>

</html>