
function isNotNull(param) {
    if (param === null || param === undefined) {
        return false;
    }
    if (typeof param === "string" && param == "") {
        return false;
    }
    return true;
}
function isNull(param) {
    return !isNotNull(param);
}
function set_if_empty(ele, text) {
    var id = "#" + ele.id;
    if ($(id).val() == "" || $(id).val() == null) {
        $(id).val(text);
    }
}
function run_if_empty(ele, fun) {
    var id = "#" + ele.id;
    if ($(id).val() == "" || $(id).val() == null) {
        fun();
    }
}

function empty_if(ele, text) {
    var id = "#" + ele.id;
    var val = $(id).val();
    if (val == text) {
        $(id).val("");
    }
}

function do_if_return(e, fun) {
    var keyCode = "";
    if (window.event) {
        keyCode = event.keyCode;
    } else {
        keyCode = e.which;
    }
    if (keyCode == 13) {
        fun();
    }
}
function check_navi_height() {
    var height = $('#menu-selector').height() + 50;
    var contaierHeight = $('#sub-navi-aside').parent().height(); 
    if (contaierHeight < height) {
        $('#sub-navi-aside').parent().height(height);
    }
}

function close_menu_selector() {
    $('> li > a > div', $("#menu-selector")).removeClass('expanded-icon').addClass('closed-icon');
    $('> li > ul', $("#menu-selector")).addClass('hidden');
    $('> li > ul > li > a', $("#menu-selector")).removeClass('sub-snav-link-current').addClass('sub-snav-link');
}
function open_menu_selector() {
    $('> li > a > div', $("#menu-selector")).removeClass('closed-icon').addClass('expanded-icon');
    $('> li > ul', $("#menu-selector")).removeClass('hidden').addClass('active');
    $('> li > ul > li > a', $("#menu-selector")).removeClass('sub-snav-link-current').addClass('sub-snav-link');
}
function active_menu_item(group, item) {
    open_menu_selector();
    $('#sub-navi-aside').parent().height("");
    check_navi_height();
    $('a:first', $(item)).toggleClass('sub-snav-link sub-snav-link-current');
}

function active_home_menu_item(item) {
    open_menu_selector();
    if (!$('a:first', $(item)).hasClass('home')) {
        return;
    }
    if ($('a:first', $(item)).hasClass('sub-snav-group')
            || $('a:first', $(item)).hasClass('sub-snav-group-selected')) {
        $('a:first', $(item)).toggleClass('sub-snav-group sub-snav-group-selected');
    }
}

function active_tab_item(item) {
    $(item).toggleClass('selected default');
}

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

jQuery.fn.center = function() {
    this.css("position", "absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
};
function bindWebVersion() {
    try {
        if (isNotNull(carsmart_config) && $("#web_version")) {
            $("#web_version").html(carsmart_config.web_version);
        }
    }catch(e){;};
}
function bindLoginEmail() {
    try {
        var email = carsmart_config.email;
        if (email == null || email == "null") {
            $("#loginEmail").html("您还未绑定邮箱,快去<a href='/home.jsp#config-uc-profile/config-uc-email.jsp'>绑定</a>吧");
        } else {
            $("#loginEmail").html(email);
        }
    }catch(e){;};
}
function bindUserAlias() {
    try {
        var alias = "";
        var showName = "";
        var offset = $(".user-alias").offset();
        if (carsmart_config.displayName == "null" || carsmart_config.displayName == null) {
            showName = carsmart_config.alias;
        } else {
            showName = carsmart_config.displayName;
        }
        if(window.location.href.indexOf("index.jsp")!=-1 || window.location.href.indexOf("map.jsp")!=-1 || window.location.href.indexOf("shop")!=-1 || window.location.href.indexOf("#")==-1){
                alias = "<a href='/home.jsp#space-home.jsp?customer=" + carsmart_config.user + "' title="+showName+" ><span id='shortAlias'>"
                        + substringbyte(showName,8)
                        + "...</span></a>";
                $(".user-alias").html(alias);
        }else{
                alias = "<a href='space-home.jsp?customer=" + carsmart_config.user + "' title="+showName+" asyncHtml=\"asyncHtml\"><span id='shortAlias'>"
                        + substringbyte(showName,8)
                        + "...</span></a>";
                $(".user-alias").html(alias);
        }
    }catch(e){;};
}

function getFilePath(file_obj){
    if (file_obj) {
        if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
            file_obj.select(); 
            return document.selection.createRange().text;
        }
        else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
            if (file_obj.files) {
                return file_obj.files.item(0).getAsDataURL();
            }
            return file_obj.value;
        }
        return file_obj.value;
    }
}

$(function() {

    $("#menu-selector li a").click(function(e) {
        if ($(this).hasClass('sub-snav-group') && !$(this).hasClass('home')) {
            e.preventDefault();
            $('a:first div:first', $(this.parentElement)).toggleClass('expanded-icon closed-icon');
            $('ul:first', $(this.parentElement)).toggleClass('hidden active');
            if ($('ul:first', $(this.parentElement)).hasClass('active')) {
                check_navi_height();
            }
        }
    });

    $(".small-dialog div.close").click(function(e) {
        $(this.parentElement.parentElement).hide();
    });

    $(".show_login_dialog").click(function(e) {
        showLogin();
    });

    bindWebVersion();
    bindLoginEmail();
    bindUserAlias();
});

function showMessage(message,operation) {
    $("#message").html(message);
    if(operation){
        $('#operation').html(operation);
    }
    $("#messageShow").center().show();
};
function closeMessage() {
    $("#messageShow").hide();
};
function getUserAlias(userId) {
    var alias = "";
    $.ajax({
        url : "/uc/ws/0.1/user/" + userId,
        dataType : "json",
        type : "get",
        async : false,
        cache:true,
        success : function(data) {
            if(data.displayName){
                alias = data.displayName;
            }else{
                alias = data.alias;
            }
        },
        error : function(xhr) {
            common401Handler(xhr);
        }
    });

    return alias;
};
function getUserDetail(userId,flag){
    var userData = null;
    $.ajax({
        url : "/uc/ws/0.1/user/detail/" + userId,
        dataType : "json",
        type : "get",
        async : false,
        cache:flag=="undefined"?true:flag,
        success : function(data) {
            if(data['message']){
                userDate = null;
            }else{
                userData = data;
            }
        },
        error : function(xhr) {
            common401Handler(xhr);
        }
    }); 
    return userData;
}
function getUserBasic(userId,flag) {
    var basic = null;
    $.ajax({
        url : "/uc/ws/0.1/user/" + userId,
        dataType : "json",
        type : "get",
        async : false,
        cache:flag==undefined?true:flag,
        success : function(data) {
            var gender =  data.gender;
            if (gender == "F") {
                gender = "女";
            }else if (gender == "M") {
                gender = "男";
            }else {
                gender = "未设置";
            }
            basic = {
                alias : data.alias,
                displayName : data.displayName,
                gender :gender,
                email:data.email
            };
        },
        error : function(xhr) {
            common401Handler(xhr);
        }
    });
    return basic;
};

function getUserInfo(userId,flag) {
    var userInfo = null;
    $.ajax({
        url : "/uc/ws/0.1/user/profile/" + userId,
        dataType : "json",
        type : "get",
        async : false,
        cache:flag=="undefined"?true:flag,
        success : function(data) {
            userInfo ={
                    id: data.id,
                    customerId: data.customerId,
                    birthday: data.birthday,
                    bloodType: data.bloodType,
                    nationality: data.nationality,
                    birthPlace: data.birthPlace,
                    livePlace: data.livePlace,
                    lifeStage: data.lifeStage,
                    selfDescription: data.selfDescription
                } ;
        },
        error : function(xhr) {
            common401Handler(xhr);
        }
    });
    return userInfo;
}

function getMinuteToTimes(created,showTime) {
 var date = new Date();
 var currentDate = date.getTime();
 var minutes = new String((currentDate - created) / 1000 / 60);
 var createDate = new Date(created);
 var month = createDate.getMonth()+1;
 if(month < 10){
     month = "0"+month;
 }
 var dateDay = createDate.getDate();
 if(dateDay < 10){
     dateDay = "0"+dateDay;
 }
 var hours = createDate.getHours();
 if(hours < 10){
     hours = "0"+hours;
 }
 var mins = createDate.getMinutes();
 if(mins < 10){
     mins = "0"+mins;
 }
 var dateTime = createDate.getFullYear()+"-"+month+"-"+dateDay+" "+hours+":"+mins;
    var minute = parseInt(minutes);
    if (minute < 1) {
        return  "1秒以前";
    }
    if (minute > 60) {// 大于60分钟,转换为小时
        minute = minute / 60;
        if (minute > 24) {// 转为小时判断大于24,转换为天数
            minute = minute / 24;
            if (minute > 30) {// 转为天数判断是否大于30,转为月
                minute = minute / 30;
                if (minute > 12) {
                    minute = minute / 12;
                    if(showTime){
                       return dateTime;
                    }
                    return Math.round(minute) + "年以前";
                } else {
                    if( showTime){
                      return dateTime;
                    }
                    return Math.round(minute) + "月以前";
                }
            } else {
                if(Math.round(minute) > 7 && showTime){
                    return dateTime;
                }
                return Math.round(minute) + "天以前";
            }
        } else {
            return Math.round(minute) + "小时以前";
        }
    } else {
        return Math.round(minute) + "分钟以前";
    }
}

$(document).ready(function() {
    $.ajaxSetup({
        cache : false,
        timeout:40000
    });
});
 $(document).bind("contextmenu",function(e){
 return false;
 });

// get url query arguments
function getQueryString(name) {
    var url = "";
// if($.browser.msie && $.browser.version < 8){
// url = $.cookie("urlHash");
// }else{
        url = window.location.href;
// }
    try {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = url.split("?")[1].match(reg);
        if (r != null)
            return decodeURIComponent(r[2]);
        return null;
    } catch (e) {
        return null;
    }
}

function dateFormat(date, format) {
    var o = {
        "M+" : date.getMonth() + 1, // 月
        "d+" : date.getDate(), // 日
        "h+" : date.getHours(), // 时
        "m+" : date.getMinutes(), // 分
        "s+" : date.getSeconds(), // 秒
        "q+" : Math.floor((date.getMonth() + 3) / 3), // 季
        "S" : date.getMilliseconds()
    // 毫秒
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for ( var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k])
                    .substr(("" + o[k]).length));
        }
    }
    return format;
}

function pagination(userCount, func,prev_show_always,prev_text) {
    var pageCount = 1;
    if (userCount > 10) {
        if (parseInt(userCount) % 10 != 0) {
            pageCount = Math.ceil(userCount / 10);
        } else {
            pageCount = parseInt(userCount) / 10;
        }
    }

    $("#paging_panel").pagination(pageCount, {
        num_edge_entries : 1, // 边缘页数
        num_display_entries : 4, // 主体页数
        callback : func,
        items_per_page : 1,
        prev_show_always:prev_show_always=='undefined'?true:prev_show_always,
        prev_text:prev_text
    });
}

function subStringLngLat(lnglat) {
    var point = lnglat.split(".")[1];
    if (point.length > 6) {
        return lnglat.split(".")[0] + "." + point.substring(0,7);
    } else {
        return lnglat;
    }
}

function common401Handler(xhr) {
    if (xhr.status == 401) {
        try{
            var errorMessage = eval("("+xhr.responseText+")");
            showErrorDialog('alert', errorMessage[0].message, true);
        }catch(e){
            showErrorDialog('alert','您还没有登录或者会话已过期', true);
        }
    }
}

var t = 5;
function showErrorDialog(level,text,link){
    // 显示图片
    var promptImage = '';
    if (level == 'alert') promptImage = '<div class="center"><img src="images/cs_icon_warn_20x20.png" class="center"></div>';
    else if(level == 'info')  promptImage = '<div class="center"><img src="images/cs_icon_ok.png" class="center"></div>';
    else if(level == 'error')  promptImage = '<div class="center"><img src="images/cs_icon_warn_20x20.png" class="center"></div>';

    // 是否显示链接
    var linkHTML = '';
    // 如果需要链接则显示链接
    t = 5;
    var closeAction = 'javascript:closeMessage()';
    if(link){
        setInterval("writeTime()",1000);
        setTimeout("relogin()",5000);
        closeAction = 'javascript:relogin()';
        linkHTML = '   <div class="center" id="message" onclick="javascript:relogin()">系统在<span id="promptTime">5</span>秒钟后自动调转到登录页面。</div>';
    }

    // 提示div内容
    var errorBody = '<div class="hint"> 提示<div class="close-button"><img src="./images/cs_map_pop_close_btn.png" onclick="closeMessage()"></div></div>'
                    +'<div>'
                    +'<div class="message" style="">'+promptImage+'<div class="center" id="message">'+text+'</div>'+linkHTML+'</div>'
                    +'<div class="center" style="margin-top:20px;" >'
                    +'<div class="small_button center" onclick="' + closeAction + '">关闭</div>'
                    +'</div></div>';
    var errorHtml = '<div class="small-dialog" id="messageShow">' + errorBody + '</div>';
    // 显示DIV并居中
    if ($("#messageShow").length) {
        $("#messageShow").html(errorBody);
    }
    else {
        $('body').append(errorHtml);
    }
    $("#messageShow").show();
    $("#messageShow").center();
}

function relogin(){
    $("#messageShow").hide();
    window.location.href="/login.jsp?backurl=" + encodeURIComponent(window.location.href);
}

function writeTime(){
   t--;
   $("#promptTime").html(t);
}

function closeMessage(){
  $("#messageShow").hide();
}


function successLogin(email, password) {
    $.cookie("carsmart","login");
    $("#popup-login").hide();
    $("#loginpanel").hide();
    if (isNotNull(email) && isNotNull(password) && $("#remusrname").attr("checked")){
        $.cookie("email",email,{expires:14});
        $.cookie("password",password,{expires:14});
    }
}

function gotoHome() {
    window.location.href="/";// 兼容IE6
    if ($.browser.msie) {
        window.location.reload(true);
    }
}

function logOut(){
    $.ajax({
        url : "/uc/ws/0.1/logout",
        dataType : "json",
        type : "get",
        async : false,
        success : function(data) {
          try{
              connection.sync = true;
              connection.flush();
              connection.disconnect(); 
          }catch(ex){
              $.cookie("carsmart","");
              $.cookie("email","") ;
              $.cookie("password","");
              gotoHome(); 
          }
          $.cookie("carsmart","");
          $.cookie("email","") ;
          $.cookie("password","");
          gotoHome();
        },
        error : function(xhr) {
            common401Handler(xhr);
        }
    });
}

String.prototype.toEscape = function() {

    var result =  this.replace(/</g, "&lt;").replace(/>/g,"&gt;");

    return result;
};

Date.prototype.toStandardDateString = function() {
    var d   = this.getDate();
    var day = (d < 10) ? '0' + d : d;
    var m = this.getMonth() + 1;
    var month = (m < 10) ? '0' + m : m;
    var yy = this.getYear();
    var year = (yy < 1000) ? yy + 1900 : yy;
    return (year + "-" + month + "-" + day);
};

function getImg(score) {
    var img = "";
    for ( var i = 0; i < 5; i++) {
        if (i < score) {
            img += "<img src='images/cs_icon_star_selected.gif'>";
        } else {
            img += "<img src='images/cs_icon_star_default.gif'>";
        }
    }
    return img;
}

function getScore(poiid,func) {
    var count = 0;
    var score = 0;
    var url;
    if(poiid != "null"){
        url = '/poicomment/ws/0.1/comment/summary/' + poiid + '';
    }else{
        var lnglat = $("#lnglat").val();
        var poiLon = lnglat.split(",")[0];
        var poiLat =  lnglat.split(",")[1];
        url ="/poicomment/ws/0.1/comment/summary?poiLon="+poiLon+"&poiLat="+poiLat+"&poiKeyword="+encodeURIComponent($("#poiname").html());
    }
    $.ajax({
        url : url,
        dataType : 'JSON',
        async : false,
        success : function(data) {
            if (!isNumber(data.count) || data.count == 0) {
                count = 0;
                score = 0;
            } else {
                count = data.count;
                score = data.score;
                func(score);
            }

        },
        error : function(xhr) {
            common401Handler(xhr);
        }
    });
    return {
        count : count,
        score : score
    };
}

/**
 * Dual licensed under the Apache License 2.0 and the MIT license. $Revision:
 * 740 $ $Date: 2009-12-16 17:59:25 +0100 (Wed, 16 Dec 2009) $
 */
(function($)
{
    var _defaultConfig = {
        'max-age' : 30 * 60,
        path : '/'
    };

    function _set(key, value, options)
    {
        var o = $.extend({}, _defaultConfig, options);
        if (value === null || value === undefined)
        {
            value = '';
            o['max-age'] = 0;
            o.expires = new Date(new Date().getTime() - 1000);
        }

        // Create the cookie string
        var result = key + '=' + encodeURIComponent(value);
        if (o.expires && (typeof o.expires == 'number'||  o.expires.toUTCString))
        {
            var date ;
            if(typeof o.expires == 'number'){
                date = new Date();
                date.setTime(date.getTime()+(o.expires*24*60*60*1000));
            }else{
                date = o.expires;
            }
            result += '; expires=' + date.toUTCString();
        }
        if (o['max-age'] && typeof o['max-age'] === 'number')
        {
            result += '; max-age=' + o['max-age'];
        }
        if (o.path)
        {
            result += '; path=' + (o.path);
        }
        if (o.domain)
        {
            result += '; domain=' + (o.domain);
        }
        if (o.secure)
        {
            result +='; secure';
        }

        document.cookie = result;
    }

    function _get(key)
    {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; ++i)
        {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, key.length + 1) == (key + '='))
            {
                return decodeURIComponent(cookie.substring(key.length + 1));
            }
        }
        return null;
    }

    $.cookie = function(key, value, options)
    {
        if (arguments.length > 1)
        {
            _set(key, value, options);
            return undefined;
        }
        else
        {
            return _get(key);
        }
    };

})(jQuery);
function poiCommnet(poiid, lnglat,poiKeyword,flag) {
    if(poiid != "null" ){
        $.ajax({
            url : '/poisearch/ws/0.1/search-with-id/?poi_id=' + poiid,
            dataType : 'JSON',
            type : 'POST',
            success : function(data) {
                if (data.poilist.length > 0) {
                    for (var i = 0; i < data.poilist.length; i++) {
                        if (data.poilist[i].pguid == poiid) {
                            var url = "home.jsp#way-poi-comment.jsp?poiid=" + data.poilist[i].pguid
                            + "&lnglat=" + lnglat + "&address=" + data.poilist[i].address + "&type="
                            + data.poilist[i].type + "&tel=" + data.poilist[i].tel + "&name="
                            + data.poilist[i].name;
                            if(flag){
                                $.cookie("urlHash",url.split("#")[1]);
                                window.location.hash =url.split("#")[1];
                                loadPanel();
                            }else{
                                $.cookie("urlHash",url.split("#")[1]);
                                 window.location.href = url;
                            }
                           
                        }
                    }
                }else{
                    var url = "home.jsp#way-poi-comment.jsp?poiid=null&lnglat=" + lnglat + "&address=null&type=null&tel=null&name="
                    +poiKeyword;
                    if(flag){   
                    $("#urlHash").val(url.split("#")[1]);
                    window.location.hash =url.split("#")[1];
                    $.cookie("urlHash",url.split("#")[1]);
                    loadPanel();
                    }else{
                        $.cookie("urlHash",url.split("#")[1]);
                        window.location.href = url;
                    } 
                }
            },
            error : function(xhr) {
                common401Handler(xhr);
            }
        });  
    }else{
        var url = "home.jsp#way-poi-comment.jsp?poiid=null&lnglat=" + lnglat + "&address=null&type=null&tel=null&name="+poiKeyword;
        if(flag){   
        $("#urlHash").val(url.split("#")[1]);
        window.location.hash =url.split("#")[1];
        $.cookie("urlHash",url.split("#")[1]);
        loadPanel();
        }else{
            $.cookie("urlHash",url.split("#")[1]);
            window.location.href = url;
            
        } 
    }

}

function sortJsonData(jsonArray,jsonField,type){
    SortFun.field = jsonField;
    jsonArray.sort(SortFun);
    if(type == "down"){
        jsonArray.reverse();
    }
}

function SortFun(data1, data2) {
    if (data1[SortFun.field] > data2[SortFun.field]) {
        return 1;
    }
    else if (data1[SortFun.field] < data2[SortFun.field]) {
        return -1;
    }
    return 0;
}
function Favorite(poiid, lnglat, address, type, tel, name, $this) {
    var url = window.location.href;
    var flag = true;
    if (isNull(carsmart_config) || isNull(carsmart_config.user)) {
        if(confirm("您还未登录,是否登录 ")){
             window.location = "login.jsp?backurl="+encodeURIComponent(url);
        }else{
            return false;
        }
    }
     var lnglatArray = lnglat.split(",");
     var telArray = null;
     if(tel){
         telArray = tel.split(";")[0];
     }
     var json = {
         "name" : name,
         "location" : {
             "address" : address,
             "source" : "GPS",
             "description" : "",
             "longitude" : lnglatArray[0],
             "latitude" : lnglatArray[1]
         },
         "ownerCustomerId" : carsmart_config.user,
         "category" : type,
         "telephone" :  telArray,
         "guid":poiid
     };
    $.ajax({
        url : '/poi/ws/0.1/favorpoi',
        type : 'POST',
        data : $.toJSON(json),
        contentType : 'application/json;charset=utf-8',
        datatype : 'JSON',
        async:false,
        success : function(data) {
            $(this).removeAttr("onclick");
            showMessage("收藏成功");
           
        },
        error : function(xhr) {
            common401Handler(xhr);
            var message = xhr.status;
            if(message == "400"){
                showMessage("POI已经收藏过");
            }
            flag =  false;
            return flag;
        }
    });
    return flag;
}

function share(address, lnglat, name, type, _this,poiid) {
    if (isNull(carsmart_config) || isNull(carsmart_config.user)) {
        if(confirm("您还未登录,是否登录 ")){
            var url = window.location.href;
            window.location = "login.jsp?backurl="+encodeURIComponent(url);
        }
        return false;
    }
    if (address == "" || address == "暂无" || address.indexOf("暂无") != -1 || address == "null") {
        $("#poiaddress").html(name);
    } else {
        $("#poiaddress").html(address);
    }
    $("#poiname").html(name);
    $("#lnglat").val(lnglat);
    $("#type").val(type);
    $("#sharePguid").val(poiid);
// var parent = $(".poi_main_list").offset();
// var left = _this.offsetLeft + parent.left;
// var top = _this.offsetTop + parent.top;
//
// if (top > 950) {
// top = top - $("#sharepoiWrap").height() - _this.offsetHeight;
// }
// $("#sharepoiWrap").animate({
// left : left,
// top : top
// });
    var html = bulidFriendPicker();
    $("#friend-picker").html(html);
    $("#sharepoiWrap").show().center();
}

function closeShare() {
    $("#sharepoiWrap").hide();
    $("#poiname").html("");
    $("#poiaddress").html("");
    $("#lnglat").val("");
}
var sharePoi = true;
function SharePoi(id) {
    if(!sharePoi){
        return false;
    }
    sharePoi = false;
    var ends = $("#lnglat").val().split(",");
    var poiid = $("#sharePguid").val();
    var source = "webgis";
    if(poiid){
        source = source +"+"+poiid;
    }
    var datajson = {
        from : "",
        to : "" + id + "",
        loc_dest : {
            address : "" + encodeURIComponent($("#poiaddress").html()) + "",
            longitude : "" + subStringLngLat(ends[0]) + "",
            source : source,
            latitude : "" + subStringLngLat(ends[1]) + "",
            description : "" + encodeURIComponent($("#type").val()) + ""
        },
        loc_start : {},
        option : {
            routingPosition : "local",
            routingMethod : "time_pri"
        }
    };
    var data = $.toJSON(datajson);
    $.ajax({
        url : '/naviassist/ws/0.1/naviassist/wzgx',
        type : 'POST',
        datatype : 'JSON',
        contentType : 'application/json',
        data : data,
        async:false,
        success : function(data) {
            sharePoi = true;
            showErrorDialog('info', "POI分享成功");
        },
        error : function(xhr) {
            common401Handler(xhr);
        }
    });
}
/*******************************************************************************
 * 创建好友选择弹出框
 * 
 * @returns {String}
 */
function bulidFriendPicker(){
    var entries = getRosterManager().getEntries();
    var userInfo = "";
    $.each(entries, function(index, element) {
        var id = entries[index].jid.substring(0, entries[index].jid.indexOf("@"));
        var imgurl = "/uc/ws/0.1/user/image/small/" + id;
        var subscription = entries[index].type;
        var alias = getUserAlias(id);
        if (subscription == "both") {
            userInfo += "<li class='checkboxes'><label><input type='checkbox' name='checkbox' userId=" + id
            + "><img src=" + imgurl + " width='25px' height='25px' style='margin:0 5px;'><span>"
            + alias + "</span></label></li>";
        }
    });
    return userInfo;
}
// 添加好友
function addFriend(id){
    var objRosterManager = getRosterManager();
    if (objRosterManager == null){
        showErrorDialog('alert', "添加好友失败", false);
        return;
    }
    if(objRosterManager.existEntry(id+'@'+carsmart_config.xmppserver)){
        if(objRosterManager.getEntry(id+'@'+carsmart_config.xmppserver).type == "both"){
            showErrorDialog('alert', "已是您的好友", false);
            return;
        }
       
    }
    connection.send($pres({
        to :id+'@'+carsmart_config.xmppserver,
        type : 'subscribe'
    }).tree());
    connection.send($pres({
        to :id+'@'+carsmart_config.xmppserver,
        type : 'subscribed'
    }).tree());
    showErrorDialog('info', "已发送添加好友请求", false);
}

// 显示新通知数目
function showNoticeCount(){
    showMsgCount("/msgcenter/ws/0.1/system/newsinfo/count", "notice-count");
}
// 显示未读好友验证信息数目
function showNewFriendRequestCount(){
    showMsgCount("/msgcenter/ws/0.1/system/friendauth/count", "friend-request-count");
}
// 显示未读空间留言数目
function showNewMsgNoteCount(){
    showMsgCount("/msgcenter/ws/0.1/sns/space/count", "msg-note-count");
}

function showMsgCount(url, showMsg_id){
    $.ajax({
        url : url,
        dataType : "JSON",
        aysnc : true,
        success : function(data) {
            var showObj = $("#" + showMsg_id);
            if (showObj.length > 0) {
                var count = data.count;
                if (count > 0) {
                    showObj.html("(" + count + ")");
                } else {
                    showObj.html("");
                }
            }
        },
        error : function(xhr) {
            common401Handler(xhr);
        }
    });
}

function ensureLogin() {
    if (carsmart_config !== undefined && carsmart_config.user == '') {
        if ($.cookie("email") && $.cookie("password")) {
            $.ajax({
                url : '/uc/ws/0.1/login',
                dataType : 'JSON',
                type : 'POST',
                data : {
                    username : $.cookie("email"),
                    password : $.cookie("password"),
                    provider : 'CARSMART'
                },
                success : function(data) {
                    successLogin();
                    window.location.reload();
                },
                error : function(xhr) {
                    window.location.href = "login.jsp?backurl=" + encodeURIComponent(window.location.href);
                }
            });
        } else {
            window.location.href = "login.jsp?backurl=" + encodeURIComponent(window.location.href);
        }
    }
}
function getCityByIp(ip,call_back){
    var cityInfo = {};
    var position = null;
    $.ajax({
        url : '/loc/ws/0.1/loc/ip?ip='+ip,
        type : 'GET',
        datatype : 'JSON',
        success : function(data) {
            var dataInfo = decodeURIComponent(data);
            var dataJson = eval("("+dataInfo+")");
            if(dataJson.message == "ok"){
                if(dataJson.SpatialBean.City){
                    var city = dataJson.SpatialBean.City.name;
                    if(city.length >=3){
                        var index = city.indexOf("市");
                        city = city.substring(0,index);
                    }
                    var telnum = dataJson.SpatialBean.City.telnum;
                    var code = dataJson.SpatialBean.City.code;
                    if(!city){
                        city = dataJson.SpatialBean.Province.name;
                        if(city.length >=3){
                            var index = city.indexOf("市");
                            city = city.substring(0,index);
                        }
                    }
                    if(!code){
                        code = dataJson.SpatialBean.District.code;
                    }
                    cityInfo.city = city;
                    cityInfo.telnum = telnum;  
                    cityInfo.code = code; 
                }else{
                    cityInfo.city = "北京";
                    cityInfo.telnum = "010";  
                    cityInfo.code = "1101"; 
                }
                call_back(cityInfo);
            }
        },
        error : function(xhtr) {
            call_back(cityInfo);
        }
    });
    return cityInfo;
}
function haveArray(element , array){
    for ( var i = 0, length = array.length; i < length; i++ ) {
        if ( element.indexOf(array[ i ]) !=-1 ) {
            return i;
        }
    }
    return -1;
};
function getCityByIpLocal(ip,call_back){
    var cityInfo = {};
    $.ajax({
        url : '/tdu/ws/0.1/tdu/ip?ip='+ip,
        type : 'GET',
        datatype : 'JSON',
        success : function(data) {
                   var city = data.city;
                   if(city.indexOf("省")!=-1){// 包含省字段
                       var citySplit = city.split("省");
                       if(citySplit[1] == ""){// 不包含市或区字段
                           cityInfo.city = proviceCity.getCityByProvice(citySplit[0]);
                           call_back( cityInfo);
                           return null;
                       }else{// 包含市或区字段
                           var cityinfo = citySplit[1];
                           if(cityinfo.indexOf("市")!=-1){// 判断是否为市
                               cityInfo.city = cityinfo.split("市")[0];
                               call_back(cityInfo);
                               return null;
                           }else{
                               
                           }
                           return 
                       }
                   }else{
                       var cityReg = new Array('新疆', '西藏', '广西','宁夏','内蒙古');
                       var index ;
                       if((index = haveArray(city,cityReg))!=-1){// 包含新疆西藏广西
                           if(index == 4 ){
                               if( city.substring(3).split("市")[0].indexOf("盟")!=-1){
                                   var cityName = city.substring(3).split("市")[0];
                                   cityInfo.city = cityName.substring(cityName.indexOf("盟")+1);
                               }else{
                                   cityInfo.city = city.substring(3).split("市")[0]
                               }
                           }else{
                               if( city.substring(2).split("市")[0].indexOf("州")!=-1){
                                   var cityName = city.substring(2).split("市")[0];
                                   cityInfo.city = cityName.substring(cityName.indexOf("州")+1);
                               }else{
                                   cityInfo.city = city.substring(2).split("市")[0];
                               }
                           }
                           
                           call_back(cityInfo);
                       }else{
                           if(city.indexOf("局域网")!=-1){
                               cityInfo.city = "北京"
                               call_back(cityInfo);
                           }else{
                               cityInfo.city = city.split("市")[0];
                               
                               call_back(cityInfo);
                           }
                           
                           return null;
                       }
                       
                   }
                   
        },
        error : function(xhtr) {
        }
    });
}

function getCityByMobileLocal(mobile,call_back){
    $.ajax({
        url : '/tdu/ws/0.1/tdu/mobile?mobile='+mobile,
        type : 'GET',
        datatype : 'JSON',
        success : function(data) {
                   var city = data.city;
                   call_back(city);
        },
        error : function(xhtr) {
        }
    });
}

/*
 * 字数监控 showCountId 字数显示组件Id maxNumber 最长输入长度
 */
$.fn.artTxtCount = function(showCountId, maxNumber){
    var oldChar;
    var count = function(){
        // val = $(this).val().length;
        var bytelen = $(this).val().replace(/[^\x00-\xff]/g, "xx").length;
        if($(this).val().indexOf("：")!=-1){
            bytelen = $(this).val().split("：")[1].replace(/[^\x00-\xff]/g, "xx").length;
        }
        var val=Math.round(bytelen/2);
        if(val <= maxNumber){
            oldChar = $(this).val();
            $("#" + showCountId).html('您还能输入<font class="input_count">' +  (maxNumber - val) + '</font>个字');
        }else{
            // $("#" + showCountId).html('您的输入已超<font class="over_input_count">'
            // + (val - maxNumber) + '</font>个字');
            $(this).val(oldChar);
        };
    };
    $(this).bind('propertychange', count);
    $(this).bind('input', count);
    return this;
};
/*
 * 按字节截取字符串(英文一个字节,中文两个字节)
 */
 function substringbyte(source, len){
    var result = "",
        _len = 0;
    var bytelen = source.replace(/[^\x00-\xff]/g, 'xx').length;
    if (bytelen <= len){
        return source;
    }
    for (var i = 0; i < source.length; i++){
        if(source.charAt(i).match(/^[\u4e00-\u9fa5]$/)){// 匹配中文
            _len += 2;
        } else {
            _len++;
        }
        if (_len <= (len - 2)){
            result += source.charAt(i);
        } else{
            break;
        }
    }
    return result + "...";
}
 function setCurrentCity(n, flag, func) {
     if (func) {
         var cookieCityCode = AD_CODE.getCodeByCity(n);
         getReport(cookieCityCode, true,0);
     }
     if (flag) {
         $.cookie("cookiCityName", n);
         var maptools = new MMapTools(mapObj);
         maptools.setCenterByCity(n);
     }
     $("#cityshow").html(n);
     $("#cityName").val(n);// 关键字提示用

 }
 var currentHash = "";
 function onHashChange(state){
     var url = window.location.href.split("#")[1];
     if(currentHash.indexOf("#")!=-1){
         currentHash = currentHash.split("#")[1];
     } 
     if(url == state && url == currentHash){
         return false;
     }
     currentHash =state;
     loadPanel(state);
 }
 function loadPanel(state){
     var hash =window.location.href.split("#")[1];
     if(state){
         hash = state;
     }
     currentHash = hash;
     if(hash && hash != "#"){
         if(hash.indexOf("#")!=-1){
             hash = hash.split("#")[1];
         }
         try{
             HistoryManager.add(hash,hash.split(".")[0]+"");
         }catch(e){
             
         }
         if(hash.indexOf("/shop/user.php")!=-1){
             if(hash.indexOf("favor")!=-1){
                 $("#mainContent").load("favor-poi.jsp",function(){
                     $("#sub-navi-aside").load("favor-left.jsp");
                     $("#operations").load("/shop/user.php");  
                 });
             }else{
                 $("#sub-navi-aside").load("favor-left.jsp");
                 $("#operations").load("/shop/user.php");  
             }
                        
         }else{
             if(hash.split("?")[0].indexOf("/")!=-1){
                 var main = hash.split("/")[0]+"-left.jsp";
                 var content = hash.split("/")[1];
                 if($("#sub-navi-aside").length > 0){
                     $("#sub-navi-aside").load(main,function(){
                         $("#operations").load(content,function(){
                             $("#operations").show();
                         });
                     });
                 }else{
                     $("#mainContent").load("home-frame.jsp",function(){
                         $("#sub-navi-aside").load(main,function(){
                             $("#operations").load(content,function(){
                                 $("#operations").show();
                             });
                         });
                     });
                 }
                
             }else{
                 $("#mainContent").load(hash,function(){
                 });
                 
             }  
         }
         
     }else{
         currentHash = "way-content.jsp";
         window.location.hash = currentHash;
         HistoryManager.add("way-content.jsp","way-content.jsp".split(".")[0]);
         $("#mainContent").load("way-content.jsp");
         $.cookie("urlHash","way-content.jsp");
         
     }
 }
$(document).delegate("a","click",function(event){
    var async = $(this).attr("asyncHtml");
    var isNavi = $(this).attr("isNavi");
    if(async != undefined){
        event.preventDefault(); 
        if(isNavi=="isNavi"){
            $(".selected").removeClass("selected").addClass("default");
            $(this).parent().removeClass("default").addClass("selected");
        }
        var show = $(this).attr("show");
        var url = $(this).attr("href");
            $("#myHome").text("我的空间");
            $("#myHome").parent().attr("href", "space-home.jsp");
        if(show){
                 var _href = $(this).attr("href").split("\/");
                _href = _href[_href.length-1];
                var hash =  window.location.hash;
                if(hash.indexOf("/")!=-1){
                    hash = hash.split("/")[0].split(".")[0];
                }
              
                currentHash = hash.split(".")[0] + "/"+_href;
                $("#urlHash").val(currentHash);
                $.cookie("urlHash",currentHash);
                window.location.hash = hash.split(".")[0] + "/"+_href;
                loadPanel();
        }else{
            var _href =url;
            
            if($(this).attr("href").indexOf("http://")!=-1){
                var index = $(this).attr("href").split("//")[1];
                _href= index.substring(_href.indexOf("/")+1);
                if(_href.indexOf("/shop/user.php")!=-1){
                    _href = _href.substring(_href.indexOf("/"));
                }else{
                    _href = _href.substring(_href.indexOf("/")+1);
                }
               
              
            }
            
          window.location.hash = _href;
          currentHash = url;
          loadPanel();
          $("#urlHash").val(_href);
          $.cookie("urlHash",_href);
        }
       
    }
   
});

function getGroupDetail(url) {
    $("#urlHash").val(url);
    $.cookie("urlHash",url);
    window.location.hash = url;
    loadPanel();
    $(document).scrollTop(0);
    
}
function loadContent(){
    $("#mainContent").load("way-content.jsp",function(){
        $("#operations").show();
    });
}
function __flash__addCallback(instance, name) {
 try{
     instance[name] = function () {
         return eval(instance.CallFunction("" + __flash__argumentsToXML(arguments,0) + ""));
         };  
 }catch(e){
 }

 }

function __flash__removeCallback(){
    return function(instance, name) { 
        if (instance) instance[name] = null; 
     };
} 

function addJSEventListener(){
    try{
        
    }catch(e){
        
    }
}
function inputCountLimit(textId, countId,maxCount) {
    var world = $("#" + textId).val().length;
    var insertCount = $("#"+countId).text();
    var maxCount = $("#"+maxCount).text();
    if (parseInt(insertCount) == 0) {
        $("#" + textId).val($("#" + textId).val().substring(0, parseInt(maxCount)));
    } else {
        $("#" + countId).text(parseInt(insertCount) - 1);
    }
}

