/*
 richPOI Fn - by Vincent Hung(Y2)

 -- 2008/05/19 beta1
 1.fix size for 1024/1280
 2.ajax html respone
 3.sidebar - click show on googlemap
 4.auto scroller to position
 5.on googlemap click, auto show selected item(background), closeInfowindow clear selected item.
 6.tabs switch
 7.search find, auto close doc.

 -- 2008/05/21 beta2
 8.search field must be input some, only press GO btn then go search.
 9.search place, show the find Point Marker
 10.layout switch, auto fit / fixed size
 11.i18n rules.
 12.click count
 13.Greybox Redux - fix 4 Firefox, add some...
 14.fix Greybox overflow

 -- 2008/05/22 beta3
 15.fix autofit layout, when resize window, and click to maximunWindow, the #extra .content show correct.

 -- 2008/05/29 beta4
 16.add search found/notfound show or marker
 17.add location search address:itema:itemb ......
 18.innerHeight > 750 ? show big size : show small size

 -- 2008/06/02 beta4
 19.fix chinese character , add encodeURIComponent(xxxxx), search Tags result line238, line 552

 -- 2008/06/03
 20.add MaxContent Fn, and 'xhtml1-strict.dtd' change to 'xhtml1-transitional.dtd', because FF MaxContent scorllbar reason.
 21. MaxCOntent with iframe.

 -- 2008/06/09 beta4
 20.add keyword search area_type
 21.fix enter(key-13) submit
 22.add extend_bounds init

 -- 2008/06/12 beta5
 23.auto scroll to selected result item to seeing area

 -- 2008/06/16 beta6
 24.fix selected click twice over.
 25.add selected/popInfoWin = r_class_win, click no reopen,  1=yes, 0=no

 -- 2008/08/11
 26.change left Panel layout, ui tabs
 27.add my fav tab

 -- 2008/08/12
 28.add infoWindowClose panToCenter(g_bounds)
 29.add infowindowOpen then resize to Max bubble -> g_map.getInfoWindow().maximize(true)

 -- 2008/08/15
 30.add tab1_use_ for tabs switch behavior

 -- 2009/09/16
 31.some logic is so mixed.....
 32.manager Fn / batch dl, ajax edit, form delete, add new type
 33.tab switch show different map poi
 -- 2010/02/06
 34.add garmin numap type

 -- 2011/08/25
 35.change googleMap to nuMap
 36.convet many function googleMap to numap

 -- 2011/09/15 final 2 nuMap
 37. all done.


 */
//var domain_cookie = 'colorado';

var domain_cookie = 'my.garmin.com.tw';
var richPOI_i_dir = "/connect/images/";
var richPOI_i_no_dir = richPOI_i_dir + "no/";
var cookie_options = { expires: 30, domain: domain_cookie};
var tab_cookie_id = parseInt($.cookie("the_tab_cookie")) || 0;
var login_ = ($.cookie("username")) ? 1 : 0;

var key_ = "";
var tab0_use_ = 0;
var tab1_use_ = 0;
var tabs_init_set_ = 0;
var tab0_data_ = 0;
var tab_id_which_one = 0;
var show_map = 0;
var first_load = 0;
var tab0_id = 0;
var tab1_id = 0;
var gb_update = 0;
var _my = 0;

var _infowin = null;
var _layer = null;

var InfoWindowW = 470;
var InfoWindowH = 280;

var infowin_move_dist = 2;

var _maxWin_W = 0;
var _maxWin_H = 1;
var maxWinWidth = 670;
var maxWinHeight = 450;
var maxWinWidthMinus = 100;
var maxWinHeightMinus = 50;

var iframeWidth = "100%";
var iframeHeight = 240;

_layer = new GShapeLayer();

/* Taiwan
 ------------------------------------------------------------------------------*/
var i18n = {
    //txt
    txt_search_process        : "搜尋結果處理中...",
    txt_process_done          : "處理完成.",
    txt_process_error         : "資料回傳格式似乎有點問題 :( ",
    txt_search_nokeyword      : "你沒有輸入『關鍵字』喲!",
    txt_search_place          : "地點搜尋中",
    txt_search_place_done     : "地點搜尋結束",
    txt_search_place_noinput  : "你沒有輸入『地點』喲!",
    txt_search_noinput        : "請任一輸入關鍵字或者地點為查詢條件",
    txt_search_place_notfound : "n&uacute; Map 資料庫裡找不到你輸入的地點 :",
    txt_dl_pnd                : "下載 - ",

    // loading-indicator slide time
    indicator_slide_time: 500,
    doc_slide_time: 10,
    //search auto hide
    doc_slide_time_click: 300,
    //click show/hide
    scrollTo_time: 800,
    //auto scrollTo
    // Gmap
    txt_gmap_loading: "n&uacute; Map 讀取中...",
    txt_gmap_loaded: "n&uacute; Map 讀取完成",
    img_gmap_marker_garmin        : richPOI_i_dir + "garmin_place2.png",
    img_gmap_marker_garmin_shadow : richPOI_i_dir + "garmin_place2_shadow.png",
    img_gmap_marker_shadow        : richPOI_i_dir + "icon-shadow.png",
    img_gmap_marker_srch          : richPOI_i_dir + "arrow.png",
    img_gmap_marker_srch_shadow   : richPOI_i_dir + "arrowshadow.png",

    // Gmap init
    init_lat      : 25.061091390109645,
    init_lon      : 121.6401877847871,
    init_scale    : 11,
    inti_g_map    : null,
    init_geocoder : null,
	init_ani_move : true,

    //init garmin Bubble
    init_html: "Garmin 歡迎您的加入.",
    init_layout_autoresize: 1,
    // auto layout
    init_onoff_place_marker: 1,
    //show result marker ?
    maxInfoWindow: 0,
    init_GBwindow_click: 0,

    // click count url , tags search url
    url_count        : "/connect/poi/score",
    url_tags_search  : "/connect/poi/list?type=1&name=",
    url_tags_search2 : "/connect/poi/list?type=2&name=",
    url_place_search : "/connect/poi/addr?",
    url_pnd_w        : "/connect/poi/red?w=",
    url_maxcontent   : "/connect/poi/pic?status=1&pid=",

    // others
    ajax_respone_time: 20000,
    template_i_dl: richPOI_i_dir + "btn_dl.jpg",
    GB_pathToImage: richPOI_i_dir + "indicator_circle_thickbox.gif",
    GB_pathToImage_close: richPOI_i_dir + "close.gif",
    extend_bounds: 1,
    init_tabs_cookie: 30,
    // cookie expire date, remember tabs item.
    //init 1st
    init_tab0_url: "/connect/poi/top",
    // 熱門排行榜 "/connect/poi/list?tid=10&name="+encodeURIComponent('遊')+"&type=2&orderBy=point"
    fav_add_url: "/connect/user/addFavorite",
    //加到我的最愛
    fav_my_url: "/connect/poi/favl",
    // 我的最愛列表
    fav_edit_url: "/connect/user/editsinglefavb",
    //修改單點我的最愛
    fav_del_url: "/connect/user/delsinglefavb",
    //刪除單點我的最愛
    fav_manage_url: "/connect/user/manage",
    //我的最愛管理介面
    send2garmin_url: "/connect/send2Garmin/s2g",
    share_poi_step1: "/connect/share/step1",

    share_upload : "/connect/share/uploadGPX",
    share_edit   : "/connect/share/shareEdit",

    login_url    : "/connect/login/login",
    logout_url   : "/connect/login/logout"
};

var resize_ = i18n.init_layout_autoresize;
var lat = i18n.init_lat;
var lon = i18n.init_lon;
var scale = i18n.init_scale;
var g_map = i18n.g_map;
var geocoder = i18n.geocoder;
var count_url = i18n.url_count;
var tags_url = i18n.url_tags_search;
var tags_url2 = i18n.url_tags_search2;
var place_url = i18n.url_place_search;

var gmarkers = [];
var my_markers = [];
var htmls = [];
var titles = [];
var srch_find = [];

// $.browser.msie  = safari , opera , msie ,mozilla
var offset_ = ($.browser.mozilla) ? 1 : 0;
var offset_gmap = ($.browser.mozilla) ? 5 : 2;

// set Bubble window size
//var a_height = $(window).height();
var a_height = $.browser.opera ? window.innerHeight : $(window).height();

var a_tf = a_height > 750;

var p_w_b_w = (a_tf) ? 215 : 150 ;
var p_w_b_h = (a_tf) ? 165 : 100 ;
var p_w_s_h = (a_tf) ? 150 : 50 ;

/* gmap_init
 ----------------------------------------------------------*/
/* search tabs */
$(function () {
    $("div.tabs div.tabNavigation a").each(

    function (i) {
        $(this).bind("click", function () {
            $('div.tabs div.tabNavigation a').removeClass('selected');
            $(this).addClass('selected');
            $('div.tabs-content').hide();

            $('div.tabs-content').eq(i).show();
        })
    })
    //$('#container-1 ul').tabs({ cookie: { expires: i18n.init_tabs_cookie } });
});

function load_list(tag_url, reload_, tabs_set, show_map) {
_my = 0;
tab0_use_ = 0;

    // tab1_use_ = 0;
    //    g_map.removeOverlay(init_marker);
    g_map.DeleteShape(init_marker)
    if (!first_load) {
        //        g_map.clearOverlays();
		g_map.DeleteAllShapes();
    }

    var tabs_set_ = tabs_set;
    $('#loading-indicator').html(i18n.txt_search_process).toggle();
    //enhanced & 1 way
    $("#box_overlay").show();
    if ($.browser.msie) {
        $("select").hide();
    }
    $.ajax({

        url: tag_url,
        cache: false,
        success: function (html) {
            $("#searchpoi .content").html(html);

            //init 1st
            //$('#container-1 ul').tabs('select', 0);
            if (tabs_set_ != 99) {
                if (!tabs_set_) {
                    $('#container-1 ul').tabs('select', 0);
                } else {
                    $('#container-1 ul').tabs('select', tabs_set_);
                }
            }

            scTop("#searchpoi .content");
            $('#loading-indicator').html(i18n.txt_process_done).slideUp(i18n.indicator_slide_time);

            if ($("div#garmintable table#srch-result tbody tr").length <= 0) {
                clearmarkers();
                tab0_data_ = 1;
            } else {
                showMap();
                tab0_data_ = 0;
                first_load = 1;

                $("div#garmintable table#srch-result tbody tr").each(

                function (i) {
                    $(this).bind("click", function () {
                        $(this).siblings().removeClass('selected');
                        $(this).addClass('selected');
                        var d = $(this).find("a").attr("id")
                        var lat = $(this).find("a").attr("lat")
                        var lon = $(this).find("a").attr("lon")
                        myclick(i, d, lat, lon);

                     if (login_) {
						tab0_use_ = 1;
						tab0_id = i;
						}

                        $("#searchpoi .content").scrollTo($(this), 1000, {
                            offset: -100
                        }, {
                            easing: 'swing'
                        });
                        return false;
                    })


                });

                $("#Searchresult a").click(function () {
                    load_list($(this).attr('lnk'));
                    return false;
                })
                $("#pagenavi a").click(function () {
                    load_list($(this).attr('lnk'));
                    return false;
                })

	                $("div#garmintable table#srch-result tbody tr").eq(0).click();
            }
            //enhanced & 1 way
            $("#box_overlay").hide();
            if ($.browser.msie) {
                $("select").show();
            }
        },
        error: function (r, error) {

            if (error = "timeout") {
                $('#loading-indicator').html("回應逾時, 請稍候再試.").slideUp(3000);
            } else {
                $('#loading-indicator').html("程式似乎有點問題, 請稍修再試").slideUp(3000);
            }
            //enhanced & 1 way
            $("#box_overlay").hide();
            if ($.browser.msie) {
                $("select").show();
            }

        },
        //        error: function(r) {
        //            $('#loading-indicator').html(i18n.txt_process_done).slideUp(i18n.indicator_slide_time);
        //            alert(i18n.txt_process_error + '\n\n' + r.responseText)
        //        },
        timeout: i18n.ajax_respone_time
    });
}





/* Map control Fn -------------------------------------------------------------*/

function myclick(markerNum, d, lat, lon) {

    _infowin.Close();
//	g_map.CloseAllInfoWin();

		gmarkers[markerNum].OpenInfoWin();

    $.get(count_url, {
        id: d
    });

    $("#poi-content").css("height", p_w_s_h);
    //    $("#poi-show-big-img").css("height", p_w_b_h).css("width", p_w_b_w);
}

function showMap(rl_) {

// login & search, switch tab0 show final result
var _show_no = rl_;

	_my = 0;
    clearmarkers();
//		g_map.DeleteAllShapes();

    var bounds = [];
    g_bounds = [];

    $("div#garmintable #srch-result a").each(function (i) {
        var _id = $(this).attr('id');
        var _t = $(this).attr('title');
        var _lat = $(this).attr("lat");
        var _lon = $(this).attr("lon");
        var _i1 = $(this).attr('i1');
        var _i2 = $(this).attr('i2');
        var _i3 = $(this).attr('i3');
        var _i4 = $(this).attr('i4');
        var _i5 = $(this).attr('i5');

        _i2 = (_i2) ? "<a href=\"javascript:void(0)\" id=\"poi_2\"><img src=\"" + _i2 + "\" onclick='chg_poi_photos(this.src)' /></a>" : "";
        _i3 = (_i3) ? "<a href=\"javascript:void(0)\" id=\"poi_3\"><img src=\"" + _i3 + "\" onclick='chg_poi_photos(this.src)' /></a>" : "";
        _i4 = (_i4) ? "<a href=\"javascript:void(0)\" id=\"poi_4\"><img src=\"" + _i4 + "\" onclick='chg_poi_photos(this.src)' /></a>" : "";
        _i5 = (_i5) ? "<a href=\"javascript:void(0)\" id=\"poi_5\"><img src=\"" + _i5 + "\" onclick='chg_poi_photos(this.src)' /></a>" : "";

        var _d = $(this).attr('desc');
        var _tl = $(this).attr('tel');
        var _a = $(this).attr('addr');
        var _tag = $(this).attr('tags');
        var _u = $(this).attr('update');

        var html = '';
        html += "<table id='poi'><tr><td colspan='2' align='center' id='poi-title'>" + _t + "</td></tr><tr><td id='poi-big-td'>";
        if (_i1 == undefined) {
            html += "<div id=\"poi-show-big\">";
        } else {
            html += "<div id=\"poi-show-big\"><img src=\"" + _i1 + "\" alt=\"\" id=\"poi-show-big-img\" style='height:" + p_w_b_h + "px;width:" + p_w_b_w + "px' />";
        }
        //html += "<div id=\"poi-show-big\"><img src=\"" + _i1 + "\" alt=\"\" id=\"poi-show-big-img\" style='height:" + p_w_b_h + "px;width:" + p_w_b_w + "' /></div>";
        html += "</td><td id='poi-desc-td'>";
        html += "<ul class=\"list\">";
        html += "<li class=\"article-add\">地址：" + _a + "</li>";
        html += "<li class=\"article-tel\">電話：" + _tl + "</li>";
        html += "</ul>";
        html += "<a href=" + i18n.url_pnd_w + _id + "&t=" + encodeURIComponent(_t) + " onclick=\"dotb('下載-" + _t + "', this.href);return false\"><img src=\"" + i18n.template_i_dl + "\" alt=\"點我下載\" /></a> <br> ";
        html += "<a onclick='_maximumWin_open(\"" + i + "\"); return false;' href='javascript:void(0)' class='lnk-fn'> * 詳細內容</a> ";
        html += "| <a onclick='add2fav(" + _id + ",\"" + _t + "\"); return false;' href='javascript:void(0)' class='lnk-fn'> + 加入收藏</a>";
        //        html += "| <a onclick='send2garmin(" + _id + "); return false;' href='javascript:void(0)' class='lnk-fn'> + s2g</a>";
        html += "</div>";
        html += "<br />相關標籤: ";

        var tmp = (_tag) ? _tag.split(",") : [];
        //  var dot = ',';
        for (var t = 0; t < tmp.length && t < 3; t++) {
            //dot = (t == tmp.length - 1 || t == 2) ? "" : "";
            html += '<a href="javascript:void(0)" onclick=\'load_list("' + tags_url2 + encodeURIComponent(tmp[t]) + '&orderBy=point ");return false; \' class="lnk-tag" />' + tmp[t] + '</a> ';
        }

        html += "</td></tr><!--<tr><td colspan=\"2\"><hr>";
        html += "<div id=\"poi-content\"><div id=\"poi-show-thumb\">";

        if (a_tf) {
            html += "<a href=\"javascript:void(0)\" id=\"poi_1\"><img src=\"" + _i1 + "\" onclick='chg_poi_photos(this.src)' /></a>";
            html += _i2 + _i3 + _i4;
        }

        html += "</div>";
        html += "<div class=\"article-body\">";
        html += _d;
        html += "<div class=\"article-date\">更新日期：" + _u + "</div>";
        html += "</div></div>";
        html += "</td></tr>--></table>";

        // create the marker
        //        var point = new GLatLng(_lat, _lon);
        var point = new GLatLon(_lat, _lon);
        var p_marker = createMarker(_id, point, i, html, _t);

//                g_map.addOverlay(marker);
//        _layer.AddShape(marker);

        g_map.AddShape(p_marker);

        gmarkers.push(p_marker);
        htmls.push(html);
        titles.push(_t);

        //        bounds.extend(point);
        //        g_bounds.extend(point);
        g_bounds.push(point);
        bounds.push(point);

  if (i == $("div#garmintable #srch-result a").size() - 1) {
    // do stuff
if (login_ && tab0_use_ && (_show_no != 'undefind')){
//alert('_show_no 1')
		g_map.SetAnimationEnabled(false);
			g_map.SetCenter(new GLatLon(gmarkers[_show_no].Latitude,gmarkers[_show_no].Longitude));
		g_map.SetAnimationEnabled(true);

		gmarkers[_show_no].OpenInfoWin();

//					myclick(_show_no);
//alert('_show_no 2')

//        $("div#garmintable table#srch-result tbody tr").eq(_show_no).click();
//        $("div#garmintable table#srch-result tbody tr").eq(_show_no).addClass('selected');
        scroller("div#searchpoi .content", _show_no);
}


  }


    });

//		g_map.SetAnimationEnabled(false);
//		g_map.AddShapeLayer(_layer, true);
//		g_map.SetAnimationEnabled(true);


//      alert("tab0_data_ = "+ tab0_data_ + 'first_load ='+first_load);
    _view = g_map.GetView();

    //	var pin = layer.GetShapeByID(id);
    _infowin.SetOptions({ enableMaximize: true });

    _infowin.AttachEvent('maximizeclick', function (p_marker, e) {
        maximumWin_open(p_marker, e, p_marker.t, p_marker.getPostMax);
    });

/*

    _infowin.AttachEvent('restoreend', function (p_marker) {
        maximumWin_restore(p_marker);
    });

    _infowin.AttachEvent('close', function (p_marker) {
		alert('close_shoMap : showMap')
        maximumWin_close(p_marker);
    });
*/
}


/* creatMarker*/

function createMarker(id, point, number, html, t) {
    var rank = number + 1;

    var img_out = richPOI_i_no_dir + "icon-" + rank + ".png";
    var img_hover = richPOI_i_no_dir + "icon-" + rank + "-2.png";

    var iconOption = {
        icon: img_out
    };

    var marker = new GShape(GShapeType.Pushpin, point, iconOption);
    marker.SetMouseEventType(Garmin.GMap.MouseEvent.MouseClick);

    marker.SetInfoWindowWidth(InfoWindowW);
    marker.SetInfoWindowHeight(InfoWindowH);

//    marker.SetTitle(t);
    marker.SetTitle('&nbsp;');
    marker.SetDescription(html);
    marker.SetCustomIcon(img_out);
    marker.SetHoverImage(img_hover);

    marker.img_out   = img_out;
    marker.img_hover = img_hover;

    var rnd = Math.floor(Math.random() * 1000001);
    marker.getPostMax = '<iframe width="' + iframeWidth + '" height="' + iframeHeight + '" frameborder="0" marginheight="0" marginwidth="0" src="' + i18n.url_maxcontent + id + '&__=' + rnd + '" id="max-frame" name="post"></iframe>';

    marker.t = t;

    marker.AttachEvent('onclick', function (pin) {
        $("#poi-content").css("height", p_w_s_h);
        $("#poi-show-big-img").css("height", p_w_b_h).css("width", p_w_b_w);
        $("table#srch-result tbody tr").eq(number).addClass('selected');
        scroller("div#searchpoi .content", number);
    });

    marker.AttachEvent('onmouseover', function (pin) {
        pin.SetZIndex(1010);
    });

    marker.AttachEvent('onmouseout', function (pin) {
        pin.SetZIndex(900);
    });

    marker.addInfoWindowListener('open', function (pin) {
        pin.SetCustomIcon(img_hover);
        pin.SetZIndex(1010);

		if (i18n.init_ani_move) {

        var loc = g_map.LatLongToPixel(pin.GetPoints()[0]);
        var pos_x = (g_map.GetWidth() - InfoWindowW) / infowin_move_dist,
            pos_y = (g_map.GetHeight() - InfoWindowH) / infowin_move_dist + InfoWindowH - 20;

        var m_x = Math.round(loc.x - pos_x); //pos_x ;
        var m_y = Math.round(loc.y - pos_y); //pos_y ;
        g_map.PanByPixel(new GPixel(m_x, m_y)); //move

		} else {
			g_map.SetCenter(pin.GetPoints()[0]);
		}

    });

    marker.addInfoWindowListener('close', function (pin) {
        $("table#srch-result tbody tr").eq(number).removeClass('selected');

        var bound = GLatLonRectangle.FromLocations(g_bounds);

		g_map.SetAnimationEnabled(false);

		g_map.SetOptions({
            bounds: bound
        });
		g_map.SetAnimationEnabled(true);

        pin.SetCustomIcon(img_out);
        pin.SetZIndex(900);

        g_map.ShowScaleBar();
        g_map.ShowDashboard();

    });

    return marker;
}

/* func 4 maximum info window */

function _my_maximumWin_open(nu) {

    g_map.HideDashboard();
    g_map.HideScaleBar();

    _infowin.SetOptions({
        maxTitle: '<b class="popMaxtitle">' + my_markers[nu].t + '</b>',
        maxContent: my_markers[nu].getPostMax,
        offset: new GPixel(0, 0),
        maxWidth: maxWinWidth,
        maxHeight: maxWinHeight
    })

    _infowin.Maximize();

	if (i18n.init_ani_move) {

    var loc = g_map.LatLongToPixel(my_markers[nu].GetPoints()[0]);
    var pos_x = (g_map.GetWidth() - maxWinWidth) / infowin_move_dist,
        pos_y = (g_map.GetHeight() - maxWinHeight) / infowin_move_dist + maxWinHeight;

    var m_x = Math.round(loc.x - pos_x); //pos_x ;
    var m_y = Math.round(loc.y - pos_y); //pos_y ;
    g_map.PanByPixel(new GPixel(m_x, m_y)); //move

	} else {
			g_map.SetCenter(my_markers[nu].GetPoints()[0]);
	}

}

function _maximumWin_open(no) {

    g_map.HideDashboard();
    g_map.HideScaleBar();

    _infowin.SetOptions({
        maxTitle: '<b class="popMaxtitle">' + gmarkers[no].t + '</b>',
        maxContent: gmarkers[no].getPostMax,
        offset: new GPixel(0, 0),
        maxWidth: maxWinWidth,
        maxHeight: maxWinHeight
    })

    _infowin.Maximize();

	if (i18n.init_ani_move) {
    var loc = g_map.LatLongToPixel(gmarkers[no].GetPoints()[0]);
    var pos_x = (g_map.GetWidth() - maxWinWidth) / infowin_move_dist,
        pos_y = (g_map.GetHeight() - maxWinHeight) / infowin_move_dist + maxWinHeight;

    var m_x = Math.round(loc.x - pos_x); //pos_x ;
    var m_y = Math.round(loc.y - pos_y); //pos_y ;
    g_map.PanByPixel(new GPixel(m_x, m_y)); //move

		} else {
			g_map.SetCenter(gmarkers[no].GetPoints()[0]);
		}



}

function maximumWin_open(pin, e, t, content) {

    g_map.HideDashboard();
    g_map.HideScaleBar();

    _infowin.SetOptions({
        maxTitle: '<b class="popMaxtitle">' + t + '</b>',
        maxContent: content,
        offset: new GPixel(0, 0),
        maxWidth: maxWinWidth,
        maxHeight: maxWinHeight
    })

	if (i18n.init_ani_move) {

    var loc = g_map.LatLongToPixel(pin.GetPoints()[0]);
    var pos_x = (g_map.GetWidth() - maxWinWidth) / infowin_move_dist ,
        pos_y = (g_map.GetHeight() - maxWinHeight) / infowin_move_dist + maxWinHeight;


    var m_x = Math.round(loc.x - pos_x); //pos_x ;
    var m_y = Math.round(loc.y - pos_y); //pos_y ;
    g_map.PanByPixel(new GPixel(m_x, m_y)); //move

		} else {
			g_map.SetCenter(pin.GetPoints()[0]);
		}

}

function maximumWin_restore(pin) {
    _infowin.Restore();

    g_map.ShowDashboard();
    g_map.ShowScaleBar();
}

function maximumWin_close(pin) {
//	if (!pin) {
	var tt = pin.t;
	if (tt != undefined)
	{
		alert(tt +' | '+pin.IsInfoWinOpen())
//		pin.CloseInfoWin();
	}

    g_map.ShowDashboard();
    g_map.ShowScaleBar();
	//alert("maximumWin_close()")
}


/* clearOlderSrchMarker */

function clearOlderSrchMarkers() {
    var sf_len = srch_find.length;
    if (sf_len > 0) {

        for (var i = 0; i < sf_len; i++) {
//            g_map.removeOverlay(srch_find[i]);
			g_map.DeleteShape(srch_find[i])
        }

//      g_map.DeleteAllShapes();

    }
    srch_find = [];

}

/* clearMarker */

function clearmarkers() {
    //    g_map.closeInfoWindow();
	    _infowin.Close();

    var gm_len = gmarkers.length;

    if (gm_len > 0) {
        try {
            for (var i = 0; i < gm_len; i++) {
                //                g_map.removeOverlay(gmarkers[i]);
                g_map.DeleteShape(gmarkers[i])
            }
        } catch (e) {}
    }

    // reset array
//    g_map.DeleteAllShapes();
    gmarkers = [];
    htmls = [];
    titles = [];
}


/* greybox onclick function by Vincent/Y2 */
var GB_ANIMATION = true;
var GB_btn_close = true;
var GB_click_overlay = false;
var GB_html_overflow = true;

function dotb(title, url) { //4 download
    GB_show(title, url, 300, 450, "", true);
}

function notice(title, url) {
    GB_show(title, url, 390, 550);
}

/*---------- Document ready --------------------------------------------------*/
$(document).ready(function () {
    $('#loading-indicator').html(i18n.txt_gmap_loading); // info -----
    $("#container-1 > ul").tabs({
        selected: tab_cookie_id,
        select: function (e, ui) {
            login_ = ($.cookie("username")) ? 1 : 0;

            if (ui.index == 0 && tab1_use_ == 1) {
                if (first_load) {
                    //                    g_map.clearOverlays();
//                    g_map.DeleteAllShapeLayers();
					g_map.DeleteAllShapes();

                }
                if (!tab0_data_ && first_load) {
//					alert(tab0_id)
                    showMap(tab0_id);
                }
            }

            if (ui.index == 1 && login_ && tab1_use_ == 1) {
                showMap_my(tab1_id);
            }
        },
        show: function (e, ui) {
            var tab_id = ui.index;
            tab_id_which_one = ui.index;
            $.cookie("the_tab_cookie", tab_id, {
                expires: i18n.init_tabs_cookie
            });
        }
    });

/*
     fx: {height: 'toggle', opacity: 'toggle' }
     event: 'mouseover'
     selected:1
     disabled: [2]
     */


    function _resize() {
        var _height = $(window).height();
        var heightNeeded = _height - $('#header').height() - $('#footer').height() - 5;

        var w_h = $('#wrapper').height();

        if (resize_) {
            main_hieght = heightNeeded;

            $('#extra , #wrapper, #content').height(heightNeeded);
            $('#gg-map').height(heightNeeded - offset_gmap);

            var e_ds = $('#extra #tab-menu').height();
            var e_ = (heightNeeded - e_ds - offset_); // padding top-bottom 10+10 = 20px
            $('#extra #container-1').height(e_);
        } else {
            main_hieght = w_h - 1;
        }

    }

    $(window).wresize(_resize);
    _resize();

    //    if (GBrowserIsCompatible()) {
    g_map = new GarMap('gg-map');
    g_map.onLoadMap = function () {
        // init_anchore = getStartLocation();
        //start_app();
        _infowin = g_map.GetInfoWindow();
        _view = g_map.GetView();
//        _layer = new GShapeLayer();

        //init set maxcontent width
        maxWinWidth = _maxWin_W ? g_map.GetWidth() - maxWinWidthMinus : maxWinWidth;

        //init set maxcontent height
        maxWinHeight = _maxWin_H ? g_map.GetHeight() - maxWinHeightMinus : maxWinHeight;

        //init set maxcontent ifarme height
        iframeHeight = maxWinHeight - $(".main_title").height() - 60;

    $('#loading-indicator').html(i18n.txt_gmap_loaded).slideUp(i18n.indicator_slide_time);

    };

    g_map.LoadMap();

    g_map.SetCenterAndZoom(new GLatLon(lat, lon), 10);

    init_iconOption = {
        icon: i18n.img_gmap_marker_garmin,
        width: 69,
        height: 112
    };
    point = new GLatLon(lat, lon);
    init_marker = new GShape(GShapeType.Pushpin, point, init_iconOption);

    init_marker.SetMouseEventType(Garmin.GMap.MouseEvent.MouseClick);
    // init_marker.SetTitle(t);
    init_marker.SetDescription(i18n.init_html);


    g_map.AddShape(init_marker);

//    init_marker.AttachEvent('onclick', function (pin) {
//        pin.OpenInfoWin();

//    });

    //    }
    /*----- on click set -----------------------------------------------------*/
    $('#accordion a').click(function () {
        clearOlderSrchMarkers();
        load_list($(this).attr('lnk'));
        return false;
    });
    $('div#doc a').click(function () {
        clearOlderSrchMarkers();
        load_list($(this).attr('lnk'));
        return false;
    });

    $('#srch-place').submit(function () {
        var tag1 = $("#tag1").val();
        if (tag1 == "") {
            alert(i18n.txt_search_nokeyword);
            $("#tag1").focus();
            return false;
        }

        $('#loading-indicator').html(i18n.txt_search_place).toggle();
        if (tag1) {
            load_list(tags_url + encodeURIComponent(tag1) + "&searchType=fulltext");
            clearOlderSrchMarkers();
        }
        return false;
    });

// search
/*
    $('#srch-complex').submit(function () {
        var addr = $("#addr").val();
        var name = $("#name").val();
        if (trim(name) == "" && trim(addr) == "") {
            alert(i18n.txt_search_noinput);;
            //            $("#keyword").focus();
            return false;
        }

        $('#loading-indicator').html(i18n.txt_search_place).toggle();

        if (geocoder) {
            geocoder.getLatLng(addr, function (point) {
                if (!point) {
                    alert(i18n.txt_search_place_notfound + addr);
                    $('#loading-indicator').html(i18n.txt_search_place_done).slideUp(i18n.indicator_slide_time);
                } else {
                    var marker = new GMarker(point);


//                var scale = g_map.getZoom();
                var scale = g_map.GetZoomLevel();
//                var center = g_map.getCenter();
                var center = g_map.GetCenter();
//					g_map.setCenter(point, scale);
				g_map.SetCenterAndZoom(point, scale);

var topleft = g_map.GetMapBound().TopLeftLatLong;
var bottomright = g_map.GetMapBound().BottomRightLatLong;
var l1 = topleft.Latitude;
var l2 = bottomright.Longitude;
var r1 = bottomright.Latitude;
var r2 = topleft.Longitude;

//                    var bounds = g_map.getBounds();
//                    var l1 = bounds.getNorthEast().lat();
//                    var l2 = bounds.getSouthWest().lng();

//                    var r1 = bounds.getSouthWest().lat();
//                    var r2 = bounds.getNorthEast().lng();

                    if (i18n.init_onoff_place_marker) {
                        clearOlderSrchMarkers();

                        var markerOpts = {};
                        var sIcon = new GIcon(srchIcon);
                        markerOpts.icon = sIcon;
                        var marker = new GMarker(point, markerOpts);

                        g_map.addOverlay(marker);
                        marker.openInfoWindowHtml(addr);
                        GEvent.addListener(marker, "click", function () {
                            marker.openInfoWindowHtml(addr);
                        });

                        srch_find.push(marker);
                    }

                    for (var r = 0; r < _p.length; r++) {
                        dot = (r == _p.length - 1) ? "" : ",";
                        _pa += $.trim(_p[r]) + dot;
                    }

                    load_list(place_url + "l1=" + l1 + "&l2=" + l2 + "&r1=" + r1 + "&r2=" + r2 + "&name=" + encodeURIComponent(_pa) + "&addr=" + encodeURIComponent(addr) + "&searchType=fulltext");

                    $('#loading-indicator').html(i18n.txt_search_place_done).slideUp(i18n.indicator_slide_time);
                }
            });
        }
        return false;
    });
*/

    $('#srch-keyword').submit(function () {
        var addr = $("#addr").val();
        var name = $("#name").val();
        var searchType = $("#searchType").val();
        //       var seachArea = $("#searchArea").val();
        var searchArea = 'partialarea'

        if (trim(name) == "" && trim(addr) == "") {
            alert(i18n.txt_search_noinput);
            //            $("#keyword").focus();
            return false;
        }

        if (searchArea == "partialarea") {

            $('#loading-indicator').html(i18n.txt_search_place).toggle();
//                var scale = g_map.getZoom();
                var scale = g_map.GetZoomLevel();
//                var center = g_map.getCenter();
                var center = g_map.GetCenter();

var topleft = g_map.GetMapBound().TopLeftLatLong;
var bottomright = g_map.GetMapBound().BottomRightLatLong;
var l1 = topleft.Latitude;
var l2 = bottomright.Longitude;
var r1 = bottomright.Latitude;
var r2 = topleft.Longitude;

/*
            var bounds = g_map.getBounds();
            var l1 = bounds.getNorthEast().lat();
            var l2 = bounds.getSouthWest().lng();
            var r1 = bounds.getSouthWest().lat();
            var r2 = bounds.getNorthEast().lng();
*/
            load_list(place_url + "l1=" + l1 + "&l2=" + l2 + "&r1=" + r1 + "&r2=" + r2 + "&addr=" + encodeURIComponent(addr) + "&name=" + encodeURIComponent(name) + "&searchArea=" + searchArea + "&searchType=" + searchType);

            $('#loading-indicator').html(i18n.txt_search_place_done).slideUp(i18n.indicator_slide_time);
            clearOlderSrchMarkers();
        } else { //action-->list
            load_list(tags_url + encodeURIComponent(name) + "&addr=" + encodeURIComponent(addr) + "&searchArea=" + searchArea + "&searchType=" + searchType);

            clearOlderSrchMarkers();
        }

        return false;
    });

    // init 1st
    // tabs = 0, get top10 poi or something...
    //var init_tab = $('#container-1 > ul').data('selected.tabs');
    if (login_) {
        // load_list(i18n.init_tab0_url , null , 99 );
        load_list_my(i18n.fav_my_url, null, 1);
        intro_login();
        var username = $.cookie("username");

        //        $("div#header #login").html('<br>' + username + ' 你好 ,  <a href="javascript:void(0)" class="white" id="lnk-logout">登出</a> | <a class="white" href="http://my.garmin.com.tw/blog/" target="_blank">樂活網開發日誌</a>')
        $("div#header #login").html('<br>' + username + ' 你好 ,  <a href="javascript:void(0)" class="white" id="lnk-logout">登出</a>')
    } else {
        $("div.notlogin").slideDown(500);
        if (tab_cookie_id != 0) {
            tabs_init_set_ = 99;
        }
        load_list(i18n.init_tab0_url, null, tabs_init_set_); // set init tabs0 url
    }

    $('a#btn-login, a#lnk-login').click(function () {
        var login_title = "登入 MyGarmin 會員";
        var login_url = i18n.login_url;
        //$.cookie("btn_clk_cookie", 1, i18n.init_tabs_cookie);
        $.cookie("btn_clk_cookie", 1, cookie_options);
        GB_show(login_title, login_url, 250, 490);
        return false;
    });

    $('a#btn-login-intro').click(function () {
        var login_title = "登入 MyGarmin 會員";
        var login_url = i18n.login_url;
        //$.cookie("btn_clk_cookie", 2, i18n.init_tabs_cookie);
        $.cookie("btn_clk_cookie", 2, cookie_options);
        GB_show(login_title, login_url, 250, 490);
        return false;
    });

    $('a#lnk-logout').click(function () {
        logout();
        return false;
    });

    // intro click
    $('a#btn-login-intro-upload').click(function () {
        GB_show("景點分享 - 景點上傳", i18n.share_upload, 730, 700);
        return false;
    });

    $('a#btn-login-intro-input').click(function () {
        GB_show("景點分享 - 手動輸入景點", i18n.share_edit, 730, 700);
        return false;
    });

    $('a#btn-login-intro-manage').click(function () {
        mysharemanage(favId);
        return false;
    });

    //hot accordion
    lastBlock = $("ul#accordion li#a1");
    maxWidth = 510;
    minWidth = 30;

    $("ul#accordion li").click(function () {
        $(lastBlock).animate({
            width: minWidth + "px"
        }, {
            queue: false,
            duration: 300
        });
        $(this).animate({
            width: maxWidth + "px"
        }, {
            queue: false,
            duration: 300
        });
        lastBlock = this;
    });

});


// vincent's Fn

function chg_poi_photos(d) {
    $('#poi-show-big-img').attr('src', d);
}

function scTop(id_scroll) {
    var id = id_scroll;
    $(id).scrollTo(0, i18n.scrollTo_time, {
        onAfter: function () {}
    });
}

function scroller(id_scroll, n) {
    var id = id_scroll;
    $(id).scrollTo('table#srch-result tbody tr:eq(' + n + ')', i18n.scrollTo_time, {
        easing: 'swing',
        onAfter: function () {}
    });
}

function maximizeInfoWindow(opt_id, opt_params) {
    if (gApplication) {
        gApplication.maximizeInfoWindow(opt_id, opt_params);
    }
    return false;
}

function add2fav(d, t) {
    if ($.cookie("username") && $.cookie("token")) {
        var add_title = "加入到我的最愛";
        var add_url = i18n.fav_add_url + "?d=" + encodeURIComponent(d) + "&t=" + encodeURIComponent(t);
        GB_show(add_title, add_url, 260, 500);
    } else {
        alert("你尚未登入喲!!!")
    }
}

function editmyfav(d, t, cateId, fid) {
    var edit_title = "修改我的最愛";
    var edit_url = i18n.fav_edit_url + "?pid=" + d + "&pname=" + encodeURIComponent(t) + "&cateId=" + cateId + "&fid=" + fid;
    GB_show(edit_title, edit_url, 255, 500);
}

function delmyfav(d, t, cateId) {
    var del_title = "刪除我的最愛";
    var del_url = i18n.fav_del_url + "?pid=" + d + "&pname=" + encodeURIComponent(t) + "&cateId=" + cateId;
    GB_show(del_title, del_url, 150, 500);
}

function mymanage(d) {
    if ($.cookie("username")) {
        var man_title = "管理我的最愛";
        var man_url = i18n.fav_manage_url;
        var man_fn = "mymanage_update()"

        if (d == 2) {
            var man_title = "管理我的分享";
            var man_url = "/connect/user/editfav?cateId=48&flag=1";
            var man_fn = null;
        }

        GB_show(man_title, man_url, 500, 750, man_fn);
    } else {
        alert("你尚未登入喲!!!")
    }
}

function mysharemanage(favId) {
    var man_title = "管理我的分享";
    var man_url = "/connect/user/editfav?flag=1&cateId=" + favId;
    GB_show(man_title, man_url, 500, 750, 'mymanage_update_cateId(' + favId + ')');
}

function mymanage_update_cateId(favId) {
    tab1_id = 0;
    var fav_my_url1 = "/connect/poi/favl?cateId=" + favId
    load_list_my(fav_my_url1, null, 1);
}


function logout() {
    $.cookie('username', null);
    parent.window.location.reload(true);
}

function mymanage_update() {
    tab1_id = 0;
    load_list_my(i18n.fav_my_url, null, 1);
}

function send2garmin(id) {
    var send2garmin_url = i18n.send2garmin_url + "?id=" + id;
    GB_show("send2garmin", send2garmin_url, 500, 800);
}

function step1() { //選擇分享方式：1-手動新增;2-上傳檔案
    var man_title = "分享景點";
    GB_show(man_title, i18n.share_poi_step1, 200, 350, 'mymanage_update()');

}

function sharepoi2() {
    GB_show("POI Share", i18n.share_poi_step1, 730, 700);
}

function sharepoi3() {
    GB_show("POI Share", i18n.share_poi_step1, 730, 700);
}

function intro_login() {
    parent.$('#intro div.notlogin').hide();
    parent.$('#intro div.login-yes').show();
    parent.$('#mypoi div.notlogin').hide();
    parent.$('#mypoi div.login-yes').show();
}

function trim(str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}


/* new 2011/08/24 get start location */

function getStartLocation() {
    if (navigator && navigator.geolocation) {
        // HTML5 GeoLocation
        navigator.geolocation.getCurrentPosition(setUserPosition);
        return true;
    }
    return false;
}

function setUserPosition(position) {
    var userPos = {
        "lat": position.coords.latitude,
        "lng": position.coords.longitude
    }

    var center = new GLatLon(userPos.lat, userPos.lng);
    g_map.SetCenterAndZoom(center, 10);
}

function setAnchorCenter() {
    var center = g_map.GetCenter();

    $("#stats").html(i18n.txt_info_latlng + center.toString() + i18n.txt_info_scale + scale);

    CenterMarker = new GShape(GShapeType.Pushpin, new GLatLon(center.Latitude, center.Longitude), AnchorIcon_options);
    g_map.AddShape(CenterMarker);
    CenterMarker.SetLocation(g_map.GetCenter());

    g_map.AttachEvent("onchangeview", function () {

        var scale = g_map.GetZoomLevel();
        CenterMarker.SetLocation(g_map.GetCenter());

        $("#stats").html(i18n.txt_info_latlng + center.toString() + i18n.txt_info_scale + scale);

    });
}



function createMarker_my(id, point, number, html, t, cateId) {

        var iconOption = {
            icon: i18n.img_gmap_marker_srch
        };

    var marker = new GShape(GShapeType.Pushpin, point, iconOption);
    marker.SetMouseEventType(Garmin.GMap.MouseEvent.MouseClick);

    marker.SetInfoWindowWidth(InfoWindowW);
    marker.SetInfoWindowHeight(InfoWindowH);

     var rnd = Math.floor(Math.random() * 1000001);

	 marker.getPostMax = '<iframe width="' + iframeWidth + '" height="' + iframeHeight + '" frameborder="0" marginheight="0" marginwidth="0" src="' + i18n.url_maxcontent + id + '&__=' + rnd + '&cateId=' + cateId + ' " id="max-frame" name="post"></iframe>';

     marker.t =  t;
     marker.SetDescription(html);

//       marker.AttachEvent('onclick', function (pin) {
//		   alert('open');
//        });

        marker.addInfoWindowListener('open', function (pin) {

		if (i18n.init_ani_move) {

		var loc = g_map.LatLongToPixel(new GLatLon(pin.Latitude, pin.Longitude));

        var pos_x = (g_map.GetWidth() - InfoWindowW) / infowin_move_dist,
            pos_y = (g_map.GetHeight() - InfoWindowH) / infowin_move_dist + InfoWindowH - 20;

        var m_x = Math.round(loc.x - pos_x); //pos_x ;
        var m_y = Math.round(loc.y - pos_y); //pos_y ;
        g_map.PanByPixel(new GPixel(m_x, m_y)); //move

		} else {
			g_map.SetCenter(new GLatLon(pin.Latitude, pin.Longitude));
		}


        });

        marker.addInfoWindowListener('close', function (pin) {
		g_map.ShowScaleBar();
	        g_map.ShowDashboard();

	        g_map.PanToLatLong(new GLatLon(pin.Latitude, pin.Longitude));

        });

 return marker;

}

/* 1st load */
function showMap_my(d) {
_my = 1;

      g_map.DeleteAllShapes();

    if ($("div#mypoitable table#srch-result tbody tr").length > 0) {

        tab1_use_ = 1;

        var d_ = d;

        var which = $("div#mypoitable #srch-result a:eq(" + d_ + ")")

        var _id = which.attr("id");
        var lat = which.attr("lat");
        var lon = which.attr("lon");
        var _i1 = which.attr('i1');
        var _t = which.attr("title");
        var _tl = which.attr('tel');
        var _a = which.attr('addr');
        var _tag = which.attr('tags');
        var _cateId = which.attr('cateId');
        var _fid = which.attr('fid');
        var _usernote = which.attr('usernote');

        var max_ = "<a onclick='_my_maximumWin_open(0); return false;' href='javascript:void(0)' class='lnk-fn'> * 詳細內容</a> | <a href='javascript:void(0)' onclick='delmyfav(" + _id + ",\"" + _t + "\",\"" + _cateId + "\");return false;' class='lnk-fn'>- 刪除</a>";

		var html = '';
        html += "<table id='poi'><tr><td colspan='2' align='center' id='poi-title'>" + _t + "</td></tr><tr><td id='poi-big-td'>";
        if (_i1 == undefined) {
            html += "<div id=\"poi-show-big\">";
        } else {
            html += "<div id=\"poi-show-big\"><img src=\"" + _i1 + "\" alt=\"\" id=\"poi-show-big-img\" style='height:" + p_w_b_h + "px;width:" + p_w_b_w + "px' />";
        }


        //    html += "<div style='text-align:left; margin: 10px 10px 5px 20px;'><b>分類</b>: 我的最愛";
        if (_usernote != "") {
            html += "<br /><b>說明</b>: " + _usernote;
        }

        html += "</div>";

        html += "</td><td id='poi-desc-td'>";
        html += "<ul class=\"list\">";
        html += "<li class=\"article-add\">地址：" + _a + "</li>";
        html += "<li class=\"article-tel\">電話：" + _tl + "</li>";
        html += "</ul>";
        html += "<a href=" + i18n.url_pnd_w + _id + "&t=" + _t + " onclick=\"dotb('下載-" + _t + "', this.href);return false\"><img src=\"" + i18n.template_i_dl + "\" alt=\"點我下載\" /></a> <br> " + max_ + "</div>";

        html += "<br />相關標籤:<br />";

        var tmp = (_tag) ? _tag.split(",") : [];
        for (var t = 0; t < tmp.length && t < 3; t++) {
            html += '<a href="javascript:void(0)" onclick=\'load_list("' + tags_url2 + encodeURIComponent(tmp[t]) + '&orderBy=point ");return false; \' class="lnk-tag" />' + tmp[t] + '</a> ';
        }

        html += "</td></tr>";
        html += "</table>";


        var point = new GLatLon(lat, lon);
        var pin_my = createMarker_my(_id, point, i, html, _t, _cateId);

		//alert('AddShape');
		g_map.AddShape(pin_my);
		//alert('setCenter');
		g_map.SetAnimationEnabled(false);
		g_map.SetCenter(point);
		g_map.SetAnimationEnabled(true);
		pin_my.OpenInfoWin();

        $("div#mypoitable table#srch-result tbody tr td:first-child").eq(d_).addClass('selected');
        scroller("div#mypoitable .content", d_);

        my_markers = [];
        my_markers.push(pin_my);

    _infowin.SetOptions({ enableMaximize: true});

    _infowin.AttachEvent('maximizeclick', function (pin_my, e) {
        maximumWin_open(pin_my, e, pin_my.t, pin_my.getPostMax);
    });

/*
    _infowin.AttachEvent('restoreend', function (pin_my) {
			maximumWin_restore(pin_my)
    });

    _infowin.AttachEvent('close', function (pin_my) {
		alert("close: showMap_my")
			maximumWin_close(pin_my);
    });

*/

    }

}



function load_list_my(tag_url, reload_, tabs_set_) {
	_my = 1;
    var tabs_set = tabs_set_;
    if (tabs_set == 1) {
//        g_map.DeleteAllShapeLayers();
		g_map.DeleteAllShapes();
    }

    $('#loading-indicator').html(i18n.txt_search_process).toggle();
    //enhanced & 1 way
    $("#box_overlay").show();
    if ($.browser.msie) {
        $("select").hide();
    }

    if (tabs_set != null) {
        $('#container-1 ul').tabs('select', tabs_set);
    }

    //$('#container-1 ul').tabs('select', 1);
    $.ajax({
        url: tag_url,
        cache: false,
        success: function (html) {
            $("div#mypoi .content").html(html);

            if ($("div#mypoitable table#srch-result tbody tr").length <= 0) {
                if (tab_id_which_one == 1) {
                      g_map.DeleteAllShapes()
                }
            } else {

        my_markers = [];
		var _n = 1;

                $("div#mypoitable table#srch-result tbody tr").each(

                function (i) {

                    $(this).find('span.del').bind("click", function () {
                        var id = $(this).parent().parent().find("a").attr("id")
                        var t = $(this).parent().parent().find("a").attr("title")
                        var cateId = $(this).parent().parent().find("a").attr("cateId")
                        var fid = $(this).parent().parent().find("a").attr("fid")
                        $('tr span.del').removeClass('highlight');
                        $(this).addClass('highlight');

                        delmyfav(id, t, cateId);

                    });

                    $(this).find('span.s2g').bind("click", function () {
                        var lon = $(this).parent().parent().find("a").attr("lon") * 1000000
                        var lat = $(this).parent().parent().find("a").attr("lat") * 1000000
                        var address = $(this).parent().parent().find("a").attr("addr")
                        var phone = $(this).parent().parent().find("a").attr("tel")
                        var name = $(this).parent().parent().find("a").attr("title")
                        var desc = $(this).parent().parent().find("a").attr("feature")
                        $('tr span.s2g').removeClass('highlight');
                        $(this).addClass('highlight');
                        window.open('/connect/api?lon=' + lon + '&lat=' + lat + '&phone=' + phone + '&name=' + encodeURIComponent(name) + '&address=' + encodeURIComponent(address) + '&desc=' + encodeURIComponent(desc), '', 'width=1000,height=00,scrollbars=no');

                    });

                    $(this).find('span.edit').bind("click", function () {
                        var id = $(this).parent().parent().find("a").attr("id")
                        var t = $(this).parent().parent().find("a").attr("title")
                        var cateId = $(this).parent().parent().find("a").attr("cateId")
                        var fid = $(this).parent().parent().find("a").attr("fid")

                        $('tr span.edit').removeClass('highlight');
                        $(this).addClass('highlight');

                        editmyfav(id, t, cateId, fid);
                    });

                    $(this).find('td:first-child').bind("click", function () {

                        tab1_use_ = 1;
                        tab1_id = i;

                        $('tr td:first-child').removeClass('selected');
                        $(this).addClass('selected');
                        var _id = $(this).find("a").attr("id");
                        var lat = $(this).find("a").attr("lat");
                        var lon = $(this).find("a").attr("lon");
                        var _i1 = $(this).find("a").attr('i1');
                        var _t = $(this).find("a").attr("title");
                        var _tl = $(this).find("a").attr('tel');
                        var _a = $(this).find("a").attr('addr');
                        var _tag = $(this).find("a").attr('tags');
                        var _cateId = $(this).find("a").attr('cateId');
                        var _fid = $(this).find("a").attr('fid');
                        var _usernote = $(this).find("a").attr('usernote');
                        //                                                var _website = $(this).find("a").attr('website');
                        //                                                var max_ = "<a onclick='g_map.getInfoWindow().maximize(); return false;' href='javascript:void(0)' class='lnk-fn'> * 詳細內容</a> | <a href='javascript:void(0)' onclick='editmyfav(" + _id + ",\"" + _t + "\",\"" + _cateId + "\",\"" + _fid + "\" );return false' class='lnk-fn'>e 修改</a> | <a href='javascript:void(0)' onclick='delmyfav(" + _id + ",\"" + _t + "\",\"" + _cateId + "\");return false;' class='lnk-fn'>- 刪除</a>";
//                        var max_ = "<a onclick='g_map.getInfoWindow().maximize(); return false;' href='javascript:void(0)' class='lnk-fn'> * 詳細內容</a> | <a href='javascript:void(0)' onclick='delmyfav(" + _id + ",\"" + _t + "\",\"" + _cateId + "\");return false;' class='lnk-fn'>- 刪除</a>";
                        var max_ = "<a onclick='_my_maximumWin_open("+_n+"); return false;' href='javascript:void(0)' class='lnk-fn'> * 詳細內容</a> | <a href='javascript:void(0)' onclick='delmyfav(" + _id + ",\"" + _t + "\",\"" + _cateId + "\");return false;' class='lnk-fn'>- 刪除</a>";


                        var html = '';
                        html += "<table id='poi'><tr><td colspan='2' align='center' id='poi-title'>" + _t + "</td></tr><tr><td id='poi-big-td'>";
                        //html += "<div id=\"poi-show-big\"><img src=\"" + _i1 + "\" alt=\"\" id=\"poi-show-big-img\" style='height:" + p_w_b_h + "px;width:" + p_w_b_w + "' />";
                        if (_i1 == undefined) {
                            html += "<div id=\"poi-show-big\">";
                        } else {
                            html += "<div id=\"poi-show-big\"><img src=\"" + _i1 + "\" alt=\"\" id=\"poi-show-big-img\" style='height:" + p_w_b_h + "px;width:" + p_w_b_w + "px' />";
                        }

                        //                                                html += "<div style='text-align:left; margin: 10px 10px 5px 20px;'><b>分類</b>: 我的最愛";
                        //html += "<br /><b>說明</b>: " + _usernote;
                        if (_usernote != "") {
                            html += "<br /><b>說明</b>: " + _usernote;
                        }
                        html += "</div>";
                        html += "</div>";

                        html += "</td><td id='poi-desc-td'>";
                        html += "<ul class=\"list\">";
                        html += "<li class=\"article-add\">地址：" + _a + "</li>";
                        html += "<li class=\"article-tel\">電話：" + _tl + "</li>";
                        //                                                if(_website){
                        //                                                    html += "<li class=\"article-tel\"><a href=\"" + _website + "\" target=\"_blank\">官方網站</a></li>";
                        //                                                }
                        html += "</ul>";
                        html += "<a href=" + i18n.url_pnd_w + _id + "&t=" + _t + " onclick=\"dotb('下載-" + _t + "', this.href);return false\"><img src=\"" + i18n.template_i_dl + "\" alt=\"點我下載\" /></a> <br> " + max_ + "</div>";

                        html += "<br />相關標籤:<br />";

                        var tmp = (_tag) ? _tag.split(",") : [];
                        for (var t = 0; t < tmp.length && t < 3; t++) {
                            html += '<a href="javascript:void(0)" onclick=\'load_list("' + tags_url2 + encodeURIComponent(tmp[t]) + '&orderBy=point ");return false; \' class="lnk-tag" />' + tmp[t] + '</a> ';
                        }

                        html += "</td></tr>";
                        html += "</table>";

		g_map.DeleteAllShapes();

        var point = new GLatLon(lat, lon);
        var pin_list = createMarker_my(_id, point, i, html, _t, _cateId);

        g_map.AddShape(pin_list);
		g_map.SetAnimationEnabled(false);
		g_map.SetCenter(point);
		g_map.SetAnimationEnabled(true);
		pin_list.OpenInfoWin();

        my_markers.push(pin_list);
		_n = _n + 1;
/*
    _infowin.SetOptions({ enableMaximize: true});


	_infowin.AttachEvent('maximizeclick', function (pin_list, e) {
        maximumWin_open(pin_list, e, pin_list.t, pin_list.getPostMax);
    });



    _infowin.AttachEvent('restoreend', function (pin_list) {
		    _infowin.Restore();
		    g_map.ShowDashboard();
		    g_map.ShowScaleBar();
    });

    _infowin.AttachEvent('close', function (pin_list) {
//		    pin_list.CloseInfoWin();
		    g_map.ShowDashboard();
		    g_map.ShowScaleBar();

//	        g_map.PanToLatLong(new GLatLon(pin_list.Latitude, pin_list.Longitude));
    });

*/

                        $("#mypoi .content").scrollTo($(this), 1000, {
                            offset: -100
                        }, {
                            easing: 'swing'
                        });
                        return false;
                    })
                });


                $("#pagenavi a").click(function () {
                    tab1_id = 0;
                    load_list_my($(this).attr('lnk'), null, 1);
                    return false;
                })
                if (tabs_set_ == 1) {
                    if (tab1_id == undefined) {
                        showMap_my(0);
                    } else {
                        showMap_my(tab1_id);
                    }
                }
            }
            $("#myfav_type").change(function () {
                tab1_id = 0
                var message_index;
                message_index = $("#myfav_type").val();
                load_list_my(message_index, null, 1);
            });

            $('#loading-indicator').html(i18n.txt_process_done).slideUp(i18n.indicator_slide_time);

            //enhanced & 1 way
            $("#box_overlay").hide();
            if ($.browser.msie) {
                $("select").show();
            }
        },
        error: function (r, error) {

            if (error = "timeout") {
                $('#loading-indicator').html("回應逾時, 請稍候再試.").slideUp(3000);
            } else {
                $('#loading-indicator').html("程式似乎有點問題, 請稍修再試").slideUp(3000);
            }
            //enhanced & 1 way
            $("#box_overlay").hide();
            if ($.browser.msie) {
                $("select").show();
            }


        },
        //        error: function() {
        //            $('#loading-indicator').html(i18n.txt_process_done).slideUp(i18n.indicator_slide_time);
        //            alert(i18n.txt_process_error)
        //        },
        timeout: i18n.ajax_respone_time
    });

}
