(function(){

/* Copyright (c) 2010 Baidu */
var baidu=baidu||{version:"1-3-1"};baidu.guid="$BAIDU$";window[baidu.guid]=window[baidu.guid]||{};baidu.json=baidu.json||{};
baidu.json.stringify=(function(){var b={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(g){if(/["\\\x00-\x1f]/.test(g)){g=g.replace(/["\\\x00-\x1f]/g,function(h){var j=b[h];
if(j){return j}j=h.charCodeAt();return"\\u00"+Math.floor(j/16).toString(16)+(j%16).toString(16)})}return'"'+g+'"'}function d(n){var h=["["],j=n.length,g,k,m;
for(k=0;k<j;k++){m=n[k];switch(typeof m){case"undefined":case"function":case"unknown":break;default:if(g){h.push(",")}h.push(baidu.json.stringify(m));
g=1}}h.push("]");return h.join("")}function c(g){return g<10?"0"+g:g}function f(g){return'"'+g.getFullYear()+"-"+c(g.getMonth()+1)+"-"+c(g.getDate())+"T"+c(g.getHours())+":"+c(g.getMinutes())+":"+c(g.getSeconds())+'"'
}return function(l){switch(typeof l){case"undefined":return"undefined";case"number":return isFinite(l)?String(l):"null";case"string":return a(l);
case"boolean":return String(l);default:if(l===null){return"null"}else{if(l instanceof Array){return d(l)}else{if(l instanceof Date){return f(l)
}else{var h=["{"],k=baidu.json.stringify,g,j;for(key in l){if(l.hasOwnProperty(key)){j=l[key];switch(typeof j){case"undefined":case"unknown":case"function":break;
default:if(g){h.push(",")}g=1;h.push(k(key)+":"+k(j))}}}h.push("}");return h.join("")}}}}}})();baidu.sio=baidu.sio||{};baidu.sio._removeScriptTag=function(b){if(b.clearAttributes){b.clearAttributes()
}else{for(var a in b){if(b.hasOwnProperty(a)){delete b[a]}}}if(b&&b.parentNode){b.parentNode.removeChild(b)}b=null};baidu.json.parse=function(a){if(!/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){return null
}return window.JSON&&window.JSON.parse?window.JSON.parse(a):(new Function("return "+a))()};baidu.json.decode=function(a){return baidu.json.parse(a)
};baidu.cookie=baidu.cookie||{};baidu.cookie._isValidKey=function(a){return(new RegExp('^[^\\x00-\\x20\\x7f\\(\\)<>@,;:\\\\\\"\\[\\]\\?=\\{\\}\\/\\u0080-\\uffff]+\x24')).test(a)
};baidu.cookie.getRaw=function(b){if(baidu.cookie._isValidKey(b)){var c=new RegExp("(^| )"+b+"=([^;]*)(;|\x24)"),a=c.exec(document.cookie);
if(a){return a[2]||null}}return null};baidu.cookie.get=function(a){var b=baidu.cookie.getRaw(a);if("string"==typeof b){b=decodeURIComponent(b);
return b}return null};baidu.browser=baidu.browser||{};if((/(\d+\.\d)(\.\d)?\s+safari/i.test(navigator.userAgent)&&!/chrome/i.test(navigator.userAgent))){baidu.browser.safari=parseFloat(RegExp["\x241"])
}baidu.url=baidu.url||{};baidu.url.queryToJson=function(a){var f=a.substr(a.indexOf("?")+1),c=f.split("&"),d=c.length,k={},h,g,j,b;
for(i=0;i<d;i++){b=c[i].split("=");h=b[0];g=b[1];j=k[h];if("undefined"==typeof j){k[h]=g}else{if(Object.prototype.toString.call(j)=="[object Array]"){j.push(g)
}else{k[h]=[j,g]}}}return k};baidu.cookie.setRaw=function(c,d,b){if(!baidu.cookie._isValidKey(c)){return}b=b||{};var a=b.expires;
if("number"==typeof b.expires){a=new Date();a.setTime(a.getTime()+b.expires)}document.cookie=c+"="+d+(b.path?"; path="+b.path:"")+(a?"; expires="+a.toGMTString():"")+(b.domain?"; domain="+b.domain:"")+(b.secure?"; secure":"")
};baidu.browser.isGecko=/gecko/i.test(navigator.userAgent)&&!/like gecko/i.test(navigator.userAgent);baidu.url.escapeSymbol=function(a){return String(a).replace(/\%/g,"%25").replace(/&/g,"%26").replace(/\+/g,"%2B").replace(/\ /g,"%20").replace(/\//g,"%2F").replace(/\#/g,"%23").replace(/\=/g,"%3D")
};baidu.json.encode=function(a){return baidu.json.stringify(a)};if(/firefox\/(\d+\.\d)/i.test(navigator.userAgent)){baidu.browser.firefox=parseFloat(RegExp["\x241"])
}baidu.url.jsonToQuery=function(f,d){var b=[],a=0,c,h,g;d=d||function(j){return baidu.url.escapeSymbol(j)};for(c in f){if(f.hasOwnProperty(c)){h=f[c];
if(Object.prototype.toString.call(h)=="[object Array]"){g=h.length;while(g--){b[a++]=c+"="+d(h[g],c)}}else{b[a++]=c+"="+d(h,c)
}}}return b.join("&")};baidu.sio.callByServer=function(a,j,k){k=k||{};var f=document.createElement("SCRIPT"),d="bd__cbs__",c=typeof j,h,g,b=k.charset;
if("string"==c){h=j}else{if("function"==c){while(1){h=d+Math.floor(Math.random()*2147483648).toString(36);if(!window[h]){window[h]=function(){try{j.apply(window,arguments)
}finally{baidu.sio._removeScriptTag(f);window[h]=null}};break}}}}if("string"==typeof h){a=a.replace(/(\?|&)callback=[^&]*/,"\x241callback="+h);
if(a.search(/(\?|&)callback=/)<0){a+=(a.indexOf("?")<0?"?":"&");a+="callback="+h}}f.setAttribute("type","text/javascript");
b&&f.setAttribute("charset",b);f.setAttribute("src",a);document.getElementsByTagName("head")[0].appendChild(f)};if(/chrome\/(\d+\.\d)/i.test(navigator.userAgent)){baidu.browser.chrome=parseFloat(RegExp["\x241"])
}baidu.browser.isWebkit=/webkit/i.test(navigator.userAgent);try{if(/(\d+\.\d)/.test(external.max_version)){baidu.browser.maxthon=parseFloat(RegExp["\x241"])
}}catch(e){}if(/msie (\d+\.\d)/i.test(navigator.userAgent)){baidu.ie=baidu.browser.ie=document.documentMode||parseFloat(RegExp["\x241"])
}baidu.cookie.set=function(b,c,a){baidu.cookie.setRaw(b,encodeURIComponent(c),a)};baidu.string=baidu.string||{};baidu.string.escapeReg=function(a){return String(a).replace(new RegExp("([.*+?^=!:\x24{}()|[\\]/\\\\])","g"),"\\\x241")
};baidu.url.getQueryValue=function(b,c){var d=new RegExp("(^|&|\\?|#)"+baidu.string.escapeReg(c)+"=([^&]*)(&|\x24)","");var a=b.match(d);
if(a){return a[2]}return null};baidu.cookie.remove=function(b,a){a=a||{};a.expires=new Date(0);baidu.cookie.setRaw(b,"",a)
};baidu.dom=baidu.dom||{};(function(){var a=new RegExp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)","g");baidu.string.trim=function(b){return String(b).replace(a,"")
}})();baidu.trim=baidu.string.trim;baidu.array=baidu.array||{};baidu.array.each=function(g,d){var c,f,b,a=g.length;if("function"==typeof d){for(b=0;
b<a;b++){f=g[b];c=d.call(g,f,b);if(c===false){break}}}return g};baidu.each=baidu.array.each;baidu.lang=baidu.lang||{};baidu.lang.isArray=function(a){return"[object Array]"==Object.prototype.toString.call(a)
};baidu.lang.isElement=function(a){return !!(a&&a.nodeName&&a.nodeType==1)};baidu.lang.isFunction=function(a){return"[object Function]"==Object.prototype.toString.call(a)
};baidu.object=baidu.object||{};baidu.object.each=function(f,c){var b,a,d;if("function"==typeof c){for(a in f){if(f.hasOwnProperty(a)){d=f[a];
b=c.call(f,d,a);if(b===false){break}}}}return f};baidu.lang.isNumber=function(a){return"[object Number]"==Object.prototype.toString.call(a)
};(function(){var g={},b=baidu.lang.isArray,f=baidu.lang.isElement,c=function(j){var h=this;if(b(j)){baidu.each(j,function(l,k){h[k]=l
})}else{h[0]=j}};g.each=function(h){baidu.object.each(this,function(j){h.call(this,(new c(j)))})};baidu.each(("addClass draggable empty hide show insertAfter insertBefore insertHTML removeClass setAttr setAttrs setStyle setStyles show toggleClass toggle children next first getAncestorByClass getAncestorBy getAncestorByTag getDocument getParent getWindow last next prev contains getAttr getPosition getStyle g q query hasClass intersect remove").split(" "),function(h){g[h]=g[h.replace(/^get[A-Z]/g,d)]=a(h,"dom")
});baidu.each(("on un").split(" "),function(h){g[h]=a(h,"event")});baidu.each(("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error").split(" "),function(h){g[h]=function(j){return this.on(h,j)
}});c.prototype=g;function a(j,h){return function(){var l=[],k=arguments;baidu.object.each(this,function(n,m){Array.prototype.unshift.call(k,n);
if(!baidu.lang.isFunction(h)){h=baidu[h][j]}l.push(h.apply(this,k));Array.prototype.shift.call(k,n)});return(f(l)||(b(l)&&f(l[0])))?new c(l):l
}}function d(h){return h.charAt(3).toLowerCase()}baidu.e=baidu.element=function(h){return new c(baidu.g(h))};baidu.element.extend=function(h){baidu.object.each(h,function(k,j){c.prototype[j]=a(j,k)
})}})();if(/opera\/(\d+\.\d)/i.test(navigator.userAgent)){baidu.browser.opera=parseFloat(RegExp["\x241"])}baidu.browser.isStrict=document.compatMode=="CSS1Compat";

/**
 * @author lixuejian
 */
(function(){
  window.im = window.im || {};
window.im.vendor = window.im.vendor || {};
window.im.vendor.common = window.im.vendor.common || {};

  /**
 * @author lixuejian
 */
window.im.vendor.common.Service = (function(){

    //==========\u5e38\u91cf ==============//

    var WEBIM_STANDARD = "webimStandard", WEBIM_MULAN = "webimMulan", HI = "hi";
    var BAIDU_DOMAIN = "baidu.com";

    //***************************//


    var backends = {};


    //==========\u914d\u7f6e===============//

    backendsOrder = ["hi", "webimstandard", "webimstandard-crossdomain"];

    //****************************//

    var sandbox = {
        lib: baidu,
        report: _report
    }

    function _report(){

    }

    function _testBackend(username){
        var backend = null;
        for (var i = 0, l = backendsOrder.length; i < l; i++) {
            var id = backendsOrder[i];
            if (backends[id] && backends[id].test(username)) {
                backend = backends[id];
                break;
            }
        }
        return backend;
    }

    function getBackend(id){
        return backends[id];
    }

    function addBackend(id, module){
        backends[id] = module(sandbox);
        backends[id].init();
    }

    function startBaiduHi(method, self, to, params){
        var backend = _testBackend(self);
        if (backend) {
            backend.open(method, self, to, params);
        }
        else {
            alert("Can not find backend");
        }
    }

    var pubs = {
        startBaiduHi: startBaiduHi,
        addBackend: addBackend,
        getBackend: getBackend
    }

    return pubs;

})();

  /**
 * @author lixuejian
 */
window.im.vendor.common.Service.addBackend("hi", function(sandbox){

    var _lib = sandbox.lib;
    var __IM_REDIRECT_IFRAME_ID = "__IM_IFRAME_REDIRECT";

    function _getClientInfo(){

        var result = {
            version: null,
            detect: null
        }
        if (_lib.browser.ie) {

            try {
                result.detect = new ActiveXObject("WebDetect.Detect");
                result.version = result.detect.GetVersion();
            }
            catch (ex) {
            }
        }
        else if (_lib.browser.firefox) {
            try {
                if (typeof(navigator.mimeTypes['application/x-baiduhi']) == 'object') {
                    result.version = '.*';
                }
            }
            catch (ex) {
            }
        }

        return result;

    }

    function _isClientExists(){
        var object = _getClientInfo();
        if (object.version) { return true; }
        return false;
    }

    function _isClientLogin(username){

        var object = _getClientInfo(), detect = object.detect;

        if (detect) {

            var version = null, isClientOnline = false;

            try {
                version = detect.GetWebDetectVersion();
                isClientOnline = detect.IsClientOnline(username);
            }
            catch (ex) {
            }

            return isClientOnline;

        }
        else { return false; }

    }

    function init(){
    }

    function test(self){
        if (self) {
            if (_lib.browser.ie) { return _isClientLogin(self); }
            return _isClientExists();
        }
        else { return _isClientExists(); }

    }

    function open(method, self, to, params){

        self = self || "";
        to = to || "";
        var iframe, href = "baidu://" + method + "/?sid=" + self;

        if (to.indexOf(":") > -1) {
            href += "&id=" + to.split(":")[0] + "&subid=" + to.split(":")[1];
        }
        else {
            href += "&id=" + to;
        }

        href += "&" + _lib.url.jsonToQuery(params);

        if (_lib.browser.ie) {
            href += '&browser=IE';
        }
        else if (_lib.browser.firefox) {
            href += '&browser=FF&promo=c2cmsg|message|addgroup|creategroup|addcontact';
        }
        else {
            alert("Unknown Browser");
            return false;
        }

        iframe = document.getElementById(__IM_REDIRECT_IFRAME_ID);
        if (!iframe) {
            iframe = document.createElement("iframe");
            iframe.id = __IM_REDIRECT_IFRAME_ID;
            iframe.style.display = "none";
            document.body.insertBefore(iframe, document.body.firstChild);
        }
        iframe.src = href;

        sandbox.report(method, self, to, params, "client");

        if (params && params.onim) params.onim();
    }

    return {
        init: init,
        test: test,
        open: open
    }

});

  /**
 * @author lixuejian
 */
window.im.vendor.common.Service.addBackend("webimstandard-crossdomain", function(sandbox){

    //========\u914d\u7f6e===========

    var URL_CONN = window.location.protocol + "//" + window.location.hostname + "/__hi_callback/im_conn/";
    var URL_BASE = "http://web.im.baidu.com";
    var URL_OBSERVER = URL_BASE + "/observer.html";
    var URL_COMMAND = URL_BASE + "/command.html";

    //***********************

    var _lib = sandbox.lib;
    var _isWebimOpen = -1;

    function _createIframe(url, data, holder){
        var iframe = document.createElement("iframe");
        iframe.style.display = "none";
        iframe.src = url + (url.indexOf("?") > -1 ? "&" : "?") + (data ? "#data=" + data : "");
        holder.appendChild(iframe);
        return iframe;
    }

    function _getHolder(){
        var div = document.getElementById("__IM_HOLDER");
        if (!div) {
            div = document.createElement("div");
            div.style.display = "none";
            div.id = "__IM_HOLDER";
            document.body.insertBefore(div, document.body.firstChild);
        }
        return div;
    }

    function _openWebim(iframeHolder){

        if (_openWebim.form && _openWebim.form.tagName == "FORM") {
            _openWebim.form.submit();
            return;
        }

        var d = document.createElement("DIV");
        d.style.display = "none";
        iframeHolder.appendChild(d);
        d.innerHTML = "<form name='__IM_REDIRECT_FORM' method='get' target='baidu_webim' action='"+URL_BASE+"'></form>";
        _openWebim.form = document.forms["__IM_REDIRECT_FORM"];
        _openWebim.form.submit();
        d = null;

    }

    function _getDomain(){
        return document.domain;
    }

    function _sendCommand(method, self, to, params){

        var data = {
            username: to,
            self: self,
            method: method,
            params: params,
            domain: _getDomain()
        }

        _createIframe(URL_COMMAND, encodeURIComponent(baidu.json.encode(data)), _getHolder());

    }

    function init(){
        _createIframe(URL_OBSERVER, encodeURIComponent("{url:'" + URL_CONN + "',domain:'" + _getDomain() + "'}"), _getHolder())
    }

    function test(self){
        return true;
    }

    function open(method, self, to, params){

        if (_isWebimOpen == -1) { return false; }
        else if (_isWebimOpen == 0) {
            _openWebim(_getHolder());
        }
        _sendCommand(method, self, to, params);


        sandbox.report(method, self, to, params, "standard");

        if (params && params.onwebim) params.onwebim();
    }

    function setWebimStatus(status){
        _isWebimOpen = status;
    }

    return {
        init: init,
        test: test,
        open: open,
        setWebimStatus: setWebimStatus
    }

});


})();

window.im = window.im || {};
window.im.vendor = window.im.vendor || {};
window.im.vendor.rakuten = window.im.vendor.rakuten || {};

im.vendor.rakuten.User = function(username, subid, status, params){
  this.username = username;
  this.status = status;
  this.subid  = subid;
}

im.vendor.rakuten.Service = (function(){

  /*********config start*******/

  var URL_REALATED_USERS = "http://x.im.baidu.com/getsubstatus";

  var STATUS_MAP = {
    "online": 1,
    "offline": 0
  }

  /*********config end*******/

  function getRelatedUsersByUsername(username, callback){

    var url = URL_REALATED_USERS + "?callback=t&mainusername=" + encodeURIComponent(username);

    baidu.sio.callByServer(url, function(json){
      if(json.result && json.result == "ok"){
        var users = _parseToRakutenUsers(json.content.list);
        callback(1, users);
      }else{
        callback(0);
      }
    });

  }

  function _parseToRakutenUsers(jsonUserList){

    var users = [];

    for(var i=0, l=jsonUserList.length; i<l; i++){
      var userRaw = jsonUserList[i];
      if (userRaw) {
        var user = new im.vendor.rakuten.User(userRaw.username, userRaw.subid, STATUS_MAP[userRaw.status]);
        users.push(user);
      }
    }

    return users;
  }

  var pubs = {
    getRelatedUsersByUsername: getRelatedUsersByUsername,
    startBaiduHi: window.im.vendor.common.Service.startBaiduHi
  };

  return pubs;

})();


})();

