/**
* 私房路徑
*/
var map;

diaryRoadAllInit = function() {
    // 摩托地圖切換功能
    var area = '%';
    $('#Map area').each(function() {
        $(this).click(function() {
            var index = $('#Map area').index(this);
            area = index+1;
            return false;
        });
    });
    
    $('#cateMenu').change(function() {
        var category = $('option:selected', this).val();
        window.location = 'diary_road_all.php?category=' + category + '&area=' + area;
    });
}

diaryTourPlayInit = function(usn) {
    // Load 肖像
    diaryLoadPortrait(usn);     
}

diaryControlTour2Init = function() {
    // 更改回應狀態功能
    $('select[name="replyOn"]').change(function() {
        var id = $(this).attr('id');
        var res = $('option:selected', this).val();
        $('#modal').html('處理中...').jqmShow();
        $.ajax({
            url: 'ajax_board_reply_on.php',
            type: 'post',
            cache: false,
            data: {id: id, res: res},
            success: function(data) {
                $('#modal').html(data);
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
    });
    
    // modal
    $('#modal').jqm({modal: true});
}

// 點選好友帳號後插入搜尋列
function friendNameClickInit() {
    $('.friendUsn').css('cursor', 'pointer').click(function() {
        $('#username').val($(this).text());
    });
}

diaryControlTourFriendInit = function() {
    // ajax setup
    $.ajaxSetup({
        cache: false
    });

    // 點選好友帳號後插入搜尋列
    friendNameClickInit()
    
    // 邀請全站
    $('[name="btnInviteAll"]').click(function() {
        if (confirm('確定要傳送全站嗎？')) {
            $('div#modal')
                .html('處理中....')
                .jqmShow();
            var id = $(this).attr('id'),
                usn = $('#username').val(),
                info = $('[name="info"]:checked').val(),
                cts = $('#contents').val();
                
            $.post('ajax_picnic_invitation_all.php', {id: id, usn: usn, info: info, cts: cts}, function(data) {
                $('div#modal').html(data);
                setTimeout(function() {
                    $('div#modal').html('').jqmHide();
                }, 1500);
            });
        }
    });
    
    // 搜尋送出按鈕
    $('#btnPopSearch').click(function() {
        if ($.trim($('#popKey').val()) != '') {
            $('#loading').show();
            $('#friendTable').hide();
            $.post('ajax_search_friend.php', {usn: $('#popKey').val()}, function(data) {
                $('#loading').hide();
                $('#friendTable')
                    .html($(data).filter('div#res').html())
                    .fadeIn();
                    // 點選好友帳號後插入搜尋列
                    friendNameClickInit()
            });
        } else {
            alert('請填選好友帳號');
            $('#popKey').focus();
        }
    });
    
    // modal
    $('#modal').jqm({modal: true});

    // 關閉搜尋好友popup
    $('#btnPopClose').click(function() {
        $('div#pop').fadeOut('normal');
    });
    
    // 搜尋好友按鈕
    $('#btnSearchFriend').click(function() {
        $('div#pop').is(':visible') ? $('div#pop').fadeOut('normal') : $('div#pop').fadeIn('normal');
    });
    
    // 允許參加功能
    $('select[name="menuJoin"]').change(function() {
        var id = $(this).attr('id');
        var res = $('option:selected', this).val();
        var menu = $(this);
        
        $('#modal').html('進行中....').jqmShow();
        
        $.ajax({
            url: 'ajax_picnic_allow.php',
            cache: false,
            type: 'post',
            data: {id: id, res: res},
            success: function(data) {
                if ($.trim(data) == '女性已額滿' || $.trim(data) == '男性已額滿') menu.find('option').eq(0).attr("selected","true");
                $('#modal').html(data);
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
    });
    
    // 邀請他按鈕
    $('[name="btnInvite"]').click(function() {
        var id = $(this).attr('id');
        var usn = $('#username').val();
        var info = $('[name="info"]:checked').val();
        var cts = $('#contents').val();
        
        if ($.trim(usn) == '') {
            alert('請填寫帳號');
            $('#username').focus();
            return false;
        }
        
        $('#modal').html('進行中....').jqmShow();
        
        $.ajax({
            url: 'ajax_picnic_invitation.php',
            cache: false,
            type: 'post',
            data: {id: id, usn: usn, info: info, cts: cts},
            success: function(data) {
                $('#modal').html(data);
                setTimeout(function() {
                    window.location.reload();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
        
        return false;
    });
}

diaryTourDetailInit = function(usn) {
    // modal
    $('div#modal, #diaryReply').jqm({modal: true});
    
    // 我要參加
    $('a[name="btnJoin"]').click(function() {
        if (!confirm('確定要報名嗎？')) return false;
        
        $('#modal').html('處理中....').jqmShow();
        var id = $(this).attr('id');
        // ajax傳送回應
        $.ajax({
            url: 'ajax_picnic_join.php',
            cache: false,
            type: 'post',
            data: {id: id},
            success: function(data) {
                $('#modal').html(data);
                if (data == '請先登入會員') {
                    window.location = 'member_login.php';
                    return false;
                }
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
        return false;
    });
    
    // 版主回覆功能
    $('a[name="btnOwnerReply"]').click(function() {
        $('#ownerSecrect').attr('checked', false);
        $('#ownerReplyContents').val('');
        $('#ownerReplyId').val($(this).attr('id'))
        $('#diaryReply').jqmShow();
        return false;
    });
    
    // 版主回覆送出按鈕
    $('#btnOwnerReplySubmit').click(function() {
        $('#diaryReply').jqmHide();
        $('#modal').html('回應中....').jqmShow();
        
        var ownerSecrect = '';
        $('#ownerSecrect:checked').size() > 0 ? ownerSecrect = 1 : ownerSecrect = 0;
        
        // ajax傳送回應
        $.ajax({
            url: 'ajax_picnic_owner_reply.php',
            cache: false,
            type: 'post',
            data: {id: $('#ownerReplyId').val(), contents: $('#ownerReplyContents').val(), secret: ownerSecrect},
            success: function(data) {
                $('#modal').html(data);
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
    });
    
    // 網友回應功能
    $('a[name="btnReply"]').click(function() {
        // 檢查內容
        if ($.trim($('#name').val()) == '') {
            alert('請填寫暱稱');
            $('#name').focus();
            return false;
        }
        if ($.trim($('#contents').val()) == '') {
            alert('請填寫留言內容');
            $('#contents').focus();
            return false;            
        }
        
        var id = $(this).attr('id');
        var secret = ''
        $('#secret:checked').size() > 0 ?  secret = 1 : secret = 0;

        $('#modal').html('回應中....').jqmShow();
        $.ajax({
            url: 'ajax_picnic_reply.php',
            cache: false,
            type: 'post',
            data: {id: id, name: $('#name').val(), email: $('#email').val(), url: $('#url').val(), contents: $('#contents').val(), secret: secret},
            success: function(data) {
                $('#modal').html(data)
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
        
        return false;
    });
    
    // 推薦功能按鈕
   $('a[name="btnRecommend"]').click(function() {
       var id = $(this).attr('id');
       $('#modal').html('推薦中....').jqmShow();
       $.ajax({
           url: 'ajax_picnic_recommend.php',
           type: 'post',
           cache: false,
           data: {id: id},
           success: function(data) {
               $('#modal').html(data);
               setTimeout(function() {
                   $('#modal').html('').jqmHide();
               }, 1500);               
           },
           error: function() {
               setTimeout(function() {
                   $('#modal').html('').jqmHide();
               }, 1500);
           }
       });
       return false;
   });
    
    // Load 肖像
    diaryLoadPortrait(usn); 
}

diaryTourInit = function(usn) {
    // Load 肖像
    diaryLoadPortrait(usn);
}

diaryControlTourInit = function() {
    // modal
    $('#modal').jqm({modal: true});
    
    $('a.listClose').live('click', function() {
        $(this).parents('.pop').hide();
        return false;
    });
    
    // ajax laod 參加名單
    $('a[name="loadParticipator"]').click(function() {
        $.ajaxSetup({
            cache: false
        });
        
        var last = $(this).next(),
            id = $(this).attr('id');
        
        $.post('ajax_tour_load_participator.php', {id: id}, function(data) {
            var res = $(data).filter('#res').html();
            last.html(res);
        });
        return false;
    });
    
    // 刪除功能
    $('img[name="btnDel"]')
        .css('cursor', 'pointer')
        .click(function() {
            if (!confirm('確定要刪除嗎？')) return false;
            $('#modal').html('刪除中....').jqmShow();
            var id = $(this).attr('id');
            $.ajax({
                url: 'ajax_picnic_del.php',
                cache: false,
                type: 'post',
                data: {id: id},
                success: function(data) {
                    $('#modal').html(data);
                    if ($.trim(data) == '刪除成功') window.location.reload();
                    setTimeout(function() {
                        $('#modal').html('').jqmHide();
                    }, 1500);                    
                },
                error: function() {
                    setTimeout(function() {
                        $('#modal').html('').jqmHide();
                    }, 1500);
                }
            });
        });
}

diaryControlTourStep1Init = function() { 
    // 標籤怎麼下？
    $('#btnTag').click(function() {
        $(this).find('div').toggle();
        return false;
    });
}

dirayControlWay1_2Init = function() {
    // 標籤怎麼下？
    $('#btnTag').click(function() {
        $(this).find('div').toggle();
        return false;
    });
}

diaryControlWay2Init = function() {
    // 更改回應狀態功能
    $('select[name="replyOn"]').change(function() {
        var id = $(this).attr('id');
        var res = $('option:selected', this).val();
        $('#modal').html('處理中...').jqmShow();
        $.ajax({
            url: 'ajax_path_reply_on.php',
            type: 'post',
            cache: false,
            data: {id: id, res: res},
            success: function(data) {
                $('#modal').html(data);
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
    });
    
    // modal
    $('#modal').jqm({modal: true});
}

diaryWayDetailInit = function(usn) {
   // 推薦功能按鈕
   $('a[name="btnRecommend"]').click(function() {
       var id = $(this).attr('id');
       $('#modal').html('推薦中....').jqmShow();
       $.ajax({
           url: 'ajax_path_recommend.php',
           type: 'post',
           cache: false,
           data: {id: id},
           success: function(data) {
               $('#modal').html(data);
               setTimeout(function() {
                   $('#modal').html('').jqmHide();
               }, 1500);               
           },
           error: function() {
               setTimeout(function() {
                   $('#modal').html('').jqmHide();
               }, 1500);
           }
       });
       return false;
   });
    
    // 版主回覆功能
    $('a[name="btnOwnerReply"]').click(function() {
        $('#ownerSecrect').attr('checked', false);
        $('#ownerReplyContents').val('');
        $('#ownerReplyId').val($(this).attr('id'))
        $('#diaryReply').jqmShow();
        return false;
    });
    
    // 版主回覆送出按鈕
    $('#btnOwnerReplySubmit').click(function() {
        $('#diaryReply').jqmHide();
        $('#modal').html('回應中....').jqmShow();
        
        var ownerSecrect = '';
        $('#ownerSecrect:checked').size() > 0 ? ownerSecrect = 1 : ownerSecrect = 0;
        
        // ajax傳送回應
        $.ajax({
            url: 'ajax_path_owner_reply.php',
            cache: false,
            type: 'post',
            data: {id: $('#ownerReplyId').val(), contents: $('#ownerReplyContents').val(), secret: ownerSecrect},
            success: function(data) {
                $('#modal').html(data);
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
    });
    
    $('#btnReplySubmit').click(function() {
        alert($('#replyId').val());
    });
    
    // 網友回應功能
    $('a[name="btnReply"]').click(function() {
        // 檢查內容
        if ($.trim($('#name').val()) == '') {
            alert('請填寫暱稱');
            $('#name').focus();
            return false;
        }
        if ($.trim($('#contents').val()) == '') {
            alert('請填寫留言內容');
            $('#contents').focus();
            return false;            
        }
        
        var id = $(this).attr('id');
        var secret = ''
        $('#secret:checked').size() > 0 ?  secret = 1 : secret = 0;

        $('#modal').html('回應中....').jqmShow();
        $.ajax({
            url: 'ajax_path_reply.php',
            cache: false,
            type: 'post',
            data: {id: id, name: $('#name').val(), email: $('#email').val(), url: $('#url').val(), contents: $('#contents').val(), secret: secret},
            success: function(data) {
                $('#modal').html(data)
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
        
        return false;
    });
    
    // modal
    $('div#modal, #diaryReply').jqm({modal: true});
    
    // Load 肖像
    diaryLoadPortrait(usn);
        
    // 照片功能
    if ($('div.diary_way_photo a').is('*')) {
        $('div.diary_way_photo a').lightBox({fixedNavigation: true});    
    }
}

diraryControlWay1Init = function() {
    // modal initial
    $('#modal').jqm({modal: true});
    
    // 刪除全部按鈕
    $('img#btnDelAll')
        .css('cursor', 'pointer')
        .hover(function() {
            $(this).attr('src', 'images/diary_search/diary_control_tour_over_07.gif');
        }, function() {
            $(this).attr('src', 'images/diary_search/diary_control_tour_07.gif');
        })
        .click(function() {
            if(!confirm('確定要刪除嗎？')) return;
            if ($('[name="boxDel"]:checked').size() == 0) {
                alert('請至少選擇一個選項');
                return;
            }
            
            $('#modal').html('刪除中....').jqmShow();
            var str = '';
            $('[name="boxDel"]:checked').each(function() {
                str += '&pt_id[]=' + $(this).attr('id');
            });
            $.ajax({
                url: 'ajax_path_del.php',
                cache: false,
                type: 'post',
                data: str,
                success: function(data) {
                    $('#modal').html(data);
                    
                     if ($.trim(data) == '刪除成功') {
                        window.location.reload();
                    }
                    
                    setTimeout(function() {
                        $('#modal').html('').jqmHide();
                    }, 1500);
                },
                error: function() {
                    setTimeout(function() {
                        $('#modal').html('').jqmHide();
                    }, 1500);
                }
            });
        });
    
    // 目錄切換
    $('#pathCategory').change(function() {
        window.location = '?category=' + $('option:selected', this).val();
    });
    
    // 允許回應狀態變更
    $('select[name="replyMenu"]').change(function() {
        $('#modal').html('變更中....').jqmShow();
        var id = $(this).attr('id'), status = $('option:selected', this).val();
        $.ajax({
            url: 'ajax_path_reply_status.php',
            cache: false,
            type: 'post',
            data: {id: id, status: status},
            success: function(data) {
                $('#modal').html(data);
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);                
            },
            error: function() {
                $('#modal').html('發生錯誤....');
                setTimeout(function() {
                    $('#modal').html('').jqmHide();
                }, 1500);
            }
        });
    });
}

diaryWayInit = function(usn) {
    // Load 肖像
    diaryLoadPortrait(usn);
}

// load 肖像
diaryLoadPortrait = function(usn) {
    var container = $('div#diary_information_pic2');
    $.ajax({
        url: 'ajax_load_portrait.php',
        type: 'GET',
        cache: false,
        data: {name: usn},
        success: function(data) {
            var res = $(data).filter('div#res').html();
            container.html(res);
        }
    });
}

function frontMapShow() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById('googlemap'));
        map.addControl(new GSmallMapControl()); // 方向移動功能
        map.addControl(new GMapTypeControl()); // 地圖類型
       
        var dirn2 = new GDirections(), // 劃線
            ret = new GClientGeocoder(),
            markers = [],
            $symIcon = new GIcon(),
            $markers_array = new Array(),
            iconCount = $('input[name="coordinate"]').size();
//            iconDefault = new GIcon(G_DEFAULT_ICON), // 預設Icon
//            iconStart = new GIcon(), // 起點Icon
//            iconStartClick = new GIcon(), // 起點Icon有內容
//            iconEnd = new GIcon(), // 終點Icon
//            iconEndClick = new GIcon(), // 終點Icon有內容
//            iconClick = new GIcon(); // 有內容的Icon
                        
        GMarker.prototype.setIndex = function(index) {
            this.index = index;
        }

//        iconStart.image = 'google_icon/start.png';
//        iconStart.iconSize = new GSize(30, 43);
//        iconStart.iconAnchor = new GPoint(14, 42);
//        iconStart.infoWindowAnchor = new GPoint(0, 0);
//        
//        iconStartClick.image = 'google_icon/start_file.png';
//        iconStartClick.iconSize = new GSize(30, 43);
//        iconStartClick.iconAnchor = new GPoint(14, 42);
//        iconStartClick.infoWindowAnchor = new GPoint(0, 0);

//        iconEnd.image = 'google_icon/end.png';
//        iconEnd.iconSize = new GSize(30, 43);
//        iconEnd.iconAnchor = new GPoint(15, 43);
//        iconEnd.infoWindowAnchor = new GPoint(0, 0);
//        
//        iconEndClick.image = 'google_icon/end_file.png';
//        iconEndClick.iconSize = new GSize(30, 43);
//        iconEndClick.iconAnchor = new GPoint(15, 43);
//        iconEndClick.infoWindowAnchor = new GPoint(0, 0);

//        iconClick.image = 'google_icon/normal_file.png';
//        iconClick.iconSize = new GSize(30, 43);
//        iconClick.iconAnchor = new GPoint(15, 45);
//        iconClick.infoWindowAnchor = new GPoint(0, 0);

            $symIcon.image = 'http://www.motorlove.com.tw/images/sym.png';
            $symIcon.iconSize = new GSize(41, 32);
            $symIcon.shadow = 'http://www.motorlove.com.tw/images/symShadow.png';
            $symIcon.shadowSize = new GSize(50, 39);
            $symIcon.iconAnchor = new GPoint(13, 25);
            $symIcon.infoWindowAnchor = new GPoint(0, 0);

        function createMarker($p, $html, $icon) {
            var $marker = new GMarker($p, {icon: $icon});
            GEvent.addListener($marker, 'click', function() {
                $marker.openInfoWindowHtml($html);
            });
            return $marker;
        }

        GDownloadUrl('store_xml.php', function($doc) {
            var $xmlDoc = GXml.parse($doc),
                $markers = $xmlDoc.documentElement.getElementsByTagName('m'),
                $len = $markers.length;
                
            for (i = 0; i < $len; i++) {
                var $lat = $markers[i].getAttribute('lat'),
                    $lng = $markers[i].getAttribute('lng'),
                    $html = $markers[i].getAttribute('c'),
                    $p = new GLatLng($lat, $lng);
                $markers_array.push(createMarker($p, $html, $symIcon));
            }
            
            var $mm = new GMarkerManager(map, {borderPadding: 1});
            $mm.addMarkers($markers_array, 12, 17);
            $mm.refresh();
        });
       
        // 初始自設地標
        if ($('input[name="coordinate"]:first').val() != '') {
            var co = $('input[name="coordinate"]:first').val();
            map.setCenter(new GLatLng(co.split(',')[0], co.split(',')[1]), 14);
        } else {
            ret.getLatLng('中正紀念堂', function(point) {
                if (!point) {
                    return '找不到';
                } else {
                    map.setCenter(point, 14);
                }
            });
        }
        
        // modal設定
        $('div#mapModal, div#modal').jqm({modal: true});
        
        // 還原marker
        $('input[name="coordinate"]').each(function(i) {
            var co = $(this).val(), // 抓取座標
                index = markers.length,
                html = $(this).nextAll('textarea[name="mapContents"]').val(),
                num = new String(i + 1);
                
                if (num.length < 2) num = '0' + num;
                
                if ($.trim(html) != '') {
                   //有文件
                   var myIcon = new GIcon(); // 起點Icon
                   myIcon.image = 'google_icon/mapIconfile_' + num + '.png';
                   myIcon.iconSize = new GSize(30, 43);
                   myIcon.iconAnchor = new GPoint(15, 43);
                   myIcon.infoWindowAnchor = new GPoint(0, 0);
                   var marker = new GMarker(new GLatLng(co.split(',')[0], co.split(',')[1]), {icon: myIcon});
                } else {
                   // 沒文件
                   var myIcon = new GIcon(); // 起點Icon
                   myIcon.image = 'google_icon/mapIcon_' + num + '.png';
                   myIcon.iconSize = new GSize(30, 43);
                   myIcon.iconAnchor = new GPoint(15, 43);
                   myIcon.infoWindowAnchor = new GPoint(0, 0);
                   var marker = new GMarker(new GLatLng(co.split(',')[0], co.split(',')[1]), {icon: myIcon});                                
                }
                
                marker.setIndex(index);
                markers[index] = marker;
                
                if ($.trim(html) != '') {
                    GEvent.addListener(marker, 'click', function() {
                        marker.openInfoWindowHtml('<div class="mapShow">' + html + '</div>');
                    });
                }
                
                map.addOverlay(marker);
        });
       
        // 劃線
        GEvent.addListener(dirn2, 'load', function() {
            map.addOverlay(dirn2.getPolyline());
        });
                
        // 劃線
        function drawing() {
            var arr = [];
            $('input[name="coordinate"]').each(function() {
                arr.push($(this).val());
            });
            dirn2.loadFromWaypoints(arr, {getPolyline: true, avoidHighways: true, avoidHighways: true});
        }
        
        // 定位按鈕
        $('input[name="goMap"]').bind('click', function() {
            var co = $(this).next().val(); // 抓取座標
            map.setCenter(new GLatLng(co.split(',')[0], co.split(',')[1]));
        });
        
        // 內文按鈕
        $('input[name="btnEdit"]').bind('click', function() {
            var title = $(this).prevAll('input[name="addresses"]').val(),
                contents = $(this).nextAll('textarea[name="mapContents"]').val();
          
            $('div#mapModal')
                .find('div#title').html(title).end()
                .find('div#content').html(contents).end()
                .jqmShow();
        });
        
        // 劃線
        drawing();
    } else {
        alert('您的瀏覽器無法使用Google Map！');
    }
}

function mapRestore(url, act) {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById('googlemap'));
        map.addControl(new GSmallMapControl()); // 方向移動功能
        map.addControl(new GMapTypeControl()); // 地圖類型
        $('div#modal, div#mapModal').jqm({modal: true}); // 設定modal
        
        var dirn1 = new GDirections(), // 拖曳取得正確目標
            dirn2 = new GDirections(), // 劃線
            dirn3 = new GDirections(), // 點擊地圖抓取正確座標
            ret = new GClientGeocoder(),
            markerLimit = 30,
            markers = [],
            oldPolys = '',
            lastMarker,
            lastContents,
            $symIcon = new GIcon(),
            $markers_array = new Array(),
            editor = new FCKeditor('mapTextArea', 300, 150, 'Basic');
            
            $symIcon.image = 'http://www.motorlove.com.tw/images/sym.png';
            $symIcon.iconSize = new GSize(41, 32);
            $symIcon.shadow = 'http://www.motorlove.com.tw/images/symShadow.png';
            $symIcon.shadowSize = new GSize(50, 39);
            $symIcon.iconAnchor = new GPoint(13, 25);
            $symIcon.infoWindowAnchor = new GPoint(0, 0);

            function createMarker($p, $html, $icon) {
                var $marker = new GMarker($p, {icon: $icon});
                GEvent.addListener($marker, 'click', function() {
                    $marker.openInfoWindowHtml($html);
                });
                return $marker;
            }

            GDownloadUrl('store_xml.php', function($doc) {
                var $xmlDoc = GXml.parse($doc),
                    $markers = $xmlDoc.documentElement.getElementsByTagName('m'),
                    $len = $markers.length;
                    
                for (i = 0; i < $len; i++) {
                    var $lat = $markers[i].getAttribute('lat'),
                        $lng = $markers[i].getAttribute('lng'),
                        $html = $markers[i].getAttribute('c'),
                        $p = new GLatLng($lat, $lng);
                    $markers_array.push(createMarker($p, $html, $symIcon));
                }
                
                var $mm = new GMarkerManager(map, {borderPadding: 1});
                $mm.addMarkers($markers_array, 12, 17);
                $mm.refresh();
            });
            
        // 設定Ajax
        $.ajaxSetup({cache: false});
            
        // 初始編輯器
        with (editor) {
            BasePath = 'fckeditor/';
            ReplaceTextarea();
        }
            
        GMarker.prototype.setIndex = function(index) {
            this.index = index;
        }
       
       
        // 初始自設地標
        if ($('input[name="coordinate"]:first').val() != '') {
            ret.getLatLng('中正紀念堂', function(point) {
                if (!point) {
                    return '找不到';
                } else {
                    map.setCenter(point, 14);
                }
            });
        }
                       
        // 地圖點擊功能
        GEvent.addListener(map, "click", function(overlay, point) {
            if (checkAmount()) {
                if (!overlay) {
                    map.setCenter(point);
                    dirn3.loadFromWaypoints([point.toUrlValue(6), point.toUrlValue(6)], {getPolyline: true, avoidHighways: true});
                }    
            }
            
        });
        
        // 查詢目前數量功能
        function checkAmount() {
            var amount = $('#mapList li').size();
            if ((amount + 1) > markerLimit) {
                alert('超出最大地標限制' + markerLimit);
                return false;
            }
            return true;
        }
        
        // 還原marker
        $('input[name="coordinate"]').each(function() {
            var co = $(this).val(), // 抓取座標
                marker = new GMarker(new GLatLng(co.split(',')[0], co.split(',')[1]), {draggable: true}),
                index = markers.length;
                
                marker.setIndex(index);
                markers[index] = marker;
                
                GEvent.addListener(marker, "dragend", function() {
                    lastMarker = marker;
                    var point = marker.getPoint();
                    dirn1.loadFromWaypoints([point.toUrlValue(6), point.toUrlValue(6)], {getPolyline: true, avoidHighways: true});
                });
                
                map.addOverlay(marker);
        });
        
        // Dragend取得正確座標
        GEvent.addListener(dirn1, "load", function() {
            var p = dirn1.getPolyline().getVertex(0),
                ad = new GClientGeocoder(), // 座標找地址
                index = lastMarker.index;
            lastMarker.setPoint(p);
            $('input[name="coordinate"]').eq(index).val(p.toUrlValue(6));
            
            
            // 利用座標抓地址
            ad.getLocations(p, function(addresses) {
                if(addresses.Status.code != 200) {
                    result = "此座標沒有找到對應的地址";
                } else { 
                    result = addresses.Placemark[0].address;
                }
                
                // 放置地址
                $('input[name="addresses"]').eq(index).val(result);
            });
            
            // 劃線
            drawing();
        });
        
        // 點擊地圖抓取正確座標
        GEvent.addListener(dirn3, 'load', function() {
            var p = dirn3.getPolyline().getVertex(0),
                marker = new GMarker(p, {draggable: true}),
                ad = new GClientGeocoder(), // 座標找地址
                index = markers.length;
                
                marker.setIndex(index);
                markers[index] = marker;
                
                // 利用座標抓地址
                ad.getLocations(p, function(addresses) {
                    if(addresses.Status.code != 200) {
                        result = "此座標沒有找到對應的地址";
                    } else { 
                        result = addresses.Placemark[0].address;
                    }
                    
                    // 放置地址
                    $('input[name="addresses"]').eq(index).val(result);
                });
                
                GEvent.addListener(marker, "dragend", function() {
                    lastMarker = marker;
                    var point = marker.getPoint();
                    dirn1.loadFromWaypoints([point.toUrlValue(6), point.toUrlValue(6)], {getPolyline: true, avoidHighways: true});
                });
                
                // 增加座標點
                var html = '<li><input type="text" size="40" readonly=true name="addresses"><input type="button" name="goMap" value="定位" class="font"><input type="hidden" value="' + p.toUrlValue(6) + '" name="coordinate"><input type="button" name="btnDel" value="刪除" class="font"><input type="button" name="btnEdit" value="編輯" class="font"><textarea name="mapContents"></textarea></li>';
                $('div#mapList ul').append(html);
                
                map.addOverlay(marker);
                
                // 劃線
                drawing();
        });
        
        // 劃線
        GEvent.addListener(dirn2, 'load', function() {
            if (oldPolys) map.removeOverlay(oldPolys);
            map.addOverlay(dirn2.getPolyline());
            oldPolys = dirn2.getPolyline();
        });
        
        // modal儲存按鈕
        $('#jqmSave').click(function() {
            var oEditor = FCKeditorAPI.GetInstance('mapTextArea');
            
            if (lastContents) {
                lastContents.val(oEditor.GetHTML());
                $('div#mapModal').jqmHide();
            }
        });
          
        // 編輯按鈕
        $('input[name="btnEdit"]').live('click', function() {
            lastContents = $(this).nextAll('textarea[name="mapContents"]');
            var title = $(this).prevAll('input[name="addresses"]').val(),
                contents = $(this).nextAll('textarea[name="mapContents"]').val(),
                oEditor = FCKeditorAPI.GetInstance('mapTextArea');
                
            oEditor.SetHTML(contents);
                
            $('div#mapModal')
                .find('div#title').html(title).end()
                .jqmShow();
        });
        
        // 定位按鈕
        $('input[name="goMap"]').live('click', function() {
            var co = $(this).next().val(); // 抓取座標
            map.setCenter(new GLatLng(co.split(',')[0], co.split(',')[1]));
        });
        
        // 搜尋按鈕        
        $('#btnAddressSearch').click(function() {
            var address = $(this).prev().val(), // 地址
                gencoder = new GClientGeocoder(); // 座標物件
                
            if ($.trim(address) == '') {
                alert('請輸入地址');
            } else {
                if (checkAmount()) {          
                    gencoder.getLatLng(address, function(point) {
                        if (!point) {
                            alert('找不到該地址！')
                        } else {
                            map.setCenter(point);
                            var marker = new GMarker(point, {draggable: true}),
                                index = markers.length;
                            marker.setIndex(index);
                            markers[index] = marker;
                            
                            GEvent.addListener(marker, "dragend", function() {
                                lastMarker = marker;
                                var point = marker.getPoint();
                                dirn1.loadFromWaypoints([point.toUrlValue(6), point.toUrlValue(6)], {getPolyline: true, avoidHighways: true});
                            });
                            
                            // 增加座標點
                            var html = '<li><input type="text" size="40" name="addresses" readonly=true value="' + $('#address').val() + '"><input type="button" name="goMap" value="定位" class="font"><input type="hidden" value="' + point.toUrlValue(6) + '" name="coordinate"><input type="button" name="btnDel" value="刪除" class="font"><input type="button" name="btnEdit" value="編輯" class="font"><textarea name="mapContents"></textarea></li>';
                            $('div#mapList ul').append(html);
                            
                            map.addOverlay(marker);
                            
                            // 劃線
                            drawing();
                        }
                    });
                }
            }
        });
        
        // 刪除座標按鈕
        $('input[name="btnDel"]').live('click', function() {
            var index = $('input[name="btnDel"]').index(this);
            $(this).parents('li').remove();
            deleteMarker(index);
        });
        
        // 儲存按鈕
        $('#btnSave').click(function() {
            var json = '',
                id = $('#mapId').val(),
                arr = [];
                
            $('input[name="coordinate"]').each(function() {
                var address = $(this).prevAll('input[name="addresses"]').val(),
                    coordinate = $(this).val(),
                    contents = $(this).nextAll('textarea[name="mapContents"]').val();
                    contents = contents.replace(/"/g,'colon');
                    
                arr.push('{"address": "' + address + '", "coordinate": "' + coordinate + '", "contents": "' + contents + '"}');
            });
            
            json = '{"map": [' + arr + ']}';

            $('div#modal')
                .html('處理中...')
                .jqmShow();
                
            $.post('ajax_update_map.php', {id: id, json: json, act: act}, function(data) {
                if (data == 'done') {
                    window.location = url;
                } else {
                    $('div#modal').html(data);
                    setTimeout(function() {
                        $('div#modal')
                            .html('')
                            .jqmHide();
                    }, 1500);
                }
            });
        });
        
        // 劃線
        function drawing() {
            var arr = [];
            $('input[name="coordinate"]').each(function() {
                arr.push($(this).val());
            });
            dirn2.loadFromWaypoints(arr, {getPolyline: true, avoidHighways: true});
        }
        
        // 劃線
        drawing();
        
        // 刪除座標
        function deleteMarker(index) {
            map.removeOverlay(markers[index]);
            for(var i = index; i < markers.length-1; i++) {
                markers[i+1].setIndex(i);
                markers[i] = markers[i+1];
            }
            markers.length = markers.length-1;
            
            if (markers.length <= 1) {
                map.removeOverlay(oldPolys);
            }
            
            // 劃線
            drawing();
        }
    } else {
        alert('您的瀏覽器無法使用Google Map！');
    }
}

function mapShow() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById('googlemap'));
        map.addControl(new GSmallMapControl()); // 方向移動功能
        map.addControl(new GMapTypeControl()); // 地圖類型
        $('div#modal, div#mapModal').jqm({modal: true}); // 設定modal
        
        var dirn2 = new GDirections(), // 劃線
            ret = new GClientGeocoder(),
            markers = [],
            oldPolys = '',
            lastMarker,
            lastContents,
            $symIcon = new GIcon(),
            $markers_array = new Array();
            
            $symIcon.image = 'http://www.motorlove.com.tw/images/sym.png';
            $symIcon.iconSize = new GSize(41, 32);
            $symIcon.shadow = 'http://www.motorlove.com.tw/images/symShadow.png';
            $symIcon.shadowSize = new GSize(50, 39);
            $symIcon.iconAnchor = new GPoint(13, 25);
            $symIcon.infoWindowAnchor = new GPoint(0, 0);
            
        function createMarker($p, $html, $icon) {
            var $marker = new GMarker($p, {icon: $icon});
            GEvent.addListener($marker, 'click', function() {
                $marker.openInfoWindowHtml($html);
            });
            return $marker;
        }

        GDownloadUrl('store_xml.php', function($doc) {
            var $xmlDoc = GXml.parse($doc),
                $markers = $xmlDoc.documentElement.getElementsByTagName('m'),
                $len = $markers.length;
                
            for (i = 0; i < $len; i++) {
                var $lat = $markers[i].getAttribute('lat'),
                    $lng = $markers[i].getAttribute('lng'),
                    $html = $markers[i].getAttribute('c'),
                    $p = new GLatLng($lat, $lng);
                $markers_array.push(createMarker($p, $html, $symIcon));
            }
            
            var $mm = new GMarkerManager(map, {borderPadding: 1});
            $mm.addMarkers($markers_array, 12, 17);
            $mm.refresh();
        });
            
            
        GMarker.prototype.setIndex = function(index) {
            this.index = index;
        }
       
       
        // 初始自設地標
        if ($('input[name="coordinate"]:first').val() != '') {
            var co = $('input[name="coordinate"]:first').val();
            map.setCenter(new GLatLng(co.split(',')[0], co.split(',')[1]), 14);
        } else {
            ret.getLatLng('中正紀念堂', function(point) {
                if (!point) {
                    return '找不到';
                } else {
                    map.setCenter(point, 14);
                }
            });
        }
        
        // 還原marker
        $('input[name="coordinate"]').each(function() {
            var co = $(this).val(), // 抓取座標
                marker = new GMarker(new GLatLng(co.split(',')[0], co.split(',')[1]), {draggable: true}),
                index = markers.length,
                html = $(this).nextAll('textarea[name="mapContents"]').val();
                
                marker.setIndex(index);
                markers[index] = marker;
                
                if ($.trim(html) != '') {
                    GEvent.addListener(marker, 'click', function() {
                        marker.openInfoWindowHtml('<div class="mapShow">' + html + '</div>');
                    });
                }
                
                map.addOverlay(marker);
        });
       
        // 劃線
        GEvent.addListener(dirn2, 'load', function() {
            if (oldPolys) map.removeOverlay(oldPolys);
            map.addOverlay(dirn2.getPolyline());
            oldPolys = dirn2.getPolyline();
        });
        
        // 內文按鈕
        $('input[name="btnEdit"]').each(function() {
            $(this).click(function() {
                var title = $(this).prevAll('input[name="addresses"]').val(),
                    contents = $(this).nextAll('textarea[name="mapContents"]').val();
                    
                $('div#mapModal')
                    .find('div#title').html(title).end()
                    .find('div#content').html(contents).end()
                    .jqmShow(); 
            });
        });
              
        // 定位按鈕
        $('input[name="goMap"]').live('click', function() {
            var co = $(this).next().val(); // 抓取座標
            map.setCenter(new GLatLng(co.split(',')[0], co.split(',')[1]), 15);
        });
                
        // 劃線
        function drawing() {
            var arr = [];
            $('input[name="coordinate"]').each(function() {
                arr.push($(this).val());
            });
            dirn2.loadFromWaypoints(arr, {getPolyline: true, avoidHighways: true});
        }
        
        // 劃線
        drawing();
    } else {
        alert('您的瀏覽器無法使用Google Map！');
    }
}

// 初始地圖
function mapInit(url, act) {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById('googlemap'));
        map.addControl(new GSmallMapControl()); // 方向移動功能
        map.addControl(new GMapTypeControl()); // 地圖類型
        $('div#modal, div#mapModal').jqm({modal: true}); // 設定modal
        
        var dirn1 = new GDirections(), // 拖曳取得正確目標
            dirn2 = new GDirections(), // 劃線
            dirn3 = new GDirections(), // 點擊地圖抓取正確座標
            ret = new GClientGeocoder(),
            markerLimit = 30,
            markers = [],
            oldPolys = '',
            lastMarker,
            lastContents,
            $symIcon = new GIcon(),
            $markers_array = new Array(),
            editor = new FCKeditor('mapTextArea', 300, 150, 'Basic');
            
            $symIcon.image = 'http://www.motorlove.com.tw/images/sym.png';
            $symIcon.iconSize = new GSize(41, 32);
            $symIcon.shadow = 'http://www.motorlove.com.tw/images/symShadow.png';
            $symIcon.shadowSize = new GSize(50, 39);
            $symIcon.iconAnchor = new GPoint(13, 25);
            $symIcon.infoWindowAnchor = new GPoint(0, 0);
        
        function createMarker($p, $html, $icon) {
            var $marker = new GMarker($p, {icon: $icon});
            GEvent.addListener($marker, 'click', function() {
                $marker.openInfoWindowHtml($html);
            });
            return $marker;
        }

        GDownloadUrl('store_xml.php', function($doc) {
            var $xmlDoc = GXml.parse($doc),
                $markers = $xmlDoc.documentElement.getElementsByTagName('m'),
                $len = $markers.length;
                
            for (i = 0; i < $len; i++) {
                var $lat = $markers[i].getAttribute('lat'),
                    $lng = $markers[i].getAttribute('lng'),
                    $html = $markers[i].getAttribute('c'),
                    $p = new GLatLng($lat, $lng);
                $markers_array.push(createMarker($p, $html, $symIcon));
            }
            
            var $mm = new GMarkerManager(map, {borderPadding: 1});
            $mm.addMarkers($markers_array, 12, 17);
            $mm.refresh();
        });
            
        // 設定Ajax
        $.ajaxSetup({cache: false});
            
        // 初始編輯器
        with (editor) {
            BasePath = 'fckeditor/';
            ReplaceTextarea();
        }
            
        GMarker.prototype.setIndex = function(index) {
            this.index = index;
        }
       
        // 初始地標
        ret.getLatLng('中正紀念堂', function(point) {
            if (!point) {
                return '找不到';
            } else {
                map.setCenter(point, 15);
            }
        });
               
        // 地圖點擊功能
        GEvent.addListener(map, "click", function(overlay, point) {
            if (checkAmount()) {
                if (!overlay) {
                    map.setCenter(point);
                    dirn3.loadFromWaypoints([point.toUrlValue(6), point.toUrlValue(6)], {getPolyline: true, avoidHighways: true});
                }
            }
        });
        
        // Dragend取得正確座標
        GEvent.addListener(dirn1, "load", function() {
            var p = dirn1.getPolyline().getVertex(0),
                ad = new GClientGeocoder(), // 座標找地址
                index = lastMarker.index;
            lastMarker.setPoint(p);
            $('input[name="coordinate"]').eq(index).val(p.toUrlValue(6));
            
            // 利用座標抓地址
            ad.getLocations(p, function(addresses) {
                if(addresses.Status.code != 200) {
                    result = "此座標沒有找到對應的地址";
                } else { 
                    result = addresses.Placemark[0].address;
                }
                
                // 放置地址
                $('input[name="addresses"]').eq(index).val(result);
            });
            
            // 劃線
            drawing();
        });
        
        // 點擊地圖抓取正確座標
        GEvent.addListener(dirn3, 'load', function() {
            var p = dirn3.getPolyline().getVertex(0),
                marker = new GMarker(p, {draggable: true}),
                ad = new GClientGeocoder(), // 座標找地址
                index = markers.length;
                
                marker.setIndex(index);
                markers[index] = marker;
                
                // 利用座標抓地址
                ad.getLocations(p, function(addresses) {
                    if(addresses.Status.code != 200) {
                        result = "此座標沒有找到對應的地址";
                    } else { 
                        result = addresses.Placemark[0].address;
                    }
                    
                    // 放置地址
                    $('input[name="addresses"]').eq(index).val(result);
                });
                
                GEvent.addListener(marker, "dragend", function() {
                    lastMarker = marker;
                    var point = marker.getPoint();
                    dirn1.loadFromWaypoints([point.toUrlValue(6), point.toUrlValue(6)], {getPolyline: true, avoidHighways: true});
                });
                
                // 增加座標點
                var html = '<li><input type="text" size="40" readonly=true name="addresses"><input type="button" name="goMap" value="定位" class="font"><input type="hidden" value="' + p.toUrlValue(6) + '" name="coordinate"><input type="button" name="btnDel" value="刪除" class="font"><input type="button" name="btnEdit" value="編輯" class="font"><textarea name="mapContents"></textarea></li>';
                $('div#mapList ul').append(html);
                
                map.addOverlay(marker);
                
                // 劃線
                drawing();
        });
        
        // 劃線
        GEvent.addListener(dirn2, 'load', function() {
            if (oldPolys) map.removeOverlay(oldPolys);
            map.addOverlay(dirn2.getPolyline());
            oldPolys = dirn2.getPolyline();
        });
        
        // 查詢目前數量功能
        function checkAmount() {
            var amount = $('#mapList li').size();
            if ((amount + 1) > markerLimit) {
                alert('超出最大地標限制' + markerLimit);
                return false;
            }
            return true;
        }
        
        // modal儲存按鈕
        $('#jqmSave').click(function() {
            var oEditor = FCKeditorAPI.GetInstance('mapTextArea');
            
            if (lastContents) {
                lastContents.val(oEditor.GetHTML());
                $('div#mapModal').jqmHide();
            }
        });
          
        // 編輯按鈕
        $('input[name="btnEdit"]').live('click', function() {
            lastContents = $(this).nextAll('textarea[name="mapContents"]');
            var title = $(this).prevAll('input[name="addresses"]').val(),
                contents = $(this).nextAll('textarea[name="mapContents"]').val(),
                oEditor = FCKeditorAPI.GetInstance('mapTextArea');
                
            oEditor.SetHTML(contents);
                
            $('div#mapModal')
                .find('div#title').html(title).end()
                .jqmShow();
        });
        
        // 定位按鈕
        $('input[name="goMap"]').live('click', function() {
            var co = $(this).next().val(); // 抓取座標
            map.setCenter(new GLatLng(co.split(',')[0], co.split(',')[1]));
        });
        
        // 搜尋按鈕        
        $('#btnAddressSearch').click(function() {
            var address = $(this).prev().val(), // 地址
                gencoder = new GClientGeocoder(); // 座標物件
                
            if ($.trim(address) == '') {
                alert('請輸入地址');
            } else {
                if (checkAmount()) {
                    gencoder.getLatLng(address, function(point) {
                    if (!point) {
                        alert('找不到該地址！')
                    } else {
                        map.setCenter(point);
                        var marker = new GMarker(point, {draggable: true}),
                            index = markers.length;
                        marker.setIndex(index);
                        markers[index] = marker;
                        
                        GEvent.addListener(marker, "dragend", function() {
                            lastMarker = marker;
                            var point = marker.getPoint();
                            dirn1.loadFromWaypoints([point.toUrlValue(6), point.toUrlValue(6)], {getPolyline: true, avoidHighways: true});
                        });
                        
                        // 增加座標點
                        var html = '<li><input type="text" size="40" name="addresses" readonly=true value="' + $('#address').val() + '"><input type="button" name="goMap" value="定位" class="font"><input type="hidden" value="' + point.toUrlValue(6) + '" name="coordinate"><input type="button" name="btnDel" value="刪除" class="font"><input type="button" name="btnEdit" value="編輯" class="font"><textarea name="mapContents"></textarea></li>';
                        $('div#mapList ul').append(html);
                        
                        map.addOverlay(marker);
                        
                        // 劃線
                        drawing();
                    }
                    });
                }
                
            }
        });
        
        // 刪除座標按鈕
        $('input[name="btnDel"]').live('click', function() {
            var index = $('input[name="btnDel"]').index(this);
            $(this).parents('li').remove();
            deleteMarker(index);
        });
        
        // 儲存按鈕
        $('#btnSave').click(function() {
            var json = '',
                id = $('#mapId').val(),
                arr = [];
                
            $('input[name="coordinate"]').each(function() {
                var address = $(this).prevAll('input[name="addresses"]').val(),
                    coordinate = $(this).val(),
                    contents = $(this).nextAll('textarea[name="mapContents"]').val();
                    contents = contents.replace(/"/g,'colon');
                    
                arr.push('{"address": "' + address + '", "coordinate": "' + coordinate + '", "contents": "' + contents + '"}');
            });
            
            json = '{"map": [' + arr + ']}';

            $('div#modal')
                .html('處理中...')
                .jqmShow();
                
            $.post('ajax_update_map.php', {id: id, json: json, act: act}, function(data) {
                if (data == 'done') {
                    window.location = url;
                } else {
                    $('div#modal').html(data);
                    setTimeout(function() {
                        $('div#modal')
                            .html('')
                            .jqmHide();
                    }, 1500);
                }
            });
        });
        
        // 劃線
        function drawing() {
            var arr = [];
            $('input[name="coordinate"]').each(function() {
                arr.push($(this).val());
            });
            dirn2.loadFromWaypoints(arr, {getPolyline: true, avoidHighways: true});
        }

        // 刪除座標
        function deleteMarker(index) {
            map.removeOverlay(markers[index]);
            for(var i = index; i < markers.length-1; i++) {
                markers[i+1].setIndex(i);
                markers[i] = markers[i+1];
            }
            markers.length = markers.length-1;
            
            if (markers.length <= 1) {
                map.removeOverlay(oldPolys);
            }
            
            // 劃線
            drawing();
        }
    } else {
        alert('您的瀏覽器無法使用Google Map！');
    }
}