/**
 * Soj V2版本发码器
 * 如果使用在PC业务中需要依赖JSON2.js
 */
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.SiteTrackerV2 = factory());
}(this || window, (function () {

    var doc = document;
    //兼容低版本无console.log
    if(!window.console) {
        window.console = {
            log : function() {}
        }
    }

    /**
     * 扩展extend函数
     */
    function funExtend (target, source) {
        for (var p in source) {
            if (source.hasOwnProperty(p)) {
                target[p] = source[p];
            }
        }
        return target;
    };

    //获取游览器referrer
    function getReferrer() {
        var referrer = "";
        try {
            referrer = window.top.document.referrer;
        } catch (e) {
            if (window.parent) {
                try {
                    referrer = window.parent.document.referrer;
                } catch (e2) {
                    referrer = "";
                }
            }
        }
        if (referrer === "") {
            referrer = document.referrer;
        }
        return referrer;
    }

    //URI转码
    var encode = window.encodeURIComponent;
    //URI编码
    var decode = window.decodeURIComponent;
    //容器
    var container = document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0];
    var I = 0;
    
    /**
     * cookie是否存在对应字段
     */
    function hasCookieItem(key) {
        return (new RegExp("(?:^|;\\s*)" + encode(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie);
    }

    /**
     * 获取cookie
     */
    function getCookie(key) {
        if (!key || !hasCookieItem(key)) { return null; }
        return decode(doc.cookie.replace(new RegExp("(?:^|.*;\\s*)" + encode(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
    }

    /**
     * 创建post提交iframe
     */
    function createIframe(formId) {
        var iframe = doc.createElement("iframe");
        iframe.id = formId;
        iframe.name = formId;
        return iframe;
    }

    /**
     * 创建post提交表单
     */
    function createForm(formId, url, data) {
        var form = doc.createElement("form"),
            inputs = [];
        url = url || "";
        data = data || {};
        for(var k in data) {
            if(data.hasOwnProperty && !data.hasOwnProperty(k)) continue;
            inputs.push("<input type='hidden' name='"+k+"' value='"+data[k]+"' />");
        }
        form.innerHTML = inputs.join("");
        form.action = url || "";
        form.method = "post";
        form.target = formId;
        return form;
    }

    /**
     * 发送post类型日志
     */
    function sendPost(url, data) {
        var timeNow = new Date().getTime(),
            formId = "SOJ__ID" + timeNow.toString(16) + "" + (++I),
            div = doc.createElement("div");
        var iframe = createIframe(formId);
        var form = createForm(formId, url, data);
        div.appendChild(iframe);
        div.appendChild(form);
        div.style.display = "none";
        //将发码器插入dom
        container.appendChild(div);
        form.submit();
        form = null;
        iframe = null;
        //添加节点回收
        setTimeout(function() {
            container.removeChild(div);
            div = null;
        }, 3000);
    }

    /**
     * 发送get类型日志
     */
    function sendGet(url) {
        var script = doc.createElement("script");
        script.src = url;
        script.async = true;
        script.onload = function() {
            container.removeChild(script);
        };
        container.appendChild(script);
    }

    /**
     * url参数组装
     */
    function params(data) {
        var s = [],
            encode = encodeURIComponent;
        function add(key, value) {
            s[s.length] = encode(key) + "=" + encode(value);
        }
        for (var j in data) add(j, data[j]);
        return s.join("&").replace(/%20/g, "+");
    }

    /**
     * 发码行为工具支持get和post行为
     */
    function track(url, data) {
        //判断发码规则
        try {
            url = url + (url.indexOf("?") >= 0 ? "&" : "?") + params(data);
            if(url.length < 2000) {
                sendGet(url, data);
            } else {
                sendPost(url, data);
            }
        } catch(e) {
            //发送日志，无法发送soj
            window.console.log(e)
        }
    }

    /**
     * 发码器
     */
    function SiteTracker() {
        if(!JSON || !JSON.stringify || !JSON.parse){
            throw new Error("The browser does not support JSON, please add JSON2. Js");
        }
        this.source = {};
        this.setUid(getCookie("ajk_member_id") || 0);
        this.setGuid(getCookie("aQQ_ajkguid") || "");
        this.setCtid(getCookie("ctid") || "");
        this.setSsid(getCookie("sessid") || "");
        this.setR(getReferrer());
        this.setRp(getReferrer());
        var location = doc.location || window.location || {};
        this.setH(location.href || "");
        //设置默认服务器
        var protocol = location.protocol;
        this.setService(protocol + "//s.anjuke.com/stb");
    }

    /**
     * 函数定义
     * site     站点 
     *     anjuke           安居客
     *     jikejia          集客家
     *     broker           网络经纪人
     *     crm              crm系统
     *     anjuke_tencent   腾讯房产
     *     wuba             58同城
     *     ganji            赶集网
     * plat     平台
     *     1                PC
     *     2                Touch
     *     3                Pad
     *     4                微信小程序
     *     5                App
     * type     日志类型
     *     1                浏览日志
     *     2                点击日志
     *     3                曝光日志
     *     99               其他日志
     * p        页面标识
     * action   行为标识
     * cp       扩展参数(与扣费相关)
     * ep       扩展参数
     * h        url
     * r        上一页的url referer
     * rp       上一页的pageName
     * t        时间戳
     * guid     用户标识
     * ssid     会话标识
     * uid      登录标识
     * ctid     城市
     * service 设置日志接收服务器
     */
    var func = "site plat type p action cp h r rp t guid ssid uid ctid pn ep".split(" ");

    /**
     * 添加设置函数和获取函数
     */
    for(var k = 0; k < func.length; k++) {
        if(!func[k]) continue;
        (function(name, o) {
            var n = name.slice(0, 1).toUpperCase() + name.slice(1);
            o.prototype["set" + n] = function(v) {
                this.source[name] = v === undefined || v === null ? "" : v;
            }
            o.prototype["get" + n] = function() {
                return this.source[name];
            }
        })(func[k], SiteTracker);
    }

    SiteTracker.prototype.setService = function(v) {
        this.service = v || "";
    }

    SiteTracker.prototype.getService = function() {
        return this.service;
    }

    SiteTracker.prototype.getSource = function() {
        return this.source;
    }

    /**
     * 格式化cp参数
     */
    function formatCp(cp) {
        var rs = {};
        if(typeof cp == "string") {
            try {
                rs = JSON.parse(cp);
            } catch(e) {
                // window.console.log(e);
                rs.oldcp = cp;
            }
        } else if(typeof cp == "object" && cp !== null) {
            rs = cp;
        }
        return rs;
    }
    
    /**
     * 执行发码
     */
    SiteTracker.prototype.track = function(action, cp) {
        var handle = window.jQuery || window.Zepto || {};
        var extend = handle.extend ? handle.extend :
            (Object.assign ? Object.assign : funExtend);
        if(!this.service) {
            throw new Error("Please use the function setService to set the log to receive the server address!");
        }
        this.setT(+new Date());
        //设置action和cp
        this.setAction(action || "");
        this.setCp(JSON.stringify(formatCp(cp || {}) ) );
        if(!this.getUid()) {
            this.setUid(getCookie("ajk_member_id") || 0);
        }
        var data = this.source;
        track(this.service, data);
    }

    //绑定getCookie函数
    SiteTracker.prototype.getCookie = getCookie;

    return SiteTracker;
})));var APF = {
    log: function(v) {
/*
*/
    }
};

APF.Namespace = {
    register: function(ns){
        var nsParts = ns.split(".");
        var root = window;
        for (var i = 0; i < nsParts.length; i++) {
            if (typeof root[nsParts[i]] == "undefined") {
                root[nsParts[i]] = new Object();
            }
            root = root[nsParts[i]];
        }
    }
}

APF.Utils = {
    getWindowSize: function() {
        var myWidth = 0, myHeight = 0;
            if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return {
            width: myWidth,
            height: myHeight
        };
    },

    getScroll: function() {
        var scrOfX = 0, scrOfY = 0;
        if( typeof( window.pageYOffset ) == 'number' ) {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
        } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
        }
        return {
            left: scrOfX,
            top: scrOfY
        };
    },

    // http://techpatterns.com/downloads/javascript_cookies.php
    setCookie: function(name, value, expires, path, domain, secure) {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime(today.getTime());
        /*
            if the expires variable is set, make the correct
            expires time, the current script below will set
            it for x number of days, to make it for hours,
            delete * 24, for minutes, delete * 60 * 24
        */
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));

        document.cookie = name + "=" +escape(value) +
            ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "" ) +
            ((secure) ? ";secure" : "" );
    },

    // this fixes an issue with the old method, ambiguous values
    // with this test document.cookie.indexOf( name + "=" );
    getCookie: function(check_name) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for (i = 0; i < a_all_cookies.length; i++) {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split( '=' );

            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if (cookie_name == check_name) {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if (a_temp_cookie.length > 1) {
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if (!b_cookie_found) {
            return null;
        }
    },

    // this deletes the cookie when called
    deleteCookie: function(name, path, domain) {
        if (this.getCookie(name)) {
            document.cookie = name + "=" +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        }
    },

    setScrollTop: function (n){
        if (document.body) {
            document.body.scrollTop = n;
            if(document.body.scrollTop == 0){
                if (document.documentElement) document.documentElement.scrollTop = n;
            }
        }else if (document.documentElement) {
            document.documentElement.scrollTop = n;
        }
    },

    getScrollTop: function (){
        return document.body ? document.body.scrollTop || document.documentElement.scrollTop : document.documentElement.scrollTop;
    },

    /*
    *
    * APF.Utils.gotoScrollTop(e, s); 这个函数可传两个参数
    * e 是滚动条滚动到什么地方(end)的缩写，如果不传默认是 0
    * s 是滚动条滚动的速度 ，参数值是默认滚动速度的倍数，比如想要加快滚动速度为默认2倍，输入2 ，如果想放慢速度
    *   到默认速度的一半，输入 0.5 。 如果不传默认是 1，就是默认速度。
    */
    gotoScrollTop: function (e, s){
        var t = APF.Utils.getScrollTop(), n = 0, c = 0;
        var s = s || 1;
        var e = e || 0;
        var i = t > e ? 1 : 0;
        (function() {
            t = APF.Utils.getScrollTop();
            n = i ? t - e : e - t;
            c = i ? t - n / 15 * s : t + 1 + n / 15 * s ;
            APF.Utils.setScrollTop( c );
            if (n <= 0 || t == APF.Utils.getScrollTop()) return;
            setTimeout(arguments.callee, 10);
        })();
    }
};
/*
    json2.js
    2015-05-03

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse. This file is provides the ES5 JSON capability to ES3 systems.
    If a project might run on IE8 or earlier, then this file should be included.
    This file does nothing on ES5 systems.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 
                            ? '0' + n 
                            : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date 
                    ? 'Date(' + this[key] + ')' 
                    : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint 
    eval, for, this 
*/

/*property
    JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (typeof JSON !== 'object') {
    JSON = {};
}

(function () {
    'use strict';
    
    var rx_one = /^[\],:{}\s]*$/,
        rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
        rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
        rx_four = /(?:^|:|,)(?:\s*\[)+/g,
        rx_escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 
            ? '0' + n 
            : n;
    }
    
    function this_value() {
        return this.valueOf();
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function () {

            return isFinite(this.valueOf())
                ? this.getUTCFullYear() + '-' +
                        f(this.getUTCMonth() + 1) + '-' +
                        f(this.getUTCDate()) + 'T' +
                        f(this.getUTCHours()) + ':' +
                        f(this.getUTCMinutes()) + ':' +
                        f(this.getUTCSeconds()) + 'Z'
                : null;
        };

        Boolean.prototype.toJSON = this_value;
        Number.prototype.toJSON = this_value;
        String.prototype.toJSON = this_value;
    }

    var gap,
        indent,
        meta,
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        rx_escapable.lastIndex = 0;
        return rx_escapable.test(string) 
            ? '"' + string.replace(rx_escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string'
                    ? c
                    : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' 
            : '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) 
                ? String(value) 
                : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0
                    ? '[]'
                    : gap
                        ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
                        : '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === 'string') {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (
                                gap 
                                    ? ': ' 
                                    : ':'
                            ) + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (
                                gap 
                                    ? ': ' 
                                    : ':'
                            ) + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0
                ? '{}'
                : gap
                    ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
                    : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        };
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            rx_dangerous.lastIndex = 0;
            if (rx_dangerous.test(text)) {
                text = text.replace(rx_dangerous, function (a) {
                    return '\\u' +
                            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (
                rx_one.test(
                    text
                        .replace(rx_two, '@')
                        .replace(rx_three, ']')
                        .replace(rx_four, '')
                )
            ) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function'
                    ? walk({'': j}, '')
                    : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());
// dns劫持处理, 已删除
var SiteTracker = function(s, p, r, u) {
  if (s != undefined && s != null) {
    this.site = s;
  }

  if (p != undefined && p != null) {
    this.page = p;
  }

  if (r != undefined && r != null) {
    this.referer = r;
  }

  if (u != undefined && u != null) {
    this.uid = u;
  }

  this.serial = 0;
};

SiteTracker.prototype.getCookie = function(sKey) {
  if (!sKey || !this.hasItem(sKey)) { return null; }
  return decodeURIComponent(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
};

SiteTracker.prototype.hasItem =  function (sKey) {
  return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
};

SiteTracker.prototype.track = function(t_params) {
  this.buildParams();

  var src = "";

  if (typeof(t_params) == "undefined" || typeof(t_params.target_url) == "undefined") {
    src = location.protocol + "//s.anjuke.com/stb?__site=" + encodeURIComponent( this.params['site'] ) + "&";
  }
  else {
    src = t_params.target_url;
  }

  var prev_if = document.getElementById("sojtracker" + this.serial);
  while (prev_if) {
    this.serial += 1;
    prev_if = document.getElementById("sojtracker" + this.serial);
  }

  var ifContainer = document.createElement("div");
  ifContainer.innerHTML = '<iframe style="display:none" id="sojtracker' + this.serial + '" name="sojtracker' + this.serial + '" height="300" width="500"></iframe>';
  (document.getElementsByTagName('head')[0]).appendChild(ifContainer);

  var form = document.createElement("form");
  form.action = src;
  form.method = "post";
  for (var k in this.params) {
    try{
      var a = document.createElement("<input type='hidden' name='"+k+"'>");
    }catch (e){
      var a = document.createElement('input');
      a.setAttribute('type', 'hidden');
      a.setAttribute('name', k);
    }
    if (k == "uid") {
      a.value = this.params[k] || 0;
    } else {
      a.value = this.params[k] || "";
    }
    form.appendChild(a);
  }
  (document.getElementsByTagName('head')[0]).appendChild(form);
  form.target = "sojtracker" + this.serial;
  form.submit();
};

SiteTracker.prototype.buildParams = function() {
  var href  = document.location.href;

  var guid = this.getCookie(this.nGuid   || "aQQ_ajkguid");
  var ctid = this.getCookie(this.nCtid   || "ctid");
  var luid = this.getCookie(this.nLiu    || "lui");
  var ssid = this.getCookie(this.nSessid || "sessid");
  var uid  = this.getCookie(this.nUid    || "ajk_member_id");

  if (this.uid != undefined && this.uid != null) {
    uid = this.uid;
  }

  if (uid == undefined || uid == null || uid == "") {
    uid = 0;
  }

  var method = "";
  if (this.method != undefined && this.method != null) {
    method = this.method;
  }

  this.params = new Object();
  this.params.p = this.page;
  this.params.h = href;
  this.params.r = this.referer;
  this.params.site = this.site;
  this.params.guid = guid;
  this.params.ssid = ssid;
  this.params.uid  = uid;
  this.params.t = new Date().getTime();
  this.params.ctid = ctid;
  this.params.luid = luid;
  this.params.m = method;

  if (this.screen != undefined) {
    this.params.sc = JSON.stringify(this.screen)
  }

  if (this.cst != undefined && /[0-9]{13}/.test(this.cst)) {
    this.params.lt = this.params.t - parseInt(this.cst);
  }

  if (this.pageName != undefined) {
    this.params.pn = this.pageName;
  }

  if (this.customParam != undefined) {
    this.params.cp = this.customParam;
  }

};

SiteTracker.prototype.setSite = function(s) {
  this.site = s;
};

SiteTracker.prototype.setPage = function(p) {
  this.page = p;
};

SiteTracker.prototype.setPageName = function(n) {
  this.pageName = n;
};

SiteTracker.prototype.setCookieNames = function(c) {
  this.cookNames = c;
};

SiteTracker.prototype.setReferer = function(r) {
  this.referer = r;
};

SiteTracker.prototype.setUid = function(u) {
  this.uid = u;
};

SiteTracker.prototype.setMethod = function(m) {
  this.method = m;
};

SiteTracker.prototype.setNGuid = function(n) {
  this.nGuid = n;
};

SiteTracker.prototype.setNCtid = function(n) {
  this.nCtid = n;
};

SiteTracker.prototype.setNLiu = function(n) {
  this.nLiu = n;
};

SiteTracker.prototype.setNSessid = function(n) {
  this.nSessid = n;
};

SiteTracker.prototype.setNUid = function(n) {
  this.nUid = n;
};

SiteTracker.prototype.setCst = function(n) {
  this.cst = n;
};

SiteTracker.prototype.setScreen = function(v) {
  this.screen = v;
};

SiteTracker.prototype.setCustomParam = function(v) {
  this.customParam = v;
}
SiteTracker.prototype.getParams = function(){
  return this.params;
}
;
(function ($) {
	'use strict';
	var _aui = {};
	/**
	 * [nameSpace 注册命名空间]
	 * @param  {[string]} ns [成序列的命名空间，例如'aui.foo.bar']
	 * @return {[type]}    [description]
	 */
	_aui.nameSpace = function (ns) {
		var nsParts = ns.split(".");
		var root = window;
		for (var i = 0; i < nsParts.length; i++) {
			if (typeof root[nsParts[i]] == "undefined") {
				root[nsParts[i]] = {};
			}
			root = root[nsParts[i]];
		}
		return root;
	}
	/**
	 * errlog
	 */
	_aui.Config = { // 各种url
        devLogURL: 'http://www.fang.anjuke.test/ts.html?',
        logURL: '//www.fang.anjuke.com/ts.html?',
        isDev: /dev|test/.test(document.domain),
        blackList: ['BdPlayer','baiduboxapphomepagetag']
    };
    function isblack(str) {
        var i,
            reg,
            length,
            blackList = _aui.Config.blackList;
        if (typeof str !== 'string') { // 对于非字符串默认黑名单
            return true;
        }
        for (i = 0, length = blackList.length; i < length; i++) {
            reg = new RegExp(blackList[i], 'g');
            if (reg.test(str)) {
                return true;
            }
        };
    }
    function log(params) {
        var errorinfo = 'tp=error&site=kfs&msg=',
            key,
            url,
            arr = [],
            image,
            msg;
        if (typeof params === 'string') {
            msg = params;
        }
        if (typeof params === 'object') {
            for (key in params) {
                if (params.hasOwnProperty(key)) {
                    arr.push(key + ':' + encodeURIComponent(params[key]));
                }
            }
            msg = arr.join(',');
        }
        if (isblack(msg)) {
            return false;
        }
        image = new Image();
        if (_aui.Config.isDev) {
            url = _aui.Config.devLogURL + errorinfo + msg;
        } else {
            url = _aui.Config.logURL + errorinfo + msg;
        }
        image.src = url;
    }

	window.onerror = function(msg, url, line,col,obj) {
		var stack = '';
		if(obj && obj.stack){
			stack = obj.stack;
		}
		log({
			message: msg,
			url: url,
			line: line,
			col:col,
			stack:stack,
            pageUrl: location.href,
            UA: navigator.userAgent
		});
	}

	/**
	 * [inherit 方法：使得子构造函数继承父构造函数]
	 * @param  {[this]} my  [子构造函数的环境变量 this]
	 * @param  {[fn]} classParent [父构造函数]
	 * @param  {[Array]} args        [父构造函数初始化所需要的参数,如果有的话]
	 * @return {[undefined]}             [description]
	 */
	_aui.inherit = function (my, classParent, args) {
		classParent.apply(my, args || []);
		$.extend(my.constructor.prototype, classParent.prototype);
	}
	/**
	 * [Observer 简单的事件观察的构造函数]
	 * @return {[对象]}             [包含事件触发、绑定、解除绑定的方法]
	 */
	_aui.Observer = function () {
		this._ob = {};
	}
	/**
	 * [on 按照事件类型挂载回调函数]
	 * @param  {[type]}   eventNames [事件名称，可以多事件以空格分隔]
	 * @param  {Function} callback   [回调函数]
	 * @return {[type]}              [如果是单一事件则返回当前回调所在事件空间的key值，如果是多事件则是一个对象，事件名与key相对应 ]
	 */
	_aui.Observer.prototype.on = function (eventNames, callback) {
		var _events = eventNames.split(' ');
		var _eventKeys = {};
		for (var i = 0; i < _events.length; i++) {
			if (!this._ob[_events[i]]) {
				this._ob[_events[i]] = [];
			}
			var _key = this._ob[_events[i]].push(callback);
			_eventKeys[ _events[i] ] = _key - 1; // push 返回数组长度，key是现有长度减一。
		}
		return _eventKeys;
	}
	/**
	 * [off 解除绑回调函数]
	 * @param  {[string]} eventName [事件名]
	 * @param  {[array]} keys      [指定回调的 key 组成的数组，key会在绑定函数的时候（on方法）返回]
	 * @return {[type]}           [description]
	 */
	_aui.Observer.prototype.off = function (eventName, keys) {
		if (!!keys && !$.isArray(keys)) {
			keys = [keys]
		}
		if (this._ob[eventName]) {
			for (var i = 0; i < this._ob[eventName].length; i++) {
				if (!keys || $.inArray(i, keys)) {
					this._ob[eventName][i] = undefined;
				}
			}
		}
	}
	/**
	 * [trigger 事件触发]
	 * @param  {[type]} eventName [事件名]
	 * @param  {[type]} args      [希望传递给回调函数的 数组或arguments对象]
	 * @return {[type]}           [description]
	 */
	_aui.Observer.prototype.trigger = function (eventName, args) {
		var r;
		if (!this._ob[eventName]) {
			return r;
		}
		var _arg = args || [];
		for (var i = 0; this._ob[eventName] && i < this._ob[eventName].length; i++) {
			if (!this._ob[eventName][i]) {
				continue;
			}
			var _r = this._ob[eventName][i].apply(this, _arg);
			r = (r === false) ? r : _r;
		}
		return r
	}
	/**
	 * [one 只执行一次行为的绑定方法，事件执行后立即解除绑定]
	 * @param  {[string]}   eventName [事件名]
	 * @param  {Function} callback  [回调函数]
	 * @return {[type]}             [description]
	 */
	_aui.Observer.prototype.one = function (eventName, callback) {
		var self = this;
		var key = self.on(eventName, function () {
			callback.apply(this, arguments);
			self.off(eventName, key);
		});
	}
	/**
	 * [render 模板渲染，模板字符串只能用双引号，模板内的变量必须是data的属性，且值会转化为字符串或任意能转化为字符串的类型]
	 * @param  {[string]} tpl  [模板字符串]
	 * @param  {[object]} data [数据包，键值必须和模板想对应]
	 * @return {[string]}      [经过data数据渲染过后的html模板]
	 *    var tpl = '<dl><dt>{% dt %}</dt>';
	 *        tpl += '{%> if(dd){ %}';
	 *			tpl += '{%> for( var i=0; i< dd.length; i++){ %}';
	 *				tpl += '<dd><strong>{% dd[i].skill %}:</strong>{% dd[i].level %}</dd>';
	 *		 	tpl += '{%> } %}';
	 *		tpl += '{%> } %}';
	 *        tpl += '</dl>';
	 *    var da = ajk.render(tpl,{
	 *		dt:'gameLevel',
	 *		dd:[
	 *			{
	 *				skill:'Diablo',
	 *				level:70
	 *			},
	 *			{
	 *				skill:'Dota',
	 *				level:16
	 *			}
	 *		]
	 *	});
	 *    //da: '<dl><dt>gameLevel</dt><dd><strong>Diablo:</strong>70</dd><dd><strong>Dota:</strong>16</dd></dl>'
	 */
	_aui.render = function (tpl, data, op) {
		var daName = [], daVal = [], efn = [], _fnBuf,
			_op = $.extend({}, _aui.render._options, op || {});
		for (var i in data) {
			daName.push(i);
			daVal.push('data.' + i);
		}
		var _tp = tpl.replace(new RegExp(_op.open, 'g'), _op.open + _op.val);
		_fnBuf = _tp.split(new RegExp(_op.open + '|' + _op.close, 'g'));
		for (var i = 0; i < _fnBuf.length; i++) {
			if (new RegExp('^' + _op.val + _op.exp).test(_fnBuf[i])) {
				_fnBuf[i] = _fnBuf[i].replace(new RegExp('^' + _op.val + _op.exp), '');
			} else if (_fnBuf[i].length > 0) {
				if (new RegExp('^' + _op.val).test(_fnBuf[i])) {
					_fnBuf[i] = '_buf.push(' + _fnBuf[i].replace(new RegExp('^' + _op.val), '') + ');';
				} else {
					_fnBuf[i] = '_buf.push(\'' + _fnBuf[i] + '\');';
				}
			}
		}
		efn.push('(function(');
		efn.push(daName.join(','));
		efn.push('){');
		efn.push('var _buf = [];');
		efn.push(_fnBuf.join(''));
		efn.push('return _buf.join("")');
		efn.push('})(');
		efn.push(daVal.join(','));
		efn.push(')');
		return eval(efn.join(''));
	}
	_aui.render._options = {
		open : '{%',
		close: '%}',
		exp  : '>',
		val  : '='
	}
	_aui.nameSpace('XF');
	window.XF = _aui;
})(jQuery);
(function ($) {
	"use strict";
	XF.nameSpace('XF.Vars');//用于页面通用全局变量
	XF.nameSpace('XF.Validate');//用于通用验证
	XF.nameSpace('XF.WindowsOpen');//用于新窗口打开
	XF.Validate.phoneMobile = function (data) {
		return    /^1[3|4|5|7|8]\d{9}$/.test(data);
	};
	XF.Validate.phoneArea = function (data) {
		return    /^0\d{2,3}$/.test(data);
	};
	XF.Validate.phonePlane = function (data) {
		return    /^[2-9]\d{6,7}$/.test(data);
	};
	XF.Validate.email = function (data) {
		return    /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(data);
	};
    XF.Validate.smsCode = function (data) {
        return   /^\d{4}$/.test(data);
    };
	XF.Validate.imgCode = function (data) {
		return   /^.{4}$/.test(data);
	};
	XF.WindowsOpen.redirect = function (url) {
		if(!/*@cc_on!@*/0){
            window.open(url,'_blank');
        }else{
            var a = document.createElement('a');
            a.href = url;
            a.target = '_blank';
            document.body.appendChild(a);
            a.click();
        }
	}
})(jQuery);
;(function(window) {
	if(window && !window.console) {
		window.console = {
			log : function() {}
		}
	}
})(window);
XF.nameSpace('XF.Soj.send');
XF.nameSpace('XF.Soj.param');//用于当前PHP页面传入soj参数
//var data = "{'from':''}"; //定制参数，内容一般为JSON字符串.
//var op = {
//		Site:'anjuke-npv'
//		Page:'aifang_web_page'
//		PageName:'aifang_web_pageName'
//}
//详细参数请参看 ：http://gitlab.corp.anjuke.com/_incubator/sojourner/tree/master
;
(function ($) {
	//XF.Soj.send 可以在页面或js中直接调用 v1  2019-06-25 已经全部切换到v2
	XF.Soj.send = function (data, op , t_params) {
		var _op = $.extend({}, {
			Site: 'anjuke-npv'
		}, op || {});
		var st = new SiteTracker();
		//58pc
		for (var i in _op) {
			(typeof st['set' + i]).toLowerCase() == 'function' && st['set' + i](_op[i]);
		}
		var docreferrer = function () {
			var referrer = "";
			try {
				referrer = window.top.document.referrer;
			} catch (e) {
				if (window.parent) {
					try {
						referrer = window.parent.document.referrer;
					} catch (e2) {
						referrer = "";
					}
				}
			}
			if (referrer === "") {
				referrer = document.referrer;
			}
			return referrer;
		};
		st.setReferer(docreferrer());
		st.setCustomParam(data);
		st.track(t_params);

		if(!/npv/.test(_op.Site)){
			var _trackURL = st.getParams();
                delete _trackURL.cp;
                delete _trackURL.sc;
            window._trackURL = JSON.stringify(_trackURL);
            $.getScript('//tracklog.58.com/referrer_anjuke_pc.js', function() {
                st.setSite(_op.Site + '-npv');
                st.setPageName(_op.PageName + '_tracklog');
                st.setPage(_op.Page + '_tracklog');
                st.track();
            });
		}
	};

	/**
	 * 添加影痕v2发码器替换v1发码器
	 */
	if(window.SiteTrackerV2) {
		var stV2 = null;
		try {
			stV2 = new window.SiteTrackerV2();
		} catch(e){}
		//sojv2 目前所有城市开通，data 为自定义参数cp，op 传p，action,ep 
		var ctid = parseInt(stV2.getCtid(), 10) || 0;
		if(stV2) {//执行v2初始化
			stV2.setPlat(1);
			XF.Soj.send = function (data, op , t_params) {
				var _op = $.extend({}, {
					Site: 'anjuke'
				}, op || {});
				//判断发码类型
				if(_op.Exposure === true) {
					stV2.setType(3);
				} else if(/npv$/.test(_op.Site)) {
					stV2.setType(2);
				} else {
					stV2.setType(_op.Type || 2);
				}
				//添加pageName
				stV2.setP(_op.Page || _op.PageName || XF.pagename);
				stV2.setPn(_op.Page || _op.PageName || XF.pagename);
				t_params = t_params || {};
				if(t_params.target_url) {
					stV2.setService(t_params.target_url)
				}
				// 新传入action，区分下wb和ajk pc  2019-06-26
				if(stV2.getCookie('is_58_pc')){
					_op.Site = 'wuba';
					if(_op.action) _op.action = "wuba_PC_"+_op.action;
				}else{
					if(_op.action) _op.action = "ajk_PC_"+_op.action;
					_op.Site = 'anjuke';
				}

				stV2.setSite(_op.Site);
				stV2.setEp(JSON.stringify(formatEp(_op.ep || {})));
				stV2.track(_op.action || _op.Page || _op.PageName || XF.pagename, data);
				//pv码补充逻辑
				if(!/npv/.test(_op.Site) && _op.Exposure !== true){ 
					var _trackURL = stV2.getSource();
		            window._trackURL = JSON.stringify(_trackURL);
		            $.getScript('//tracklog.58.com/referrer_anjuke_pc.js', function() {});
				}
			}
		}
	}


	//页面加载玩之后给a标签设置from参数
	$('a[soj]').each(function (id, el) {
		var _this = $(el),
			_href = _this.attr('href') || '',
			_data = encodeURIComponent(_this.attr('soj'));
		if (/from=/.test(_href)) {
			return
		}
		_href = _href.split('#');
		var addData = ( /\?/.test(_href[0]) ) ? '&from=' + _data : '?from=' + _data;
		if (_href.length > 1) {
			addData += '#';
			_this.attr('href', _href.join(addData));
		} else {
			_this.attr('href', _href[0] + addData);
		}
	});

	XF.Exposure = function(op) {
		var defaults = {
			trackTag: 'data-trace',
			actionTag:'data-action',
		};
		this.ops = $.extend(defaults, op);
		this.domCache = []; // 保存内容
		this.expData = [];//保存数据
		this.pageViewHeight = $(window).height(); // 页面可视区域高度
		this.timer = null;
		this.data = {};
		this.init();
		this.expStatus = false;
	};
	XF.Exposure.prototype = {
		constructor: XF.Exposure,
		add: function(list) {
			var _this = this;
			this.expStatus = true;
			list.each(function(index, el) {
				_this.domCache.push($(el));
				_this.expData.push('');
			});
			$(window).scroll();	
		},
		init: function() {
			var wd = $(window);
			wd.resize($.proxy(this.resize, this)); // resize
			wd.on('beforeunload', $.proxy(this.beforeunload, this));
			wd.scroll($.proxy(this.scroll, this));
		},
		resize: function() {
			this.pageViewHeight = $(window).height();
		},
		beforeunload: function() {
			this.buildData();
		},
		scroll: function() {
			if (!this.expStatus) {
				return;
			}
			clearTimeout(this.timer);
			if (this.domCache.length === 0) {
				this.expStatus = false;
				this.buildData();
				return;
			}
			this.timer = setTimeout($.proxy(this.addData, this), 50)
		},
		sendExp: function(action,param) {
			var op = {
				Page:XF.pagename,
				PageName:XF.pagename,
				Exposure : true,
				action:action,
				ep: {exposure:param},
			};
			XF.Soj.send({},op);//第一个参数是cp
		},
		addData: function() {
			var pageViewHeight = this.pageViewHeight,
				topY = $(window).scrollTop(),
				botY = topY + pageViewHeight,
				_this = this;
			if (this.domCache.length === 0) {
				return;
			}
			
			$.each(this.domCache, function(index, val) {
				var _topY,
					data,
					key,
					arr,
					expkey,
					expval;
				if (!val) {
					return;
				}
				_topY = val.offset ? val.offset().top : 0;
				if (_topY > topY && _topY < botY) {
					data = val.data('trace') || {};
					action = val.data('action') || '';
					if(!data && !action){
						return;
					}
					var obj = {
						action: action || '',
						param : data || {}
					};
					_this.expData[index] = obj;
					// arr = data.match(/(Exp_\w+)\:(.*)}/);
					// if ($.isArray(arr)) {
					// 	if (!(arr[1] in _this.data)) {
					// 		_this.data[arr[1]] = [];
					// 	}
					// 	_this.data[arr[1]].push(arr[2]);
					// }
				}

			});
			this.buildData();
		},
		buildData: function() {
			var _this = this,
				result,
				i=0;
			var listData = $.extend({},this.expData);
			$.each(listData, function(index, obj) {
				index = index-i;
				if (obj && (obj.action || obj.param)) {
					_this.sendExp(obj.action,obj.param);
					_this.domCache.splice(index, 1); // 删除已统计过的dom
					_this.expData.splice(index,1);
					i++;
				}
			});
			// console.log(_this.expData);
		}
	};
})(jQuery);

/*检测到data-sojcommon就发送SOJ*/
function init_data_sojcommon(data_soj_param){
    if( typeof data_soj_param !== 'undefined' ){
        jQuery('*[data-sojcommon]').on('click.sendsoj', function () {
            var sojcommon = "{from:" + jQuery(this).data('sojcommon') + "}";
            XF.Soj.send(sojcommon,  data_soj_param);
        });
    }
}

function formatEp(ep){
	var rs = {};
	if(typeof ep == "string") {
		try {
			rs = JSON.parse(ep);
		} catch(e) {
			// window.console.log(e);
			rs.ep = ep;
		}
	} else if(typeof ep == "object" && ep !== null) {
		rs = ep;
	}
	return rs;
}
;(function ($) {
    var selopt = $('.sel-city');
    var citybox = $('.city-mod');
    var timer
    selopt.on('mouseenter',function(){
        citybox.show();
        selopt.find('.i-triangle').toggleClass('triangle-up');
    });
    selopt.on('mouseleave',function(){
        // citybox.hide();
        timer = setTimeout(function(){
            citybox.hide();
        },500);
        selopt.find('.i-triangle').toggleClass('triangle-up');
    });
    
    citybox.on('mouseenter',function(){
        if(timer) clearTimeout(timer)
    });
    citybox.on('mouseleave',function(){
        timer = setTimeout(function(){
            citybox.hide();
        },500);
        selopt.find('.i-triangle').toggleClass('triangle-up');
    });
})(jQuery);;
(function ($) {
	"use strict";
	XF.nameSpace('XF.Login');
	XF.Login = function (op) {
		var self = this;
		self.op = $.extend({
			loginST: '',
			pathUrl: '',
			baseUrl: ''
		}, op);
		self._init();
	};
	XF.Login.prototype._init = function () {
		var self = this, op = self.op, siteLogin = $(op.loginST);
		op.unLogin = siteLogin.find('.site-user');
		op.afLogin = siteLogin.find('.site-user-login');
		var timer
		/*客户登录下拉*/
		var dropUser = op.unLogin.find('.drop-user'), dropUserList = op.unLogin.find('.site-userlist');
		dropUser.on({'mouseenter.login': function () {
			dropUserList.show();
		}, 'mouseleave.login'          : function () {
			timer = setTimeout(function(){
				dropUserList.hide();
			}, 500)
		}});
		dropUserList.on('mouseenter',function(){
			if(timer) clearTimeout(timer)
		});
		dropUserList.on('mouseleave',function(){
			timer = setTimeout(function(){
				dropUserList.hide();
			},500);
		});
		/*登录－更新数据*/
		self.updateLogin();
	};
	XF.Login.prototype.updateLogin = function () {
		var self = this, op = self.op, isLoginCookie;
		$.ajax({
			type    : 'get',
			url     : op.baseUrl + op.pathUrl + '?r=' + Math.random(),
			dataType: 'jsonp',
			jsonp   : 'callback',
			success : function (rs) {
				var data = rs.data;
				// 增加后期判断是否登录变量
				XF.Vars.userid = data.user_id;
				isLoginCookie = APF.Utils.getCookie("aQQ_ajkauthinfos") || APF.Utils.getCookie("ajkAuthTicket");
				// 非正常用户，或者登录失败，则返回
				if (!data.user_id) {
					return false;
				}
				op.afLogin.html(self._loginUserTpl(data));
				var drop = op.afLogin.find('.drop-myajk'), list = op.afLogin.find('.site-myajk-list');
				var timer
				drop.off('mouseenter.login mouseleave.login').on({
					'mouseenter.login': function () {
						list.show();
					},
					'mouseleave.login': function () {
						timer = setTimeout(function(){
							list.hide();
						}, 500)
					}
				});
				list.on('mouseenter',function(){
					if(timer) clearTimeout(timer)
				});
				list.on('mouseleave',function(){
					timer = setTimeout(function(){
						list.hide();
					},500);
				});
				op.unLogin.remove();
			}
		});
	};

	XF.Login.prototype._loginUserTpl = function (data) {
		var menuLn = data.menu_list.length || 0;
		var tpl = '<li class="drop-myajk">';
		tpl += '<a href="javascript:"><image class="hicon hicon-user" src="//pic7.58cdn.com.cn/nowater/frs/n_v31ad2044976564e899cae6f35e75bc459.png"/><span class="user-name">' + data.user_name + '</span>&nbsp;<image class="arrow" src="//pic8.58cdn.com.cn/nowater/frs/n_v33a4d6e680bba459da9bc71173d99ae0d.png"/></a>';
		tpl += '<div class="site-myajk-list" style="display: none;">';
		$.each(data.menu_list, function(k, rows) {
			$.each(rows, function(i, row) {
				tpl += '<a target="_blank" href="' + row.url + '">'+row.name+'</a>';
			})
		});
		return tpl + '</div></li>';
	};
})(jQuery);;
(function ($) {
	"use strict";
	XF.nameSpace('XF.Search');
	XF.Search = function (op) {
		var self = this;
		XF.inherit(self, XF.Observer);
		self.op = $.extend({}, XF.Search._default, op);
		self._init();
	};
	XF.Search._default = {
		searchST  : '',
		formST    : '',
		inputST   : '',
		listST    : '',
		hoverClass: 'hover',
		initVal   : '',
		url       : '',
		t         : null,
		c         : null,
		n         : 8
	};
	XF.Search.prototype._init = function () {
		var self = this, op = self.op;
		op.search = $(op.searchST);
		op.form = op.search.find(op.formST);
		op.input = op.search.find(op.inputST);
		op.list = op.search.find(op.listST);
		op.btn = op.search.find(op.searchBtn);
		op.hideTimer;
		op.timeHander=null;
		/*设定输入框为空时的初始值，以及变化*/
		op.input.attr('placeholder', op.initVal);
		!$.trim(op.input.val()) && op.input.attr('value', op.initVal);
		op.input.on({
			'focus.search.init'  : function () {
                var soj= JSON.parse(op.soj);
				XF.Soj.send('{from:ajk_'+soj.click_input+'}', XF.Soj.param);
				$.trim($(this).val()) == op.initVal && $(this).val('');
				$(this).addClass('f-int-focus');
				var value = $(this).val();
				value && self.change(value,false);
			}, 'blur.search.init': function () {
				// $.trim($(this).val()) == '' && $(this).val(op.initVal);
				$(this).removeClass('f-int-focus');
			}
		});
		op.btn.on('click',function(){
			if(op.wcs_search == 1){
				var key = $.trim(op.input.val());
				if(key == '' || key == op.initVal){//输入为空的情况
					op.input.val('')
					op.form.submit();
				}else{
					self.change(key,true);
				}
			}else{
				self.submit();
			}

		});
		self.start();
	};
	/*绑定搜索联想键盘事件*/
	XF.Search.prototype.start = function () {
		var self = this, op = self.op;
		op.input.off('keyup.search.start focus.search.start blur.search.start');
		op.input.on({
			'keyup.search.start': function (event) {
				var inputVal = $.trim(op.input.val()), keycode = event.which;
				if (keycode == 38) {
					op.item && self.updown(op.item.index(op.item.filter('.' + op.hoverClass)), true);
				} else if (keycode == 40) {
					op.item && self.updown(op.item.index(op.item.filter('.' + op.hoverClass)), false);
				} else {
					if (inputVal != "") {
						var flag = keycode == 13?true:false;
						if(op.wcs_search != 1 && flag){//老搜索逻辑
							op.form.submit();
						}else{
							self.change(inputVal,flag);
						}
					} else {
						self.hide();
						op.list.html('');
					}
				}
			},
			'focus.search.start': function () {
				var sojParam = $.extend({},{action:'xf_loupan_find_click'},XF.Soj.param);
				var customParam = JSON.stringify({
					from:'wuba_pc_search_box_click',
				});
				XF.Soj.send(customParam,sojParam);
				var value = $.trim(op.input.val());
				value && self.change(value,false);

			},
			'blur.search.start' : function () {
				self.hide();
			}
		});
	};
	/*根据关键字进行搜索，并插入搜索结果*/
	XF.Search.prototype.change = function (kw,flag) {//flag为true点击搜索或enter提交表单
		var self = this, op = self.op;
        var listHtml = '';
        clearTimeout(op.timer);
        op.timer = setTimeout(function(){
        	$.ajax({
				type    : 'get',
				dataType: "jsonp",
	            jsonp   : 'callback',
				url     : op.brand_url,
				data    : {t: op.t, c: op.c, n: op.n, kw: kw, p : op.p || "",type: op.type, is_commercial: op.is_commercial, has_rent: op.has_rent, property: op.property},
				async   : false,//设置为true，页面新窗口会被浏览器拦截
				success : function (data) {
					var val = $.trim(op.input.val());
					if(val != kw) return;
					// if(op.wcs_search == 1){
						self.render(data,flag);
					// }else{
					// 	//老的搜索
					// 	self.renderContent(data);
					// }
				}
			});
        },300);
	};
	//老搜索渲染
	XF.Search.prototype.renderContent= function(data){
		var self = this, op = self.op;
        var listHtml = '';
        if(data.brand){
           var logo_url = data.brand.logo_url;
           var name = data.brand.brand_title;
           var url = data.brand.url;
           listHtml += '<li class="brand-itm"><a target="_blank" href='+url+'><img src='+logo_url+' width="95" height="30"><label>'+name+'</label>&nbsp;&nbsp;&gt;</a></li>';
        }
        if(data.content){
        	for (var i = 0; i < data.content.length; i++) {
				listHtml += '<li class="cnt-item"><label>' + data.content[i] + '</label></li>';
			}
        }
        if(listHtml != ''){
            op.list.html(listHtml);
            op.item = op.list.find('li');
            op.item.on({
                'mouseenter'   : function () {
                    $(this).addClass(op.hoverClass).siblings().removeClass(op.hoverClass);
                }, 'mouseleave': function () {
                    $(this).removeClass(op.hoverClass);
                }, 'click'     : function () {
                    op.input.val($(this).find('label').text());
                    self.submit();
                }
            });
            self.show();
            clearTimeout(op.hideTimer);
        }
	};
	XF.Search.prototype.render=function(data,flag){
		var self = this, op = self.op;
		var listHtml = '';
		//有品牌馆展示
		var hasBrand = (data.brand && $.isArray(data.brand) && data.brand.length>0) ? true :false;
        if(hasBrand){
		   var brand = data.brand;
		   var brand_obj = brand[0];

			if(flag){
				op.form.submit();
			}else{
				$.each(brand,function(index, obj){
					listHtml += '<li class="brand-itm"><a target="_blank" href="'+obj.url+'?from=brand_sslx"><label>'+obj.brand_title+'</label><em>品牌</em><span class="entry">进入品牌馆<i class="iconfont">&#xea1e;</i></span></a></li>';
				});
			}


		}
		var hasLoupan = (data.loupan && $.isArray(data.loupan) && data.loupan.length>0) ? true :false;
		//有楼盘
		if(hasLoupan){
			var loupan = data.loupan;
			if (!$.isArray(loupan)) {
			        return;
			    }
			    var obj = loupan[0];
			    if(loupan.length == 1 && flag){//匹配一条并且点搜索到楼单页
            if (obj.url) {
              var url = obj.url + (obj.url.indexOf('?') > -1 ? '&from=loupanlist_sslx' : '?from=loupanlist_sslx');
              XF.WindowsOpen.redirect(url);
            }
			    }else{
			    	if(flag){
			    		op.form.submit();
			    	}else{
			    		listHtml +=self.renderList(loupan);
			    	}
			    }
		}

		//没有楼盘没有品牌馆,置空
		if(!hasBrand && !hasLoupan){
			listHtml = '';
			op.list.html(listHtml);
            if(flag){
			 	op.form.submit();
			}
		}

        if(listHtml != ''){
            op.list.html(listHtml);
        	op.item = op.list.find('li');
			op.item.on({
			    'mouseenter'   : function () {
	                $(this).addClass(op.hoverClass).siblings().removeClass(op.hoverClass);
		        },
			    'mouseleave': function () {
			        $(this).removeClass(op.hoverClass);
			    },
			    'click':function(){
			        var href = $.trim($(this).data('href')),
			        soj = $.trim($(this).data('soj'));
              if (href) {
                if (href.indexOf('?') > -1) {
                  href += '&from='+soj;
                } else {
                  href += '?from='+soj;
                }
                XF.WindowsOpen.redirect(href);
              }
			    }
			});
			self.show();
      		clearTimeout(op.hideTimer);
        }
	};
	XF.Search.prototype.renderList = function(data){
		var op= this.op,self = this,
			arr = [];
		 $.each(data, function(index, obj) {
		 	var html = "<li class='itm' data-href="+obj.url+" data-soj='loupanlist_sslx' >";
		 		html += "<p class='name'>"+obj.nameEm;
		 		if(!!obj.aliasEm && obj.aliasEm != ''){
		 			html += "<i>别名:"+obj.aliasEm+"</i>";
				 }
				if(op.has_rent == 1){
					if(!!obj.rentStatus){ //有租状态显示租赁状态
						if(!!obj.rentStatusName && obj.rentStatusName!= ''){
							html += "<em>"+obj.rentStatusName+"</em>"
						}
					}
				}else{
					if(!!obj.saleStatusName && obj.saleStatusName != ''){
						html += "<em>"+obj.saleStatusName+"</em>"
					}
				}


		 		html +="</p>";
		 		if(!!obj.addrEm && obj.addrEm != ''){
		 			html += "<p class='address'><label>"+obj.addrEm+"</label>";
				}
				var priceObj = {};
				if(op.has_rent == 1){
					if(!!obj.rentStatus){ //有租状态显示租价格
						if(!!obj.rentPrice){
							priceObj =  obj.rentPrice;
							if(!priceObj.hasOwnProperty('value')|| obj.rentStatus == 99){
								html += "<em>租金待定</em>";
							}
						}
					}
				}else{
					if(!!obj.price){
						priceObj =  obj.price;
					}
				}
				if(priceObj.hasOwnProperty('value')){
					if(op.has_rent == 1 && obj.rentStatus == 99){
						html += '';
					}else{
						html += "<em>"+ (priceObj.front || '') +" "+(priceObj.value || '')+ (priceObj.back || '')+"</em>";
					}
				}

		 		html += "</p></li>";
		 	arr.push(html);
		 });
		return arr.join('');

	};
	XF.Search.prototype.updown = function (index, upordown) {
		var self = this, op = self.op, len = op.item.length;
		if (upordown) {
			index = index <= 0 ? len - 1 : index - 1;
		} else {
			index = index < 0 || index == len - 1 ? 0 : index + 1;
		}
		op.item.eq(index).addClass(op.hoverClass).siblings().removeClass(op.hoverClass);
		var text= op.item.eq(index).data('key');
		op.input.val(text);
	};
	XF.Search.prototype.stop = function () {
		var self = this, op = self.op;
		op.input.off('keyup.search.start focus.search.start blur.search.start');
		self.hide();
	};
	XF.Search.prototype.submit = function () {
		var self = this, op = self.op;
		var param = '{from:ajk_pc_search_event_click}';
		XF.Soj.send(param, XF.Soj.param);
		//获取搜索的结果，判断跳转到那个页面
		var key = $.trim(op.input.val());
		if(op.wcs_search == 1){
			self.change(key,true);
		}else{
			op.form.submit();
		}
	};
	XF.Search.prototype.show = function () {
		var self = this, op = self.op;
		op.list.fadeIn(100);
	};
	XF.Search.prototype.hide = function () {
		var self = this, op = self.op;
		op.timer && clearTimeout(op.timer);
		op.hideTimer = setTimeout(function () {
			op.list.hide();
		}, 200);
	};
})(jQuery);
;
(function ($) {
	"use strict";
	XF.nameSpace('XF.HotSearch');
	XF.HotSearch = function (op) {
		var self = this;
		XF.inherit(self, XF.Observer);
		self.op = $.extend({}, XF.HotSearch._default, op);
		self._init();
	};
	XF.HotSearch._default = {
		gSearch   : null,
		hSearchST : '',
		hoverClass: ''
	};
	XF.HotSearch.prototype._init = function () {
		var self = this, op = self.op, input = op.gSearch.op.input;
		/**/
		op.hideTimer;
		op.hSearch = $(op.hSearchST);
		op.item = op.hSearch.find('li');
		op.hSearch.appendTo(op.gSearch.op.search);
		op.gSearch.stop();
		/**/
		input.on({
			'keyup.hotsearch': function (event) {
				var inputVal = $.trim(input.val()), keycode = event.which;
				if (keycode == 38) {
					op.item && self.updown(op.item.index(op.item.filter('.' + op.hoverClass)), true);
				} else if (keycode == 40) {
					op.item && self.updown(op.item.index(op.item.filter('.' + op.hoverClass)), false);
				} else {
					if (inputVal != "") {
						self.hide();
						input.trigger('focus.search.start');
					} else {
						clearTimeout(op.hideTimer);
						self.show();
					}
				}
			},
			'focus.hotsearch': function () {
				$.trim(input.val()) == "" && self.show();
			},
			'blur.hotsearch' : function () {
				self.hide();
			}
		});
		/**/
		op.item.on({
			'mouseenter.hotsearch'   : function () {
				$(this).addClass(op.hoverClass).siblings().removeClass(op.hoverClass);
			}, 'mouseleave.hotsearch': function () {
				$(this).removeClass(op.hoverClass);
			}, 'click.hotsearch'     : function () {
				//点击热门楼盘，直接跳转到楼单页
				var href = $.trim($(this).data('href')),
					soj = $.trim($(this).data('soj'));
					href &&  XF.WindowsOpen.redirect(href+'?from='+soj);

				// input.val($(this).find('.lp-name').text());
				// op.gSearch.submit();
			}
		});
	};
	XF.HotSearch.prototype.show = function () {
		var self = this, op = self.op;
		op.hSearch.fadeIn(100);
		op.gSearch.stop();
	};
	XF.HotSearch.prototype.hide = function () {
		var self = this, op = self.op;
		op.hideTimer = setTimeout(function () {
			op.hSearch.hide();
		}, 200);
		op.item.removeClass(op.hoverClass);
		var inputVal = $.trim(op.gSearch.op.input.val());
		if(inputVal !=''){
			op.gSearch.start();
		}else{
			op.gSearch.hide();
		}
		
	};
	XF.HotSearch.prototype.updown = function (index, upordown) {
		var self = this, op = self.op, len = op.item.length;
		var input = op.gSearch.op.input;
		if (upordown) {
			index = index <= 0 ? len - 1 : index - 1;
		} else {
			index = index < 0 || index == len - 1 ? 0 : index + 1;
		}
		op.item.eq(index).addClass(op.hoverClass).siblings().removeClass(op.hoverClass);
		input.val(op.item.eq(index).find('.lp-name').text());
	};
})(jQuery);;(function ($) {
   "use strict";
   XF.nameSpace('XF.footer');
   XF.footer.foldedLayer = function(onbtn,offbtn,layer){
       var onbtn = $(onbtn);
       var layer = $(layer);
       var offbtn = $(offbtn);
       onbtn.on('click',function(){
       	   layer.show();
       });
       offbtn.on('mouseleave',function(){
       	   setTimeout(function(){layer.hide();},1000);
       });
   };
})(jQuery);;
(function ($) {
	"use strict";
	XF.nameSpace('XF.Modal');
	XF.Modal = function (op) {
		var self = this;
		XF.inherit(self, XF.Observer);
		self.op = $.extend({}, XF.Modal._default, op);
		self.op.ie6 = /MSIE 6/.test(navigator.userAgent);
	};
	XF.Modal._default = {
		modalClass: '', //className,多个类名空格分开
		con       : '', //conHtml
		hd        : '', //headerHtml
		title     : '', //titleText
		subtitle: '', //弹窗幅标题
		bd        : '', //bodyHtml
		ft        : '', //footerHtml
		width     : 560, //Number
		height    : '', //Number
		pos       : {top: undefined, left: undefined},//Number
		mask      : true, //true,false，遮罩层
		duration  : 200, //Number，动画持续时间
		showCloseButton:true //true,false 是否显示关闭按钮
	};
	XF.Modal.prototype._create = function () {
		var self = this,
			op = self.op;
		//生成节点
		op.modal = $('<div class="xf-modal"></div>');
		op.modalMask = $('<div class="modal-mask"></div>');
		op.modalIfr = $('<iframe class="modal-ifr"></iframe>');
		op.modalCover = $('<div class="modal-cover"></div>');
		//写入节点内容
		var shadow = $('<div class="shadow"></div>'),
			close = $('<a href="javascript:" class="close iconfont">&#xea29;</a>'),
			con = $('<div class="con"></div>').append($(op.con).show()),
			hd = $('<div class="hd"></div>').append($(op.hd).show()),
			bd = $('<div class="bd"></div>').append($(op.bd).show()),
			ft = $('<div class="ft"></div>').append($(op.ft).show());
		//插入节点
		if(!op.subtitle){
			!op.hd && op.title && hd.html('<h3 class="title">' + op.title + '</h3>');
		}else{
			!op.hd && op.title && op.subtitle && hd.html('<h3 class="title">' + op.title + '</h3><h4 class="subtitle">'+op.subtitle+'</h4>');
		}
		op.con || $().add((op.hd || op.title) && hd).add(op.bd && bd).add(op.ft && ft).appendTo(con);
		con.add(close).appendTo(op.modal);
		op.modalClass && op.modal.addClass(op.modalClass);
		con.css({width: op.width, height: op.height});
		op.modalCover.append(op.modal).appendTo('body');
		//关闭按钮事件
		close.on('click.modal', function () {
			$('html').removeClass('modal-open');
			self.close();
		});
		//是否添加遮罩层
		var docHeight = $(document).height();
		op.mask && op.modalMask.css({'height': docHeight}).appendTo('body');
		//ie6添加iframe
		op.ie6 && op.modalIfr.css({'height': docHeight}).appendTo('body');
		if (!op.showCloseButton) {
			close.css({'visibility': 'hidden'});
		}
	};
	/**
	 * [center 弹出框居中函数]
	 */
	XF.Modal.prototype.center = function (node, duration) {
		if(!node) {
			return;
		}
		var self = this,
			op = self.op,
			nodeWidth = node.outerWidth(),
			nodeHeight = node.outerHeight(),
			winHeight = $(window).height();
		//弹出内容超过一屏时，隐藏body滚动条，显示弹出框滚动条，ie6全部隐藏body滚动条
		if (op.ie6 || nodeHeight > winHeight) {
			$('html').css({'overflow': 'hidden'});
			op.modalCover.css({'overflow': 'auto'});
		} else {
			$('html').css({'overflow': ''});
			op.modalCover.css({'overflow': 'hidden'});
		}
		//未传入pos值，默认居中定位
		if (op.pos.top === undefined || op.pos.left === undefined) {
			var _left = -parseInt(nodeWidth / 2, 10),
				_top = -parseInt(nodeHeight / 2, 10);
			if (nodeHeight > winHeight) {
				_top = -parseInt(winHeight / 2, 10);
			}
			// node.animate({'margin-top': _top, 'margin-left': _left,'z-index':10000}, duration);
		} else {
			node.animate(op.pos, duration);
		}
	};
	/**
	 * [open 弹出框打开函数]
	 * 可绑定函数 openBefore,openAfter
	 */
	XF.Modal.prototype.open = function () {
		var self = this, op = self.op, undefined = window.undefined;
		//计算位置
		function calpos(duration) {
			op.ie6 && op.modalCover.css({'top': $(window).scrollTop()});
			self.center(op.modal, duration);
		}

		if ($(self).trigger('openBefore') !== false) {
			//第一次弹出，则插入节点到body
			(op.modal === undefined) && self._create();
			calpos(0);
			//解决页面穿透
			$('html').addClass('modal-open');
			op.modalCover.add(op.modalMask).add(op.modalIfr).css({'display': 'block'});
			//绑定窗口resize事件
			$(window).off('resize.modal').on('resize.modal', function () {
                var fe = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;
				op.timer && clearTimeout(op.timer);
				op.timer = setTimeout(function () {
                    // 如果当前有全屏的元素则不相应resize事件，用于视频播放时。
					!fe && calpos(op.duration);
				}, 200);
			});
			$(self).trigger('openAfter');
		}
	};
	/**
	 * [close 弹出框关闭函数]
	 * 可绑定函数 closeBefore,closeAfter
	 */
	XF.Modal.prototype.close = function () {
		var self = this, op = self.op;
    $('html').removeClass('modal-open');
		if ($(self).trigger('closeBefore') !== false) {
			if (op.modal !== undefined) {
				op.modalCover.css({'overflow': 'hidden'}).add(op.modalMask).add(op.modalIfr).css({'display': 'none'});
				$('html').css({'overflow': ''});
				$(window).off('resize.modal');
				$(self).trigger('closeAfter');
			}
		}
	};
})(jQuery);
;
(function ($) {
	"use strict";
	XF.nameSpace('XF.Select');
	XF.Select = function (op) {
		var self = this;
		self.op = $.extend({}, XF.Select._default, op);
		self.op.ie6 = /MSIE 6/.test(navigator.userAgent);
		self._init();
	};
	XF.Select._default = {
		selectST    : ".xf-select",//下拉框选择器，String
		focusClass  : 'xf-select-fo',//打开下拉内容后添加的类名，String
		hoverClass  : 'option-hv',//下拉选项hover后添加的类名，String
		disableClass: 'option-dis',//下拉选项禁用类名，能显示不能选择，String
		adaptive    : true//下拉框的宽度是否根据父元素自适应，Boolean
	};
	XF.Select.prototype._init = function () {
		var self = this, op = self.op;
		op.$select = $(op.selectST);
		op.$select.each(function () {
			//获取DOM元素
			var $thisSelect = $(this),
				$text = $thisSelect.find('.text'),
				$input = $text.find('input'),
				$span = $text.find('span'),
				$ul = $thisSelect.find('ul'),
				$li = $ul.find('li').not('.' + op.disableClass),
				$initLi = $li.filter('.' + op.hoverClass).removeClass(op.hoverClass).eq(0);
			//初始值可自定义输入，也可通过“option-hv”指定某一选项
			$initLi.length && change($initLi.text(), $initLi.data('code'));
			//模拟ie6下的宽度自适应
			if (op.ie6 && op.adaptive) {
				var maxHeight = parseInt($ul.css('height')),
					actualHeight = $ul.css('height', 'auto').outerHeight() - 2,
					liWidth = $text.outerWidth() - parseInt($li.css('padding-left')) - 2;
				if (actualHeight > maxHeight) {
					$ul.css('height', maxHeight);
					$li.css('width', liWidth - 17);
				} else {
					$li.css('width', liWidth);
				}
				$ul.css('width', $text.outerWidth());
			}
			//下拉框打开和关闭事件
			$text.on('click.select', function (event) {
				event.stopPropagation();
				$thisSelect.hasClass(op.focusClass) ? close() : open();
			});
			$(document).on('click.select', function () {
				close();
			});
			$ul.on({
				'mouseenter': function () {
				$(this).addClass(op.hoverClass);
				}, 
				'mouseleave'     : function () {
					$(this).removeClass(op.hoverClass);
				}, 
				'click'          : function () {
					if(!$(this).hasClass(op.disableClass)){
						change($(this).text(), $(this).data('code'));
					}
				}
		    },'li');
			function open() {
				op.$select.not($thisSelect.addClass(op.focusClass)).removeClass(op.focusClass);
			}

			function close() {
				$thisSelect.removeClass(op.focusClass);
			}

			//改变text和code
			function change(text, code) {
				if ($input.val() != ( code || text)) {
					$input.val(code || text);
					$span.text(text);
					$(self).trigger('change', [$input]);
				}
			}
		});
	};
})(jQuery);;XF.nameSpace('XF.Kft.CarPoperV2');
;(function($) {
    XF.Kft.CarPoperV2 = function(op){
        this.ops = $.extend(this.ops, op||{});
        this.init();
    }
    XF.Kft.CarPoperV2.prototype={
        init:function(){
            var self = this,
            data = JSON.parse(self.ops.data);
            /*看房团报名*/
            //[{ tid:xxx, {lp_name:xxx} }]
            XF.Vars.kftCarData = JSON.parse(data.zhuanche_data_json);
            //{ p:xxx , pn:xxx}
            XF.Vars.guid = data.guid;
            XF.Vars.sojData = JSON.parse(data.soj_data_json);
            //做特殊错误识别的代码
            XF.Vars.kftErrCode = {vcode:24001,vcodeError:24002,vcodeExpired:24003};
        }
    }
    
})(jQuery);;
(function($){
    if (window.need_mobile_code) {
        return;
    }
    XF.nameSpace('XF.Subscribe');
    XF.Subscribe = function (options) {
        this.options    = options;
        this.subSuccess = $('#subscribe-success');
        this.subFail    = $('#subscribe-fail');
        this.item = {
            subBtn     : $('#subscribe-success .mailsub-btn'), 
            subInput   : $('#subscribe-success .mail-input'),
            errBox     : $('#subscribe-success .com-msg'),
            subSuccess : $('#mailsub-success')
        }
        this.acts();
    };
    XF.Subscribe.prototype.subAjax = function(){
        var self  = this,subArgus = this.options;
        var param = this.param =  {
            source_id : XF.Vars.loupan_id,//楼盘ID
            phone     : subArgus.inputVal,
            sub_from  : 101,
            category  : subArgus.category
        };
        $.post(__base_url + '/list/subscribe/',param,function(data){
            if(data==0||data==3){
                subArgus.type=='show'?
                self.showSuccess():
                self.toSuccess();
            }else{
                subArgus.type=='show'?
                self.showFail():
                self.toFail();
            }
        },'text');
    }
    XF.Subscribe.prototype.showSuccess = function(){
        var self  = this;
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : this.subSuccess,
            width     : '560',
            height    : '354'
        });
        subModal.open();
    }
    XF.Subscribe.prototype.showFail = function(){
        var self  = this;
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : self.subFail,
            width     : '560',
            height    : '397'
        });
        subModal.open();
    }
    XF.Subscribe.prototype.toSuccess = function(){
        var self  = this;
        closeModal();
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : self.subSuccess,
            width     : '560',
            height    : '354'
        });
        subModal.open();
        // $('.modal-subscribe .bd').empty().append(self.subSuccess.show());
    }
    XF.Subscribe.prototype.toFail = function(){
        var self  = this;
        closeModal();
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : self.subFail,
            width     : '560',
            height    : '354'
        });
        subModal.open();
        // $('.modal-subscribe .bd').empty().append(self.subSuccess.show());
    }
    XF.Subscribe.prototype.acts = function(){
        var self = this;
        self.item.subBtn.off('click').on('click',function(){//123
            var mail   = $.trim(self.item.subInput.val());
            var errBox = self.item.errBox;
            var sucModal = new XF.Modal({
                modalClass: 'modal-custom',
                title     : '优惠订阅',
                bd        : self.item.subSuccess,
                width     : '560',
                height    : '316'
            });
            if(mail == ''){
                self.item.subInput.addClass('int-err');
                errBox.show().find('span').text('邮箱地址不能为空！');
            }else if(!XF.Validate.email(mail)){
                self.item.subInput.addClass('int-err');
                errBox.show().find('span').text('请正确输入邮箱地址！');
            }else{
                errBox.hide();
                self.item.subInput.removeClass('int-err');
                var params = {
                    loupan_id : self.param.source_id,
                    phone     : self.param.phone,
                    email     : mail,
                    position  : 4
                };
                $.ajax({
                    type:'post',
                    data:params,
                    dataType:'text',
                    url:'/emailsubscribe/',
                    success : function(result){
                        closeModal();
                        result && sucModal.open();
                    }
                });
            }
            
        });
    }
    function closeModal(){
        $('.modal-cover').css('visibility','hidden');
        $('.modal-mask').css('visibility','hidden');
    }

})(jQuery);

(function($){
    if (window.need_mobile_code) {
        return;
    }
    var subscribe    = $('.subscribe-mix');
    var subSuccess   = $('#subscribe-success');
    var subFail      = $('#subscribe-fail');
    var colResult    = $('.collect-result');
    var favor        = $('.collect-result');
    var checkbox     = subscribe.find(':checkbox');
    var phone        = subscribe.find('.cell-phone');
    var submitBtn    = subscribe.find('.btn');
    var msgBox       = subscribe.find('.com-msg');
    var errMsg       = subscribe.find('.com-msg').children('span');
    
    var favsubmitBtn = favor.find('.btn');
    var favphone     = favor.find('.cell-phone');
    var favmsgBox    = favor.find('.com-msg');
    var faverrMsg    = favor.find('.com-msg').children('span');

    //触发收藏弹出层事件
    $('.unfavor').on('click',function(){
        var favorModel = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '收藏信息',
            bd        : favor,
            width     : '560',
            height    : '397'
        });
        favorModel.open();
    });

    //触发订阅弹出层事件
    $('.subscribe-link').on('click',function(){
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : subscribe,
            width     : '560',
            height    : '397'
        });
        var subData = $(this).attr('sub-data');
        if(subData){
            var checkbox = subscribe.find(':checkbox');
            checkbox.prop('checked',false);
            $.each(subData.split(","), function(k, subData) {
                checkbox.filter('[sub-data='+subData+']').prop('checked',true);
            });
        }
        subModal.open();
    });

    //清除默认提示
    phone.one('focus',function(){
        $(this).val('');
    });
    favphone.one('focus',function(){
        $(this).val('');
    });

    //确认订阅请求
    $(document).on('click','.subscribe-mix .btn',function(){
        var favCodes  = '';
        var forward   = true;
        var inputVal  = $.trim(phone.val());
        if(!checkbox.filter(':checked').length){
            errMsg.html('请选择需要订阅的内容！');
            forward  = false;
        }else if(!inputVal || inputVal=="请输入您的手机号码"){
            errMsg.html('手机号码不能为空！');
            forward  = false;
        }else if(!XF.Validate.phoneMobile(inputVal)){
            errMsg.html('请正确输入手机号！');
            forward  = false;
        }
        if(!forward) {
            phone.addClass('int-err');
            msgBox.show();
        }else{
            checkbox.filter(':checked').each(function(){
                favCodes+=$(this).val()+'|';
            });
            phone.removeClass('int-err');
            msgBox.hide();
            var xfSubscribe = new XF.Subscribe({
                type    :'to',
                inputVal:inputVal,
                category:favCodes.substring(0,favCodes.length-1)
            });
            xfSubscribe.subAjax();
        }
    });

    //收藏确认手机号
    $(document).on('click','.collect-result .btn',function(){
        var favCodes = '3';
        var forward  = true;
        var inputVal = $.trim(favphone.val());
        if(!inputVal || inputVal=="请输入您的手机号码"){
            faverrMsg.html('手机号码不能为空！');
            forward  = false;
        }else if(!XF.Validate.phoneMobile(inputVal)){
            faverrMsg.html('请正确输入手机号！');
            forward  = false;
        }
        if(!forward) {
            favphone.addClass('int-err');
            favmsgBox.show();
        }else{
            favphone.removeClass('int-err');
            favmsgBox.hide();
            var xfSubscribe = new XF.Subscribe({
                type    :'to',
                inputVal:inputVal,
                category:favCodes
            });
            xfSubscribe.subAjax();
        }
    });

})(jQuery);
;
(function($){
    if (!window.need_mobile_code) {
        return;
    }
    XF.nameSpace('XF.Subscribe');
    XF.Subscribe = function (options) {
        this.options    = options;
        this.subSuccess = $('#subscribe-success');
        this.subFail    = $('#subscribe-fail');
        this.item = {
            subBtn     : $('#subscribe-success .mailsub-btn'), 
            subInput   : $('#subscribe-success .mail-input'),
            errBox     : $('#subscribe-success .com-msg'),
            subSuccess : $('#mailsub-success')
        }
        this.acts();
    };
    XF.Subscribe.prototype.subAjax = function(){
        var self  = this,subArgus = this.options;
        var param = this.param = {
            source_id : loupan_id,//楼盘ID
            phone     : subArgus.inputVal,
            sub_from  : 101,
            category  : subArgus.category,
            type      : 10,
            code      : subArgus.codePara.val
        };
        $.post(__base_url + '/list/subscribe/',param,function(data){
            if(data==0||data==3){
                subArgus.type=='show'?
                self.showSuccess():
                self.toSuccess();
                subArgus.codePara.dom.removeClass('int-err');
                subArgus.codePara.msgSms.hide();
            }else if(data==-1){
                subArgus.codePara.dom.addClass('int-err');
                subArgus.codePara.msgSms.show();
                subArgus.codePara.msg.text('验证码已过期');
            }else if(data==-2){
                subArgus.codePara.dom.addClass('int-err');
                subArgus.codePara.msgSms.show();
                subArgus.codePara.msg.text('验证码错误');
            }else if(data==-3){
               self.options.smsMod.show();
            }else{
                subArgus.codePara.dom.removeClass('int-err');
                subArgus.codePara.msgSms.hide();
                subArgus.type=='show'?
                self.showFail():
                self.toFail();
            }
        },'text');
    }
    XF.Subscribe.prototype.showSuccess = function(){
        var self  = this;
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : this.subSuccess,
            width     : '560',
            height    : '354'
        });
        subModal.open();
    }
    XF.Subscribe.prototype.showFail = function(){
        var self  = this;
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : self.subFail,
            width     : '560',
            height    : '397'
        });
        subModal.open();
    }
    XF.Subscribe.prototype.toSuccess = function(){
        var self  = this;
        closeModal();
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : self.subSuccess,
            width     : '560',
            height    : '354'
        });
        subModal.open();
        // $('.modal-subscribe .bd').empty().append(self.subSuccess.show());
    }
    XF.Subscribe.prototype.toFail = function(){
        var self  = this;
        closeModal();
        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : self.subFail,
            width     : '560',
            height    : '354'
        });
        subModal.open();
        // $('.modal-subscribe .bd').empty().append(self.subSuccess.show());
    }
    XF.Subscribe.prototype.acts = function(){
        var self = this;
        self.item.subBtn.off('click').on('click',function(){
            var mail   = $.trim(self.item.subInput.val());
            var errBox = self.item.errBox;
            var sucModal = new XF.Modal({
                modalClass: 'modal-custom',
                title     : '优惠订阅',
                bd        : self.item.subSuccess,
                width     : '560',
                height    : '316'
            });
            if(mail == ''){
                self.item.subInput.addClass('int-err');
                errBox.show().find('span').text('邮箱地址不能为空！');
            }else if(!XF.Validate.email(mail)){
                self.item.subInput.addClass('int-err');
                errBox.show().find('span').text('请正确输入邮箱地址！');
            }else{
                errBox.hide();
                self.item.subInput.removeClass('int-err');
                var params = {
                    loupan_id : self.param.source_id,
                    phone     : self.param.phone,
                    email     : mail,
                    position  : 4
                };
                $.ajax({
                    type:'post',
                    data:params,
                    dataType:'text',
                    url:'/emailsubscribe/',
                    success : function(result){
                        closeModal();
                        result && sucModal.open();
                    }
                });
            }
            
        });
    }
    function closeModal(){
        $('.modal-cover').css('visibility','hidden');
        $('.modal-mask').css('visibility','hidden');
    }

})(jQuery);

(function($){
    if (!window.need_mobile_code) {
        return;
    }
    var subscribe    = $('.subscribe-mix'); 
    var openLayer = $('#subscribe-basic').find('.notice-list');
    var subSuccess   = $('#subscribe-success');
    var subFail      = $('#subscribe-fail');
    var favor        = $('.collect-result');
    var phone        = $('.subscribe-code-1').find('.c-phone');
    var verfiyCode   = $('.subscribe-code-1').find('.img-code-int');
    var smsCode      = $('.subscribe-code-1').find('.sms-code-int');
    var msgBox       = $('.subscribe-code-1').find('.msg-box');
    var errMsg       = $('.subscribe-code-1').find('.msg-box').children('span'); 
    var isShowImgMod = $('.subscribe-code-1 .j-is-show');
    var isShowSmsMod = $('.subscribe-code-1 .j-sms-show');  
    var timeDelayStatus;
    var timeDelay;


    var favPhone        = $('.subscribe-code-2').find('.c-phone');
    var favVerfiyCode   = $('.subscribe-code-2').find('.img-code-int');
    var favSmsCode      = $('.subscribe-code-2').find('.sms-code-int');
    var favMsgBox       = $('.subscribe-code-2').find('.msg-box');
    var favErrMsg       = $('.subscribe-code-2').find('.msg-box').children('span');    
    var isFavShowImgMod = $('.subscribe-code-2 .j-is-show');
    var isFavShowSmsMod = $('.subscribe-code-2 .j-sms-show');
    var openPhoneVal;   
    var timeDelayFav;
    var timeDelayStatusFav;
    var doubleClick = true;

    //触发收藏弹出层事件
    $('.unfavor').on('click',function(){
        var favorModel = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '收藏信息',
            bd        : favor,
            width     : '560'
        });
        favorModel.open();
    });
    // 楼盘单页和地图交通Tab页 （开放式入口,类型选择）
    function setSubscribeType(){
        var isTypeOpenSubData = 0 ;
        if($('.subscribe-open-a .sub-list').length){
            var openPage = $('.subscribe-open-a .sub-list li'),
                input = openPage.find('input');
                input.each(function(index,element){
                    $(element).attr('sub-data',index+1);
                });
                input.filter(':checked')
                     .prop('checked',true);
            openLayer.empty().append(openPage.clone());
        }else{
            isTypeOpenSubData = 1;
        }
    }    
    //楼盘单页和地图交通Tab页 （手机号码验证）
    function openPhoneValide(phone,msgBox,errMsg){
        var val = $.trim(phone.val()),
            msgPhone = msgBox,
            msg = errMsg;
            val = val == '请输入您的手机号码' ? '':val;
            msgPhone.show();
        if(val != '' && !XF.Validate.phoneMobile(val)){
            phone.addClass('int-err');
            msg.html('请正确输入手机号！');
            return false;
        }else if(val ==""){
            phone.addClass('int-err');
            msg.html('手机号码不能为空！');
            return false;
        }else{
            openPhoneVal = val;
            phone.removeClass('int-err');
            msgPhone.hide();
            return true;
        }
    }
    //订阅内容验证
    function openContentValide(dom,msgBox,errMsg){
        if(!dom.length){
            msgBox.show();
            errMsg.html('请选择需要订阅的内容！');
            return false; 
        }else{
            msgBox.hide();
            return true;
        }
    }
    // 是否启用订阅验证
     function isContentsValide(){
          var  openSub = $('.subscribe-open-a .acti-group'),
               msgBox = openSub.next(),
               errMsg = msgBox.find('span'),
               boxCont = openSub.parent().prev(),
               checkBox = boxCont.find('input').filter(':checked');
               if(boxCont.length){
                    return openContentValide(checkBox,msgBox,errMsg);
                }else{
                    return true;
                }
     }
     //收藏调接口判断是否显示图片验证码
     function isFavShowImagValideCode(){
        $.post(__base_url + "/vcode/image/", {}, function (data) {
            if (data.status == 1) {//成功
                isFavShowImgMod.show();
                isFavShowSmsMod.show();
            }else{
                isFavShowImgMod.hide();
            }
        }, 'json');
     }
     //调接口判断是否显示图片验证码
     function isShowImagValideCode(){
        $.post(__base_url + "/vcode/image/", {}, function (data) {
            if (data.status == 1) {//成功
                isShowImgMod.show();
                isShowSmsMod.show();
            }else{
                isShowImgMod.hide();
            }
        }, 'json');
     }
     // 清空数据
    function clearDataInput(){
        var phoneDa = $('.xf-verify-module').find('.c-phone');
        var verfiyCodeDa = $('.xf-verify-module').find('.img-code-int');
        var smsCodeDa = $('.xf-verify-module').find('.sms-code-int');
        var msgBoxDa = $('.xf-verify-module').find('.msg-box');
        phoneDa.removeClass('int-err');
        verfiyCodeDa.attr('placeholder',_errConfig.code.defaults);
        verfiyCodeDa.val('');
        verfiyCodeDa.removeClass('int-err');        
        smsCodeDa.attr('placeholder',_errConfig.smscode.defaults);
        smsCodeDa.val('');
        smsCodeDa.removeClass('int-err');
        msgBoxDa.hide();
     }
    //触发订阅弹出层事件
    /*
        * 侧边浮层的订阅 subscribe-link（非开放式）
        * 选择订阅类型 .subscribe-open-a .acti-group（开放式）
        * 直接订阅 subscribe-open-btn（开放式）
    */
    $('.subscribe-link,.subscribe-open-a .acti-group,.subscribe-open-btn').on('click',function(){
        // 防止双击触发两次
        if (!doubleClick) {
            return;
        }
        doubleClick = false;
        setTimeout(function(){
            doubleClick = true;
        }, 500);

        var subModal = new XF.Modal({
            modalClass: 'modal-custom modal-subscribe',
            title     : '订阅信息',
            bd        : subscribe,
            width     : '560'
        });
        var subData = $(this).attr('sub-data');
        if(subData){
            var checkbox = openLayer.find(':checkbox');
            checkbox.prop('checked',false);
            $.each(subData.split(","), function(k, subData) {
                checkbox.filter('[sub-data='+subData+']').prop('checked',true);
            });
        }
        // 开放式订阅              
        if($(this).prev().attr('data-subscribe') == 'open'){
            var dom = $(this).prev(),
                msgBox = $(this).next(),
                errMsg = msgBox.find('span'),
                checkBox = $(this).parent().prev().find('input').filter(':checked');
                setSubscribeType();  
            if(openPhoneValide(dom,msgBox,errMsg) && isContentsValide()){
                phone.val(openPhoneVal); 
                subModal.open(); 
            }
        }else{            
            subModal.open(); 
            if(APF.Utils.getCookie('xf_register_phone')){
                phone.val(APF.Utils.getCookie('xf_register_phone'));                
            } 
        }
        isShowSmsMod.hide();
        // 调接口判断是否显示图片验证码
        isShowImagValideCode();
        refreshCodeImg();
        clearDataInput();
        clearTimeDelayHandle();
    });
    $('.int-text').each(function () {
        $(this).on({
            'focus.inttext': function () {
                $(this).addClass('int-focus');
            },
            'blur.inttext' : function () {
                $(this).removeClass('int-focus');
            }
        });
    });
    
    // 订阅验证码
    var checkList = [],
        _errConfig = {
            'subscribe': {'contents':'请选择需要订阅的内容！'},
            'phone'    : {'defaults':'请输入您的手机号码','empty':'手机号码不能为空！','format':'请正确输入手机号！'},
            'code'     : {'defaults':'请输入图片码','empty':'图片码不能为空','format':'图片码错误'},
            'smscode'  : {'defaults':'请输入短信验证码','empty':'短信验证不能为空','format':'短信验证码错误'}
        };   
    //是否选择订阅内容
    checkList['subscribe'] = function(){
        var checkbox = subscribe.find(':checkbox'); 
        var msgPhone = msgBox.eq(0);
            msg = errMsg.eq(0);
            msgPhone.show();
        if(!checkbox.filter(':checked').length){
            msg.html(_errConfig['subscribe'].contents);
            return false;
        }else{            
            msgPhone.hide();
            return true;
        }
    }
    // 手机号码的验证    
    checkList['phone'] = function(){
        var val = $.trim(phone.val()),
            msgPhone = msgBox.eq(0),
            msg = errMsg.eq(0);

            val = val == _errConfig['phone'].defaults ? '':val;
        if(val != '' && !XF.Validate.phoneMobile(val)){
            msgPhone.show();
            phone.addClass('int-err');
            msg.html(_errConfig['phone'].format);
            return false;
        }else if(val ==""){
            msgPhone.show();
            phone.addClass('int-err');
            msg.html(_errConfig['phone'].empty);
            return false;
        }else{
            phone.removeClass('int-err');
            msgPhone.hide();
            return true;
        }
    }
    // 半开放订阅有3处
    if(APF.Utils.getCookie('xf_register_phone')){
        //楼盘单页的开放式订阅（1）
        $('.subscribe-open-a').find('.cell-phone').val(APF.Utils.getCookie('xf_register_phone'));  
        //楼盘子页的公用模块的开放式订阅（2）
        $('.subscript').find('.int-text').val(APF.Utils.getCookie('xf_register_phone'));
        //实体探盘处的开放式订阅 （3）       
        $('.subscribe-tanpan').find('.int-text').val(APF.Utils.getCookie('xf_register_phone'));
    } 
    // 图片验证码
    checkList['imgCode'] = function(){
        var val = $.trim(verfiyCode.val()),
            msgCode = msgBox.eq(1);
            msg = errMsg.eq(1);
            val = val == _errConfig['code'].defaults ? '':val; 
        if (val!='' && val.length!=4) {
            msgCode.show();
            verfiyCode.addClass('int-err');
            msg.html(_errConfig['code'].format);
            return false;
        } else if(val==''){
            msgCode.show();
            verfiyCode.addClass('int-err');
            msg.html(_errConfig['code'].empty);
            return false;
        }else {
            verfiyCode.removeClass('int-err');
            msgCode.hide();
            return true;
        }
    }
    // 短息验证码
     checkList['smsCode'] = function(){
        var val = $.trim(smsCode.val()),
            msgSms  = msgBox.eq(2),
            msg = errMsg.eq(2);
            val = val == _errConfig['smscode'].defaults ? '':val;
            msgSms.show();
           
            if(val != '' && !XF.Validate.smsCode(val)){
                smsCode.addClass('int-err');
                msg.html(_errConfig['smscode'].format);
                return false;
            }else if(val ==""){
                smsCode.addClass('int-err');
                msg.html(_errConfig['smscode'].empty);
                return false;
            }else{
                smsCode.removeClass('int-err');
                msgSms.hide();
                return true;
            }
     }
     // 图片验证码是否启用
     checkList['isShowCode'] = function(){
        if(isShowImgMod.is(':visible')){
            return checkList['imgCode']();
        }else{
            return true;
        }
     }
      // 短信验证码是否启用
     checkList['isShowSmsCode'] = function(){
        if(isShowSmsMod.is(':visible')){
            return checkList['smsCode']();
        }else{
            return true;
        }
     }      
      //刷新图片验证函数 
     function refreshCodeImg(){
         var newStamp = $.now(), newSrc,
            codeImg  = $('.subscribe-code-1 .refresh-btn').prev();
            newSrc = codeImg.attr('src').substr(0,codeImg.attr('src').length-13) + newStamp;
            codeImg.attr('src',newSrc);
     }
     // 发送短信验证函数
     function verfiyPhone(obj, inputVal,time) {
        var mobieData = {
            phone:inputVal,
            type :10
        };
        if(isShowImgMod.is(':visible')){
            mobieData.imagecode = $.trim(verfiyCode.val());
        }
        $.ajax({
            url: __base_url + '/vcode/mobilecode/',
            type: 'post',
            dataType: 'json',
            data: mobieData,
            success : function(data){
                    var msgPhone,
                        phoneText,
                        msgImg,
                        imgText;
                        msgPhone = msgBox.eq(0),
                        phoneText = errMsg.eq(0),
                        msgImg = msgBox.eq(1),
                        imgText = errMsg.eq(1);                     
                    if(data.rst > 0){
                        verfiyCountdown(obj, time);
                        msgPhone.hide();
                        msgImg.hide();
                    }else if(data.rst==-3){
                        isShowImgMod.show();
                        msgImg.show();
                        verfiyCode.addClass('int-err');
                        imgText.html(data.msg);
                    }else{
                        if(isShowImgMod.is(':visible')){
                            msgImg.show();
                            verfiyCode.addClass('int-err');
                            imgText.html(data.msg);
                        }else{
                            verfiyCode.removeClass('int-err');
                            msgPhone.show();
                            msg.html(data.msg);
                        }
                    }
                }
        }); 
    }
    // 倒计时函数
     function verfiyCountdown(obj, time) {
        if (time == 0) {
            obj.removeAttr('disabled');
            obj.removeClass('f-getcode-dis');
            obj.text('发送短信验证码');
            time = time;
            getverfiyCode();
            timeDelayStatus = false;
        } else {
            obj.attr('disabled', 'disabled');
            obj.addClass('f-getcode-dis');
            obj.text(time + '秒后重新发送');
            obj.off('click.send');
            time--;
            timeDelay = setTimeout(function() {
                verfiyCountdown(obj, time);
            }, 1000);
            timeDelayStatus = true;
        }
    }
    // 订阅清空倒计时
    function clearTimeDelayHandle(){
        if(timeDelayStatus){
            clearTimeout(timeDelay);
            $('.subscribe-code-1 .send-sms-btn').removeAttr('disabled');
            $('.subscribe-code-1 .send-sms-btn').removeClass('f-getcode-dis');
            $('.subscribe-code-1 .send-sms-btn').text('发送短信验证码');
            getverfiyCode();
        }
    }
    // 刷新图片验证码
    $('.subscribe-code-1 .refresh-btn').on('click.refresh',function(){
        refreshCodeImg();
    });
    // 发送短信验证码按钮
    function getverfiyCode(){
        $('.subscribe-code-1 .send-sms-btn').on('click.send',function(){
            var val = $.trim(phone.val());
            if(checkList['phone']() && checkList['isShowCode']()){
                verfiyPhone($(this),val,60);
            }
        });
    }
    getverfiyCode();
    //点击立即订阅按钮
    $(document).on('click','.subscribe-mix .btn',function(){
        var favCodes  = '';       
        var inputVal  = $.trim(phone.val());
        var codeVal = $.trim(smsCode.val());
        var msgSms = msgBox.eq(2);
        var msg = errMsg.eq(2);
        if(checkList['subscribe']()&&checkList['phone']() &&checkList['isShowCode']() && checkList['isShowSmsCode']()){
            var checkbox = subscribe.find(':checkbox'); 
            checkbox.filter(':checked').each(function(){
                favCodes+=$(this).val()+'|';
            });
            phone.removeClass('int-err');
            msgBox.hide();
            var xfSubscribe = new XF.Subscribe({
                type    :'to',
                inputVal:inputVal,
                category:favCodes.substring(0,favCodes.length-1),
                smsMod  :isShowSmsMod,
                codePara:{val:codeVal,msgSms:msgSms,msg:msg,dom:smsCode}
            });
            xfSubscribe.subAjax();
        }
    });


   // 收藏**************************/
    var favCheckList = [];    
   
    // 手机号码的验证
    favCheckList['phone'] = function(){
        var val = $.trim(favPhone.val()),
            msgPhone = favMsgBox.eq(0),
            msg = favErrMsg.eq(0);
            val = val == _errConfig['phone'].defaults ? '':val;
            msgPhone.show();
        if(val != '' && !XF.Validate.phoneMobile(val)){
            favPhone.addClass('int-err');
            msg.html(_errConfig['phone'].format);
            return false;
        }else if(val ==""){
            favPhone.addClass('int-err');
            msg.html(_errConfig['phone'].empty);
            return false;
        }else{
            favPhone.removeClass('int-err');
            msgPhone.hide();
            return true;
        }
    }
    // 图片验证码
    favCheckList['imgCode'] = function(){
       var val = $.trim(favVerfiyCode.val()),
            msgCode = favMsgBox.eq(1);
            msg = favErrMsg.eq(1);
            val = val == _errConfig['code'].defaults ? '':val;           
        if (val!='' && val.length!=4) {
            msgCode.show();
            favVerfiyCode.addClass('int-err');
            msg.html(_errConfig['code'].format);
            return false;
        } else if(val==''){
            msgCode.show();
            favVerfiyCode.addClass('int-err');
            msg.html(_errConfig['code'].empty);
            return false;
        }else {
            favVerfiyCode.removeClass('int-err');
            msgCode.hide();
            return true;
        }
    }
    // 短息验证码
     favCheckList['smsCode'] = function(){
        var val = $.trim(favSmsCode.val()),
            msgSms = favMsgBox.eq(2),
            msg = favErrMsg.eq(2);
            val = val == _errConfig['smscode'].defaults ? '':val;
            
            if(val != '' && !XF.Validate.smsCode(val)){
                msgSms.show();
                favSmsCode.addClass('int-err');
                msg.html(_errConfig['smscode'].format);
                return false;
            }else if(val ==""){
                msgSms.show();
                favSmsCode.addClass('int-err');
                msg.html(_errConfig['smscode'].empty);
                return false;
            }else{
                favSmsCode.removeClass('int-err');
                msgSms.hide();
                return true;
            }
     }
     // 图片验证码是否启用
     favCheckList['isShowCode'] = function(){
        if(isFavShowImgMod.is(':visible')){
            return favCheckList['imgCode']();
        }else{
            return true;
        }
     } 
     // 短信验证码是否启用
     favCheckList['isShowSmsCode'] = function(){
        if(isFavShowSmsMod.is(':visible')){
            return favCheckList['smsCode']();
        }else{
            return true;
        }
     }     
      //刷新图片验证函数 
     function favRefreshCodeImg(){
         var newStamp = $.now(), newSrc,
            codeImg  = $('.subscribe-code-2 .refresh-btn').prev();
            newSrc = codeImg.attr('src').substr(0,codeImg.attr('src').length-13) + newStamp;
            codeImg.attr('src',newSrc);
     }
     // 发送短信验证函数
     function favVerfiyPhone(obj, inputVal,time) {
        var mobieData = {
            phone:inputVal,
            type :10
        };
        if(isFavShowImgMod.is(':visible')){
            mobieData.imagecode = $.trim(favVerfiyCode.val());
        }
        $.ajax({
            url: __base_url + '/vcode/mobilecode/',
            type: 'post',
            dataType: 'json',
            data: mobieData,
            success : function(data){
                    var msgPhone,
                        phoneText,
                        msgImg,
                        imgText;
                        msgPhone = favMsgBox.eq(0),
                        phoneText = favErrMsg.eq(0),
                        msgImg = favMsgBox.eq(1),
                        imgText = favErrMsg.eq(1);                     
                    if(data.rst > 0){
                        verfiyCountdown(obj, time);
                        msgPhone.hide();
                        msgImg.hide();
                        favVerfiyCode.removeClass('int-err');
                    }else if(data.rst==-3){
                        isShowImgMod.show();
                    }else{
                        if(isFavShowImgMod.is(':visible')){
                            msgImg.show();
                            favVerfiyCode.addClass('int-err');
                            imgText.html(data.msg);
                        }else{
                            favVerfiyCode.removeClass('int-err');
                            msgPhone.show();
                            msg.html(data.msg);
                        }
                    }
                }
        }); 
    }
    // 倒计时函数
     function favVerfiyCountdown(obj, time) {
        if (time == 0) {
            obj.removeAttr('disabled');
            obj.removeClass('f-getcode-dis');
            obj.text('发送短信验证码');
            time = time;
            favGetverfiyCode();
            timeDelayStatusFav = false;
        } else {
            obj.attr('disabled', 'disabled');
            obj.addClass('f-getcode-dis');
            obj.text(time + '秒后重新发送');
            obj.off('click.favSend');
            time--;
            timeDelayFav = setTimeout(function() {
                favVerfiyCountdown(obj, time);
            }, 1000);
            timeDelayStatusFav = true;
        }
    }
    // 收藏清空倒计时
    function clearTimeDelayHandleFav(){
        if(timeDelayStatusFav){
            clearTimeout(timeDelayFav);
            $('.subscribe-code-2 .send-sms-btn').removeAttr('disabled');
            $('.subscribe-code-2 .send-sms-btn').removeClass('f-getcode-dis');
            $('.subscribe-code-2 .send-sms-btn').text('发送短信验证码');
            favGetverfiyCode();
        }
    }
    // 刷新图片验证码
    $('.subscribe-code-2 .refresh-btn').on('click.refresh',function(){
        favRefreshCodeImg();
    });
    // 发送短信验证码按钮
    function favGetverfiyCode(){
        $('.subscribe-code-2 .send-sms-btn').on('click.favSend',function(){
            var val = $.trim(favPhone.val());
            if(favCheckList['phone']() && favCheckList['isShowCode']()){
                favVerfiyPhone($(this),val,60);
            }
        });
    }
    favGetverfiyCode();
     $('#z-addFav').on('click',function(){
         isFavShowImagValideCode();
         clearTimeDelayHandleFav();
         isFavShowSmsMod.hide();
         if(APF.Utils.getCookie('xf_register_phone')){
            favPhone.val(APF.Utils.getCookie('xf_register_phone'));
        }
     });
    //收藏确认手机号
    $(document).on('click','.collect-result .btn',function(){
        var favCodes = '3';
        var inputVal  = $.trim(favPhone.val());
        var codeVal =  $.trim(favSmsCode.val());
        var msgSms = favMsgBox.eq(2);
        var msg = favErrMsg.eq(2);
        favRefreshCodeImg();
        if(favCheckList['phone']() &&favCheckList['isShowCode']() && favCheckList['isShowSmsCode']()){
            favPhone.removeClass('int-err');
            var xfSubscribe = new XF.Subscribe({
                type    :'to',
                inputVal:inputVal,
                category:favCodes,
                smsMod  :isFavShowSmsMod,
                codePara:{val:codeVal,msgSms:msgSms,msg:msg,dom:favSmsCode}

            });
            xfSubscribe.subAjax();
        }
    });

    // 点击关闭按钮 短信验证码关闭
    $('body').on('click','.xf-modal .close',function(){
        $('.j-sms-show').hide();
    });

})(jQuery);
;(function($) {
    XF.nameSpace('XF.pc');
    var sideBar;
    XF.pc.sideBar = sideBar = function(op) {
        this._op = $.extend({}, {
            sideBarBox: $('.sidebar'),
            toTop: $('.sidebar-top'),
            sidebarNav: $('.sidebar-mod a'),
            minWidth: 1280,
            minTop: 400
        }, op || {});

        this.init();
    };

    sideBar.prototype.init = function() {
        var self = this;
        self.checkVisible();
        $(window).on('scroll resize', function() {
            self.checkVisible();
        });
        self.getQrcodeWeapp()
        self._op.toTop.on('click',function(e) {
            $('html,body').animate({
                scrollTop: 0
            }, 100);
        });

    };

    //得到小程序二维码
    sideBar.prototype.getQrcodeWeapp = function () {
        var self = this;
        var weappcode = $('#qrcode_weapp');
        var imgUrl="";
        setTimeout(function(){
            if(window.QrCodeImg){
                imgUrl = window.QrCodeImg;
                weappcode.attr('src',imgUrl);
            }else{
                $.ajax({
                type: 'get',
                url: __base_url + '/aifang/web/ajax/getQrCode/',
                data:{loupan_id:self._op.loupan_id,from:'loupan_view'},
                context: weappcode,
                success: function(res){
                    var data = JSON.parse(res)||{};
                    if(data.status=='true'||data.status==true){
                        imgUrl = decodeURIComponent(data.image_url);
                        window.QrCodeImg = imgUrl;
                        if(imgUrl){
                            weappcode.attr('src',imgUrl);
                        }
                    }else {
                        weappcode.hide();
                    }
                },
                error: function () {
                    weappcode.hide();
                }})
            }
        },500);    
    }

    sideBar.prototype.checkVisible = function() {
        var self = this,
            winWidth = $(window).width(),
            scrollTop = $(window).scrollTop();

        //sidebar 通栏是否显示
        if (winWidth > self._op.minWidth) {
            self._op.sideBarBox.show();
            self._op.sideBarBox.stop().animate({
                right: '0px'
            }, 100)
            self._op.toTop.removeClass('sd-top-sig');
        } else {
            self._op.sideBarBox.stop().animate({
                right: '-40px'
            }, 100)
            self._op.toTop.addClass('sd-top-sig');
        }

        if (scrollTop > self._op.minTop) {
            self._op.sideBarBox.show();
            self._op.toTop.show();
        } else {
            self._op.sideBarBox.hide();
            self._op.toTop.hide();
        }

        self.slideNav();

    };

    sideBar.prototype.slideNav = function() {
        var self = this;
        self._op.sidebarNav.hover(
            function() {
                var hoverWidth = '135px';
                $(this).children('.sidebar-nav-hover').css('visibility','visible')
                $(this).children('.sidebar-nav-hover').stop()
                    .animate({
                        width: hoverWidth
                    }, 100);
            },
            function() {
                $(this).children('.sidebar-nav-hover').stop()
                    .animate({
                        width: '0px'
                    }, 100)
                $(this).children('.sidebar-nav-hover').css('visibility','hidden')
            }
        )
    };

})(jQuery);
;
(function ($) {
	/*看房意向弹窗*/
	var intentBd = $('.modal-intention-bd');
	var modalIntent = new XF.Modal({
		modalClass: 'modal-custom',
		title     : '看房意向',
		bd        : intentBd,
		width     : '560'
	});
	var intentStatus = $('.modal-intention-status');
	var modalIntentStatus = new XF.Modal({
		modalClass: 'modal-custom',
		title     : '看房意向',
		bd        : intentStatus,
		width     : '560',
		height    : '400'
	});
    var intentStatusErr = $('.modal-intention-status-err');
    var modalIntentStatusErr = new XF.Modal({
        modalClass: 'modal-custom',
        title     : '看房意向',
        bd        : intentStatusErr,
        width     : '560',
        height    : '400'
    });
	var textArea = $('.modal-intention-bd .intention-info textarea'),
		intentSubmit = $('.modal-intention-bd .btn-box .btn'),
		areaInt = $('.modal-intention-bd .area-info .text input'),
		phoneInt = $('.modal-intention-bd .phone-box .int-text'),
		phoneMsg = $('.modal-intention-bd .phone-box .com-msg'),
		phoneMsgCon = phoneMsg.find('span'),
		pregflagPhone = false,
		oldVal = $.trim(phoneInt.val()),
		initText = $.trim(textArea.val());

	$('#j-intention').on('click',function(){
 		modalIntent.open();
 	});

	var myst = new XF.Select({
		selectST   : '.modal-intention-bd .xf-select'
	});
	/* phoneInt, focus边框样式，value值改变 */
	phoneInt.on({
		'focus': function () {
			var self = $(this);
			var newVal = $.trim(self.val());
			newVal == oldVal && self.val('');
			self.addClass('int-focus');
		},
		'blur' : function () {
			var self = $(this);
			var newVal = $.trim(self.val());
			newVal == '' && self.removeClass('int-focus');			
		}
	});
	/* textArea, value值改变 */
	textArea.on({
		'focus': function () {
			var self = $(this);
			var newVal = $.trim(self.val());
		   	newVal == initText && self.val('');
		   	self.addClass('int-focus');
		},
		'blur' : function () {
			var self = $(this);
			var newVal = $.trim(self.val());
			newVal == '' && self.val(initText);
			self.removeClass('int-focus');		
		},
		'keydown' : function () {
			var self = $(this);
			if(self.val().length > 100){
				self.val(self.val().substring(0,100)); 
			}
		}
	});

	function checkPhone(phoneNum) {		
        phoneNum = phoneNum == '请输入您的手机号码' ? '':phoneNum ;
		phoneNum ? phoneMsgCon.text('手机格式错误！') : phoneMsgCon.text('手机号码不能为空！');
		if (XF.Validate.phoneMobile(phoneNum)){
            phoneInt.removeClass('int-err');
            phoneMsg.hide();
            pregflagPhone = true;
        } else {
            phoneInt.addClass('int-err');
            phoneMsg.show();
            pregflagPhone = false;
        }
	}
	intentSubmit.on('click', function () {
		var areaVal = areaInt.val(),
    		phoneVal = $.trim(phoneInt.val()),
    		textAreaVal = $.trim(textArea.val()),
            kft_type = $.trim($('input[name=way]').val());

		checkPhone(phoneVal);

		if (pregflagPhone) {
			var intentData = {
				region_id  : (areaVal ? areaVal : 0),
				phone      : phoneVal, 
				content    : (textAreaVal == '请输入您想去的楼盘或其它信息')?'':textAreaVal,
                kft_type   : kft_type
			};
			/*send ajax*/
			$.post(__base_url + "/aifang/web/kft/ajax/feedback/", intentData,
				function (data) {
                    modalIntent.close();
					if (data.status == 0) {//成功
						modalIntentStatus.open();
	                } else {//失败
                        modalIntentStatusErr.open();
					}
			}, 'json');
		}
	});
	/*置顶交互*/
	var gotop = $('#j-site-gotop'), btnGotop = gotop.find('.btn-gotop');
	btnGotop.on('click.gotop', function () {
		$('html,body').animate({scrollTop: 0}, 400);
	});
	function checkGotop() {
		var scrTop = $(window).scrollTop(),
			show_pos = $('#j-triggerlayer-b').length > 0 ?$('#j-triggerlayer-b').offset().top : 0;
		if(scrTop > show_pos){
			 btnGotop.css({visibility: 'visible'}); 
			 $('.sweepQR').show();
		}else{
			btnGotop.css({visibility: 'hidden'}); 
			$('.sweepQR').hide();
		}
	}

	checkGotop();
	$(window).on('scroll.gotop', function () {
		checkGotop();
	});
})(jQuery);
(function ($) {
    // 意见反馈点击跳转
    $('#j-feedback').on('click.feedback',function() {
        var feedbackUrl = $.trim($(this).data('url'));
        feedbackUrl && XF.WindowsOpen.redirect(feedbackUrl);
    });
    var odbox       = $('.conbox').not('.consult');
    var conbox      = $('.conbox').filter('.consult');
    var favoredbox  = $('.conbox').filter('.favored');
    var container   = $('.phoneBanner');
    var bannerbox   = $('.phoneBanner>div');
    var fatherWidth = container.width();
    var innerWidth  = bannerbox.width();
    var outerWidth  = bannerbox.outerWidth();
    container.hide();
    bannerbox.css('width',innerWidth).removeClass('static');
    odbox.on('mouseenter mouseleave',function(){
        $(this).toggleClass('light');
    });
    conbox.on({
        mouseenter:function(){
            $(this).addClass('highlight');
            container.show();
            bannerbox.stop().animate({left:fatherWidth-outerWidth+'px'},500);
        }
        ,mouseleave:function(){
            $(this).removeClass('highlight');
            bannerbox.stop().animate({left:fatherWidth},500,function(){container.hide();});

        }
    });
})(jQuery);/*
    json2.js
    2015-02-25

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 
                        ? '0' + n 
                        : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint 
    eval, for, this 
*/

/*property
    JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (typeof JSON !== 'object') {
    JSON = {};
}

(function () {
    'use strict';

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 
        ? '0' + n 
        : n;
    }
    
    function this_value() {
        return this.valueOf();
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function () {

            return isFinite(this.valueOf())
            ? this.getUTCFullYear() + '-' +
                    f(this.getUTCMonth() + 1) + '-' +
                    f(this.getUTCDate()) + 'T' +
                    f(this.getUTCHours()) + ':' +
                    f(this.getUTCMinutes()) + ':' +
                    f(this.getUTCSeconds()) + 'Z'
            : null;
        };

        Boolean.prototype.toJSON = this_value;
        Number.prototype.toJSON = this_value;
        String.prototype.toJSON = this_value;
    }

    var cx,
        escapable,
        gap,
        indent,
        meta,
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) 
        ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string'
            ? c
            : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' 
        : '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) 
            ? String(value) 
            : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0
                ? '[]'
                : gap
                ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
                : '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === 'string') {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (
                                gap 
                                ? ': ' 
                                : ':'
                            ) + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (
                                gap 
                                ? ': ' 
                                : ':'
                            ) + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0
            ? '{}'
            : gap
            ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
            : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        };
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (
                /^[\],:{}\s]*$/.test(
                    text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, '')
                )
            ) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function'
                ? walk({'': j}, '')
                : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());
/**
 *     __  ___
 *    /  |/  /___   _____ _____ ___   ____   ____ _ ___   _____
 *   / /|_/ // _ \ / ___// ___// _ \ / __ \ / __ `// _ \ / ___/
 *  / /  / //  __/(__  )(__  )/  __// / / // /_/ //  __// /
 * /_/  /_/ \___//____//____/ \___//_/ /_/ \__, / \___//_/
 *                                        /____/
 *
 * @description MessengerJS, a common cross-document communicate solution.
 * @author biqing kwok
 * @version 2.0
 * @license release under MIT license
 */

window.Messenger = (function(){

    // 消息前缀, 建议使用自己的项目名, 避免多项目之间的冲突
    // !注意 消息前缀应使用字符串类型
    var prefix = "[PROJECT_NAME]",
        supportPostMessage = 'postMessage' in window;

    // Target 类, 消息对象
    function Target(target, name, prefix){
        var errMsg = '';
        if(arguments.length < 2){
            errMsg = 'target error - target and name are both required';
        } else if (typeof target != 'object'){
            errMsg = 'target error - target itself must be window object';
        } else if (typeof name != 'string'){
            errMsg = 'target error - target name must be string type';
        }
        if(errMsg){
            throw new Error(errMsg);
        }
        this.target = target;
        this.name = name;
        this.prefix = prefix;
    }

    // 往 target 发送消息, 出于安全考虑, 发送消息会带上前缀
    if ( supportPostMessage ){
        // IE8+ 以及现代浏览器支持
        Target.prototype.send = function(msg){
            this.target.postMessage(this.prefix + '|' + this.name + '__Messenger__' + msg, '*');
        };
    } else {
        // 兼容IE 6/7
        Target.prototype.send = function(msg){
            var targetFunc = window.navigator[this.prefix + this.name];
            if ( typeof targetFunc == 'function' ) {
                targetFunc(this.prefix + '|' + this.name + '__Messenger__' + msg, window);
            } else {
                throw new Error("target callback function is not defined");
            }
        };
    }

    // 信使类
    // 创建Messenger实例时指定, 必须指定Messenger的名字, (可选)指定项目名, 以避免Mashup类应用中的冲突
    // !注意: 父子页面中projectName必须保持一致, 否则无法匹配
    function Messenger(messengerName, projectName){
        this.targets = {};
        this.name = messengerName;
        this.listenFunc = [];
        this.prefix = projectName || prefix;
        this.initListen();
    }

    // 添加一个消息对象
    Messenger.prototype.addTarget = function(target, name){
        var targetObj = new Target(target, name,  this.prefix);
        this.targets[name] = targetObj;
    };

    // 初始化消息监听
    Messenger.prototype.initListen = function(){
        var self = this;
        var generalCallback = function(msg){
            if(typeof msg == 'object' && msg.data){
                msg = msg.data;
            }

            // 防止其他postMessage方法向内部传递消息引发错误
            if ( !msg.split ) {
                return false;
            }

            var msgPairs = msg.split('__Messenger__');
            var msg = msgPairs[1];
            var pairs = msgPairs[0].split('|');
            var prefix = pairs[0];
            var name = pairs[1];


            for(var i = 0; i < self.listenFunc.length; i++){

                if (prefix + name === self.prefix + self.name) {
                    self.listenFunc[i](msg);
                }
            }
        };

        if ( supportPostMessage ){
            if ( 'addEventListener' in document ) {
                window.addEventListener('message', generalCallback, false);
            } else if ( 'attachEvent' in document ) {
                window.attachEvent('onmessage', generalCallback);
            }
        } else {
            // 兼容IE 6/7
            window.navigator[this.prefix + this.name] = generalCallback;
        }
    };

    // 监听消息
    Messenger.prototype.listen = function(callback){
        var i = 0;
        var len = this.listenFunc.length;
        var cbIsExist = false;
        for (; i < len; i++) {
            if (this.listenFunc[i] == callback) {
                cbIsExist = true;
                break;
            }
        }
        if (!cbIsExist) {
            this.listenFunc.push(callback);
        }
    };
    // 注销监听
    Messenger.prototype.clear = function(){
        this.listenFunc = [];
    };
    // 广播消息
    Messenger.prototype.send = function(msg){
        var targets = this.targets,
            target;
        for(target in targets){
            if(targets.hasOwnProperty(target)){
                targets[target].send(msg);
            }
        }
    };

    return Messenger;
})();/**
* 用户中心登录控件
* 后端文档 : http://gitlab.corp.anjuke.com/_site/docs/blob/master/API/%E7%94%A8%E6%88%B7%E4%B8%AD%E5%BF%83/%E6%96%B0%E7%89%88%E7%94%A8%E6%88%B7%E4%B8%AD%E5%BF%83%E6%8E%A5%E5%8F%A3.md
* 前端文档 : http://gitlab.corp.anjuke.com/yaohuiwang/iframelogin-js/tree/master
* created by yaohuiwang@anjuke.com 17-02-21
*/
;(function($) {
    var _IframeLogin = function(op) {
        var defaults = {
            redirectTime: 1000,
            iframeLoginMaskId: "", // 组件的id[可选]
            ifm: null
        };
        this.ops = $.extend(defaults, op);
        this.$parentNode = $("#" + this.ops.iframeLoginMaskId);
        this.iframeLoginMask = this.$parentNode;
        this.ifm = $(this.ops.ifm || this.$parentNode.find(".iframe-login-ifm"));
        this.iframeLoading = this.$parentNode.find(".loading-wrap");
        this.iframeLoginWrap = this.$parentNode.find(".iframe-login-wrap");
        this.isInlayer = !this.iframeLoginMask.hasClass("not-in-layer");    // 是否处于弹层中（默认隐藏，手动弹出）
        this._initOuterMsger();
    }

    // 初始化外层messenger
    _IframeLogin.prototype._initOuterMsger = function() {
        var self = this;

        if (!self.outerMsger) {
            self.outerMsger = new Messenger("parent", "login");
            self.outerMsger.listen(function(msg) {
                self._handleReceive(msg);
            });
        }
        if (self.outerMsgerInited) {
            return;
        }
        var ifm = self.ifm[0];
        if (!ifm) {
            self.ifm = self.ops.ifm || self.$parentNode.find(".iframe-login-ifm");
            ifm = self.ifm[0];
        }
        if(ifm && ifm.contentWindow) {
            self.outerMsger.addTarget( ifm.contentWindow, "iframe" );
            self.outerMsgerInited = true;
        }
    }

    // 向内层发送消息（只能是{}）
    _IframeLogin.prototype._send = function(msg) {
        this.outerMsger.send( JSON.stringify(msg) );
    }

    // 接收到内层传来的消息@msg（字符串）
    _IframeLogin.prototype._handleReceive = function(msg) {
        this._initOuterMsger(); // iframe为动态载入时需要重新建立通信
        var msgObj = JSON.parse(msg);

        // 登录成功
        if (msgObj.name === "showSuccess") {
            this.showSuccess(msgObj);
        }

        // iframe加载完成
        if (msgObj.name === "logincontentLoaded") {
            if (self.oncontentLoaded) {
                self.oncontentLoaded();
            }
            this._toggleIfmLoading(false);
        }

        // 关闭弹层
        if (msgObj.name === "close") {
            if (self.onclose) {
                var result = self.onclose();
                if (result === false) {
                    return;
                }
            }
            this.close();
        }
    }

    // iframe loading状态的控制。@b : true / false
    _IframeLogin.prototype._toggleIfmLoading = function(b) {
        if (b) { // 显示loading
            this.ifm.addClass("none");
            this.iframeLoading.removeClass("none");
        } else { // 隐藏loading
            this.iframeLoading.addClass("none");
            this.ifm.removeClass("none");
        }
    }

    // 重置登录表单
    _IframeLogin.prototype.reset = function(args) {
        this._send({
            name : "reset",
            args : args
        });
    }

    // 打开登录弹层
    _IframeLogin.prototype.open = function() {
        var self = this;
        if (this.isInlayer) {
            // this.refresh();
            self.iframeLoginMask.addClass("iframelogin-layer-mask-show");
        }

        // 轮询检测是否在其他页面登录
        var timer = setTimeout(function checkLogged() {
            if (document.cookie.indexOf("aQQ_ajkauthinfos") !== -1) { // 已登录
                clearTimeout(timer);
                self.showSuccess();
            } else { // 尚未登录
                setTimeout(checkLogged, 500);
            }
        }, 500);

        this._send({
            name : "soj",
            args : "track_login_phonetc"
        });

        return self;
    }

    // 关闭登录弹层
    _IframeLogin.prototype.close = function() {
        if (this.isInlayer) {
            this.iframeLoginMask.removeClass("iframelogin-layer-mask-show");
        }
        return this;
    }

    _IframeLogin.prototype.refresh = function() {
        var originSrc = this.ifm.attr("src");
        var newSrc;
        if (!originSrc) {
            return;
        }
        if ( originSrc.indexOf("t=") === -1 ) {
            if (originSrc.indexOf("?") === -1) {
                newSrc = originSrc + "?t=" + (+new Date());
            } else {
                newSrc = originSrc + "&t=" + (+new Date());
            }
        } else {
            newSrc = originSrc.replace(/t\=[\d]+/, "t=" + (+new Date()));
        }
        this.ifm.attr("src", newSrc);
        return this;
    }

    // 显示登录成功.在弹层中：显示成功，关闭弹层，自动刷新;没在弹层中，显示成功，自动跳转
    _IframeLogin.prototype.showSuccess = function(msgObj) {
        var self = this;
        if ( self.loggedin ) { // 避免多次触发登录成功之后的逻辑
            return;
        }
        self.loggedin = true;
        var result = {
            autoShowSuccess : true,
            autoReload : true,
            autoClose : true
        }

        if (self.ops.onloginSuccess) {
            result = self.ops.onloginSuccess(msgObj) || result;
        }

        // 通知内层，显示登录成功
        if ( result && result.autoShowSuccess && result.autoShowSuccess !== false ) {
            var successObj = {
                name : "showSuccess"
            }
            if (self.successStyle) {
                successObj.successStyle = self.successStyle
            }
            this._send(successObj);
        }

        if (this.isInlayer) { // 弹层中
            setTimeout(function() {
                if ( result && result.autoClose &&  result.autoClose !== false ) {
                    self.close();
                }
            }, this.ops.redirectTime);
        } else { // 内联
            setTimeout(function() {
                if (msgObj && msgObj.history && result && result.autoReload && result.autoReload !== false ) {
                    location.href = msgObj.history;
                }
            }, this.ops.redirectTime);
        }

        return self;
    }

    // 自定义成功之后的样式
    _IframeLogin.prototype.setSuccessStyle = function(str) {
        this.successStyle = str;
        return this;
    }

    window.IframeLoginClass = window.IframeLoginClass || _IframeLogin;
})(jQuery);/**
* 用户中心绑定手机控件
* 后端文档 : http://gitlab.corp.anjuke.com/_site/docs/blob/master/API/%E7%94%A8%E6%88%B7%E4%B8%AD%E5%BF%83/%E6%96%B0%E7%89%88%E7%94%A8%E6%88%B7%E4%B8%AD%E5%BF%83%E6%8E%A5%E5%8F%A3.md
* 前端文档 : http://gitlab.corp.anjuke.com/yaohuiwang/iframelogin-js/tree/master
* created by yaohuiwang@anjuke.com 17-02-21
*/
;(function($) {
    var _IframeBindPhone = function(op) {
        var defaults = {
            redirectTime: 1000,
            iframeMaskId: "", // 组件的id[可选]
            ifm: null
        };
        this.ops = $.extend(defaults, op);
        this.$parentNode = $("#" + this.ops.iframeMaskId);
        this.ifm = $(this.ops.ifm || this.$parentNode.find(".iframe-login-ifm"));
        this.iframeLoading = this.$parentNode.find(".loading-wrap");
        this.iframeBindPhoneMask = this.$parentNode;
        this.iframeBindPhoneWrap = this.$parentNode.find(".iframe-login-wrap");
        this.isInlayer = !this.iframeBindPhoneMask.hasClass("not-in-layer");
        this._initOuterMsger();
    }

    // 初始化外层messenger
    _IframeBindPhone.prototype._initOuterMsger = function() {
        var self = this;
        if (self.outerMsgerInited) {
            return;
        }
        if (!self.outerMsger) {
            self.outerMsger = new Messenger("parent", "login");
        }
        var ifm = self.ifm[0];
        if (!ifm) {
            self.ifm = self.ops.ifm || self.$parentNode.find(".iframe-login-ifm");
            ifm = self.ifm[0];
        }
        if(ifm && ifm.contentWindow) {
            self.outerMsger.addTarget( ifm.contentWindow, "iframe" );
            self.outerMsgerInited = true;
            self.outerMsger.listen(function(msg) {
                self._handleReceive(msg);
            });
        }
    }

    // 向内层发送消息（只能是{}）
    _IframeBindPhone.prototype._send = function(msg) {
        this.outerMsger.send( JSON.stringify(msg) );
    }

    // 接收到内层传来的消息@msg（字符串）
    _IframeBindPhone.prototype._handleReceive = function(msg) {
        this._initOuterMsger(); // iframe为动态载入时需要重新建立通信
        var msgObj = JSON.parse(msg);

        // 登录成功
        if (msgObj.name === "showBindPhoneSuccess") {
            this.showSuccess(msgObj);
        }

        // iframe加载完成
        if (msgObj.name === "bindphonecontentLoaded") {
            if (self.oncontentLoaded) {
                self.oncontentLoaded();
            }
            this._toggleIfmLoading(false);
        }

        // 关闭弹层
        if (msgObj.name === "close") {
            if (self.onclose) {
                var result = self.onclose();
                if (result === false) {
                    return;
                }
            }
            this.close();
        }
    }

    // iframe loading状态的控制。@b : true / false
    _IframeBindPhone.prototype._toggleIfmLoading = function(b) {
        if (b) { // 显示loading
            this.ifm.addClass("none");
            this.iframeLoading.removeClass("none");
        } else { // 隐藏loading
            this.iframeLoading.addClass("none");
            this.ifm.removeClass("none");
        }
    }

    // 重置登录表单
    _IframeBindPhone.prototype.reset = function(args) {
        this._send({
            name : "reset",
            args : args
        });
    }

    // 打开登录弹层
    _IframeBindPhone.prototype.open = function() {
        var self = this;
        if (this.isInlayer) {
            this.iframeBindPhoneMask.addClass("iframebindphone-layer-mask-show");
            this.refresh();
        }

        return self;
    }

    // 关闭登录弹层
    _IframeBindPhone.prototype.close = function() {
        if (this.isInlayer) {
            this.iframeBindPhoneMask.removeClass("iframebindphone-layer-mask-show");
        }
    }

    _IframeBindPhone.prototype.refresh = function() {
        var originSrc = this.ifm.attr("src");
        var newSrc;
        if ( originSrc.indexOf("t=") === -1 ) {
            if (originSrc.indexOf("?") === -1) {
                newSrc = originSrc + "?t=" + (+new Date());
            } else {
                newSrc = originSrc + "&t=" + (+new Date());
            }
        } else {
            newSrc = originSrc.replace(/t\=[\d]+/, "t=" + (+new Date()));
        }
        this.ifm.attr("src", newSrc);
        return this;
    }

    // 显示登录成功.在弹层中：显示成功，关闭弹层，自动刷新;没在弹层中，显示成功，自动跳转
    _IframeBindPhone.prototype.showSuccess = function(msgObj) {
        var self = this;

        // 自定义了success
        if (self.ops.onbindPhoneSuccess) {
            var result = self.ops.onbindPhoneSuccess(msgObj);
            if (result === false) {
                return;
            }
        }

        // 通知内层，显示登录成功
        var successObj = {
            name : "showSuccess"
        }
        if (this.successStyle) {
            successObj.successStyle = this.successStyle
        }
        this._send(successObj);

        if (this.isInlayer) { // 弹层中
            setTimeout(function() {
                self.close();
            }, this.ops.redirectTime);
        } else { // 内联
            setTimeout(function() {
                if (msgObj && msgObj.history) {
                    location.href = msgObj.history;
                }
            }, this.ops.redirectTime);
        }

        return this;
    }

    // 自定义成功之后的样式
    _IframeBindPhone.prototype.setSuccessStyle = function(str) {
        this.successStyle = str;
        return this;
    }

    window.IframeBindPhoneClass = window.IframeBindPhoneClass || _IframeBindPhone;
})(jQuery);;
/*
*share template
*support IE6/7
*Syntax:
* <%= %> <%~ %> <%  %>
*Usage:
* XF.Tool.tpl.template(tplTxt)(data)
*/
(function(tool) {
    var _ = {}
    // Is a given variable an object?
    _.isObject = function(obj) {
      var type = typeof obj;
      return type === 'function' || type === 'object' && !!obj;
    };
    _.isFunction = function(obj) {
      return typeof obj == 'function' || false;
    };


    // Shortcut function for checking if an object has a given property directly
    // on itself (in other words, not on a prototype).
    _.has = function(obj, key) {
      return obj != null && Object.prototype.hasOwnProperty.call(obj, key);
    };

    //兼容不支持Object.keys的环境
    if (!Object.keys) {
      Object.keys = (function () {
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
            dontEnums = [
              'toString',
              'toLocaleString',
              'valueOf',
              'hasOwnProperty',
              'isPrototypeOf',
              'propertyIsEnumerable',
              'constructor'
            ],
            dontEnumsLength = dontEnums.length;

        return function (obj) {
          if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

          var result = [];

          for (var prop in obj) {
            if (hasOwnProperty.call(obj, prop)) result.push(prop);
          }

          if (hasDontEnumBug) {
            for (var i=0; i < dontEnumsLength; i++) {
              if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
            }
          }
          return result;
        }
      })()
    };
    // Retrieve all the property names of an object.
    _.allKeys = function(obj) {
      if (!_.isObject(obj)) return [];
      return Object.keys(obj);
      // if (Object.keys) return Object.keys(obj);
      // var keys = [];
      // for (var key in obj) keys.push(key);
      // Ahem, IE < 9.
      // if (hasEnumBug) collectNonEnumProps(obj, keys);
      // return keys;
    };
    // Retrieve the names of an object's own properties.
    // Delegates to **ECMAScript 5**'s native `Object.keys`.
    _.keys = function(obj) {
      if (!_.isObject(obj)) return [];
      return Object.keys(obj);
      // if (Object.keys) return Object.keys(obj);
      // var keys = [];
      // for (var key in obj) if (_.has(obj, key)) keys.push(key);
      // Ahem, IE < 9.
      // if (hasEnumBug) collectNonEnumProps(obj, keys);
      // return keys;
    };

    // An internal function for creating assigner functions.
    var createAssigner = function(keysFunc, defaults) {
        return function(obj) {
            var length = arguments.length;
            if (defaults) obj = Object(obj);
            if (length < 2 || obj == null) return obj;
            for (var index = 1; index < length; index++) {
                var source = arguments[index],
                    keys = keysFunc(source),
                    l = keys.length;
                for (var i = 0; i < l; i++) {
                    var key = keys[i];
                    if (!defaults || obj[key] === void 0) obj[key] = source[key];
                }
            }
            return obj;
        };
    };
    // Fill in a given object with default properties.
    _.defaults = createAssigner(_.allKeys, true);
    // List of HTML entities for escaping.
    var escapeMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;',
        '`': '&#x60;'
    };
    // Functions for escaping and unescaping strings to/from HTML interpolation.
    var createEscaper = function(map) {
        var escaper = function(match) {
            return map[match];
        };
        // Regexes for identifying a key that needs to be escaped.
        var source = '(?:' + _.keys(map).join('|') + ')';
        var testRegexp = RegExp(source);
        var replaceRegexp = RegExp(source, 'g');
        return function(string) {
            string = string == null ? '' : '' + string;
            return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
        };
    };
    _.escape = createEscaper(escapeMap);
    // By default, Underscore uses ERB-style template delimiters, change the
    // following template settings to use alternative delimiters.
    var templateSettings = {
        evaluate: /<%([\s\S]+?)%>/g,
        interpolate: /<%=([\s\S]+?)%>/g,
        escape: /<%-([\s\S]+?)%>/g
    };

    // When customizing `templateSettings`, if you don't want to define an
    // interpolation, evaluation or escaping regex, we need one that is
    // guaranteed not to match.
    var noMatch = /(.)^/;

    // Certain characters need to be escaped so that they can be put into a
    // string literal.
    var escapes = {
        "'": "'",
        '\\': '\\',
        '\r': 'r',
        '\n': 'n',
        '\u2028': 'u2028',
        '\u2029': 'u2029'
    };

    var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;

    var escapeChar = function(match) {
        return '\\' + escapes[match];
    };

    // JavaScript micro-templating, similar to John Resig's implementation.
    // Underscore templating handles arbitrary delimiters, preserves whitespace,
    // and correctly escapes quotes within interpolated code.
    // NB: `oldSettings` only exists for backwards compatibility.
    _.template = function(text, settings, oldSettings) {
        if (!settings && oldSettings) settings = oldSettings;
        settings = _.defaults({}, settings, templateSettings);

        // Combine delimiters into one regular expression via alternation.
        var matcher = RegExp([
            (settings.escape || noMatch).source,
            (settings.interpolate || noMatch).source,
            (settings.evaluate || noMatch).source
        ].join('|') + '|$', 'g');

        // Compile the template source, escaping string literals appropriately.
        var index = 0;
        var source = "__p+='";
        text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
            source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
            index = offset + match.length;

            if (escape) {
                source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
            } else if (interpolate) {
                source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
            } else if (evaluate) {
                source += "';\n" + evaluate + "\n__p+='";
            }

            // Adobe VMs need the match returned to produce the correct offset.
            return match;
        });
        source += "';\n";

        // If a variable is not specified, place data values in local scope.
        if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

        source = "var __t,__p='',__j=Array.prototype.join," +
            "print=function(){__p+=__j.call(arguments,'');};\n" +
            source + 'return __p;\n';

        var render;
        try {
            render = new Function(settings.variable || 'obj', '_', source);
        } catch (e) {
            e.source = source;
            throw e;
        }

        var template = function(data) {
            return render.call(this, data, _);
        };

        // Provide the compiled source as a convenience for precompilation.
        var argument = settings.variable || 'obj';
        template.source = 'function(' + argument + '){\n' + source + '}';

        return template;
    };

    var tt = XF.nameSpace('XF.Tool');
    tt.tpl= _ ;
})();
/**
 * 统一登录所支持的弹窗type
 */
XF.nameSpace('XF.User');
;(function ($,ns) {
    ns.PA_TYPE = {
        BOOKINGCALL:'bookingcall',//预约回电
        SUBSCRIBE:'subscribe',//订阅
        ONEKEYSUBSCRIBE:'onekeysubscribe'//订阅
    }
})(jQuery, XF.User);/**
 * 申请业务处理逻辑，负责所有申请逻辑处理，提供标准api
 * 负责模块 tuangou, applycheck, applycar, applygroup, subscribe, appoint
 */
XF.nameSpace('XF.User');
;(function($, ns, vars, XF) {

    function getSojObj(name) {
        var conf = {Page: "", PageName : ""};
        var obj = vars[name] || (name == "default" ?  XF.Soj.param : vars['sojData']);
        if(obj && obj.p && obj.pn) {
            conf = $.extend({}, conf, {
                Page : obj.p,
                PageName : obj.pn || obj.p
            });
        } else {
            conf = $.extend({}, conf, XF.Soj.param);
            conf.PageName = conf.PageName || conf.Page;
        }
        return conf;
    }

    /**
     * tapSoj 触碰时
     * @type {Object}
     */
    function getConfig(type) {
        var rs;
        var config = {
            appoint : {
                sojObj : "default",
                def : {
                    tap : "loupan_index_first_yykf",
                    apply : "loupan_detail_dingyue_mould_yuyuekanfang"
                }
            },
            subscribe : {
                sojObj : "sojData",
                def : {
                    tap : "loupan_detail_dingyue",
                    apply : "loupan_detail_dingyue_mould"
                }
            },
            applygroup : {
                sojObj : "groupsojData",
                def : {
                    tap : 'zc_lpdetail',
                    apply : 'click_loupan_index_activity_group_sign'
                },
                Aifang_Web_Kft_LookgroupPage : {
                    tap : 'undefined',
                    apply : 'click_xianlu_kft_list_group_sign'
                },
                Aifang_Web_Kft_CarListPage : {
                    tap : 'undefined',
                    apply : 'click_zhuanche_kft_list_group_sign'
                }
            },
            applycar : {
                sojObj : "sojData",
                def : {
                    tap : 'zc_lpdetail',
                    apply : 'zc_list_mould'
                },
                Aifang_Web_Kft_CarViewPage : {
                    tap : 'zc_detail'

                },
                Aifang_Web_Kft_CarListPage : {
                    tap : 'zc_list'
                }
            },
            tuangou : {
                sojObj : "sojData",
                applySojObjExt: "_confirm_discount",
                def : {}
            },
            applycheck : {
                sojObj : "sojData",
                def : {
                    apply : 'click_loupan_tab_kft_mould'
                },
                Aifang_Web_Loupan_View2_Index : {
                    apply : "click_loupan_index_activity_xian"
                },
                Aifang_Web_Kft_ViewPage : {
                    apply : 'danye'
                },
                Aifang_Web_Kft_LookgroupPage : {
                    apply :'kftlist_submit'
                }
            },
            similarloupan : {
                sojObj : "sojData",
                def : {}
            }

        };
        if(rs = config[type])  {
            rs.sojObj = getSojObj(rs.sojObj);
            if(rs.applySojObjExt) {
                rs.applySojObj = {};
                $.each(rs.sojObj, function(k, v) {
                    rs.applySojObj[k] = v + rs.applySojObjExt;
                })
            }
        }
        return rs;
    }

    /*
     * 发码器
     * @param type 类型
     * @param soj 标签上的soj
     * @param isApply是否是apply状态
     */
    function send(type, soj, isApply) {
        var conf = getConfig(type);
        if(!conf) {
            return;
        }
        var sojObj = conf.sojObj;
        if(isApply) {
            sojObj = conf.applySojObj || conf.sojObj;
        }
        if(isApply) {
            soj = soj || conf.def.apply;
        } else {
            soj = soj || conf.def.tap;
        }
        $.each(conf, function(k, v) {
            if(k == "sojObj" || k == "applySojObjExt" || k == "def" || k == "applySojObj") {
                return;
            }
            if(k == sojObj.Page) {
                soj = (isApply ? v.apply : v.tap) || soj;
            }
        });
        XF.Soj.send("{from : "+soj+"}", sojObj);
    }

    ns.Soj = {
        send : send
    };

})(jQuery, XF.User, XF.Vars, XF);/**
 * 申请业务处理逻辑，负责所有申请逻辑处理，提供标准api
 * 负责模块 tuangou, applycheck, applycar, applygroup, subscribe, appoint
 */
XF.nameSpace('XF.User');;
(function($, ns) {

    var PA_TYPE = ns.PA_TYPE;

    function Apply(params) {
        this.ajaxUrl = "";
        this.userPhone = "";
    }

    Apply.prototype = {
        constructor: Apply,
        setAjaxUrl: function(url) {
            this.ajaxUrl = url;
            return this;
        },
        /**
         * 数据提交
         */
        ajax: function(params, cb) {
            var that = this;
            cb = typeof cb == "function" ? cb : function() {};
            $.ajax({
                url: this.ajaxUrl,
                method: "post",
                dataType: "json",
                data: params,
                success: function(rs) {
                    cb(null, rs);
                },
                error: function(err) {
                    cb(err);
                }
            });
        },
        tuangou: function(params, cb) { //获取优惠
            var rs = {
                subscribe_type: "tuangou",
                tid: params.tid,
                loupan_id: params.loupan_id,
                tuangou: params.tuangou,
                tuantype:params.tuanType,
                join_kft: params.join_kft || 0,
                line_id: params.line_id || 0,
                kft_join_id: params.kft_join_id || 0,
                kft_type: params.kft_type || 0,
                bind_id: params.bind_id || 0,
                channel: params.channel || 1,
                check:params.check || 0,
                authorize_status: params.authorize_status || 0
            };
            this.ajax(rs, cb);
        },
        applycheck: function(params, cb) { //看房团
            var rs = {
                subscribe_type: "applycheck",
                num: 1,
                name: "",
                line_id: params.line_id,
                apply_source: params.apply_source,
                tuangou_id: params.tuangou_id || 0,
                channel: params.channel || 1,
                check:params.check || 0,
                authorize_status: params.authorize_status || 0
            };
            this.ajax(rs, cb);
        },
        applycar: function(params, cb) { //专车看房
            var rs = {
                subscribe_type: "applycar",
                name: "",
                from_module: params.from_module,
                zhuanche_id: params.zhuanche_id,
                channel: params.channel || 1,
                check:params.check || 0
            };
            this.ajax(rs, cb);
        },
        applygroup: function(params, cb) { //组团看房
            var rs = {
                subscribe_type: "applygroup",
                num: 1,
                name: "",
                loupan_name: params.loupan_name,
                groupSign_id: params.gid,
                apply_source: params.apply_source,
                channel: params.channel || 1,
                check:params.check || 0
            };
            this.ajax(rs, cb);
        },
        subscribe: function(params, cb) { //订阅
            var rs = {
                subscribe_type: "subscribe",
                source_id: params.loupanId,
                sub_from: params.subFrom,
                category: params.category.join("|"),
                check:params.check || 0
            };
            this.ajax(rs, cb);
        },
        appoint: function(params, cb) { //预约看房
            var rs = {
                subscribe_type: "appoint",
                loupan_id: params.loupanId,
                username: "",
                consultant_id: params.consultantId,
                type: params.type,
                channel: params.channel || 1,
                check:params.check || 0
            };
            this.ajax(rs, cb);
        },
        follow:function(params, cb){ //特惠关注
            var rs = {
                subscribe_type: "th_follow",
                source_id: params.sourceId,
            };
            this.ajax(rs, cb);
        },
    }
    Apply.prototype[PA_TYPE.BOOKINGCALL] = function(params, cb) { //订阅
        var rs = {
            subscribe_type: "subscribe",
            source_id: params.loupanId,
            sub_from: params.subFrom,
            category: params.category.join("|")
        };
        this.ajax(rs, cb);
    }

    ns.ApplyInterface = new Apply();
})(jQuery, XF.User);
Array.prototype.indexOf = function (v) {
    for (var k in this) {
        if (this[k] === v) {
            return k;
        }
    }
    return -1;
}

/**
 * 统一注册登录功能 - 统一逻辑，本次改造提供（订阅信息，看房团，领取优惠，专车看房，组团看房，售罄盘订阅相似楼盘动态，纯登陆，点评登陆，问答登陆）
 * 当用户未登录，使用手机号注册登录并立即发起申请
 * 当用户已登录，没有关联手机号，则绑定手机号并立即发起申请
 * 当用户已经登录，存在已关联手机号，则立即发起申请
 */
XF.nameSpace('XF.User');
/**
 * 注册公共属性
 */


;
(function ($, ns) {
    ns.prefix = "PhoneActivate_";
    ns.keys = {
        frameLoad: ns.prefix + "frameLoad",
        loginSuccess: ns.prefix + "loginSuccess",
        bindPhoneSuccess: ns.prefix + "bindPhoneSuccessn"
    }
    var PA_TYPE = ns.PA_TYPE;
    /**
     * getBaseConfig
     * @param {string} type 分类
     * @return {object} 对应类型下的配置
     */
    function getBaseConfig(type) {
        var oneKeySubMainhead = $('.user-one-key-sub-hint--des').html();
        var bookCallMainhead = $('.user-booking-call-hint--des').html();
        var newSubHead = $('.user-booking-call-hint--tip').html();
        var config = {
            subscribe: ["subscribe", "立即订阅", "一键订阅", "订阅成功", "楼盘最新动态信息，将第一时间以短信方式通知到您", "订阅楼盘信息，及时以短信方式通知到您", '确认', ''],
            zhuanche: ["applycar", "立即开启", "专车看房", "报名成功", "感谢您的参与，我们会尽快联系您安排行程", "随时免费专车看房，我们会尽快联系您安排行程", '确认', ''],
            zutuan: ["applygroup", "报名组团", "组团看房", "报名成功", "感谢您的参与，稍后获取优惠短信会发送至您的手机", "", '确认', ''],
            kanfang: ["applycheck", "免费报名", "优惠活动", "报名成功", "登录后即可参与活动，开发商将收集你的电话号码并安排顾问致电为你提供专属服务", "报名成功后，开发商将收集你的电话号码并安排顾问致电为你提供专属服务", '确认报名', '我再想想'],
            youhui: ["tuangou", "确认领取", "优惠活动", "领取成功", "登录后即可参与活动，开发商将收集你的电话号码并安排顾问致电为你提供专属服务", "领取成功后，开发商将收集你的电话号码并安排顾问致电为你提供专属服务", '确认领取', '我再想想'],
            yuyuekanfang: ["appoint", "立即预约", "预约看房", "预约成功", "请保持手机畅通，您的专属置业顾问将很快与您联系。", "", '确认', ''],
            yuyueguwen: ["appoint", "立即预约", "预约看房", "预约成功", "请保持手机畅通，您的专属置业顾问将很快与您联系", "预约置业顾问看房，为您提供专业带看服务", '确认', ''],
            similarloupan: ["similarloupan", "立即订阅", "订阅相似楼盘动态", "订阅成功", "", "订阅楼盘信息，及时以短信方式通知到您", '确认', ''],
            signup: ['tuangou', '确认报名', '优惠活动', '报名成功', '登录后即可参与活动，开发商将收集你的电话号码并安排顾问致电为你提供专属服务。', '报名成功后，开发商将收集你的电话号码并安排顾问致电为你提供专属服务', '确认报名', '我再想想'],
            signuser: ['signuser', '立即登录', '立即登录', ],
            wenda: ["wenda", "确定", "参与楼盘问答", "提交成功", "小编在快马加鞭审核您的回答", ""],
            ugc: ["ugc", "确定", "点评楼盘", "点评成功", "审核通过将获取相应经验值", ""],
            market: ['market', "获取优惠", "获取优惠"],
            live: ['live', '确定', '订阅开播提醒', '', '请手机验证登录后订阅提醒，您也可以登录安居客APP查看更多直播内容。'],
            house: ['house', '立即领取', '房源优惠', '领取成功', "感谢您的参与，稍后获取优惠短信会发送至您的手机", ""],
        };
        config[PA_TYPE.BOOKINGCALL] = [PA_TYPE.BOOKINGCALL, "立即预约", "预约回电", "预约成功!", "", "现在是售楼处休息时间，售楼处将会在工作时间尽快与您联系"];
        config[PA_TYPE.ONEKEYSUBSCRIBE] = ["subscribe", "立即订阅", "一键订阅", "订阅成功！", "", "订阅楼盘信息，及时以短信方式通知到您"];

        var tmp = config[type] || {};
        var result = {};
        $.each(['apiType', 'submitText', 'title', 'mainHead', 'subHead', 'confirmTip', 'confirmBtnText', 'cancelBtnText'], function (k, v) {
            result[v] = tmp[k] || "";
        });
        return result;
    }
    ns.GetBaseConfig = getBaseConfig;

    /**
     * double click switcher
     */
    var doubleSwitcher = true;

    function isSwitcher() {
        if (!doubleSwitcher) {
            return false;
        }
        doubleSwitcher = false;
        setTimeout(function () {
            doubleSwitcher = true;
        }, 500);
        return true;
    }
    ns.IsSwitcher = isSwitcher;


})(jQuery, XF.User);
/**
 * 提示弹出层模块
 */
;
(function ($, ns, XF) {
    var modal = null;

    function bindModelCloseEvent() {
        $('body').on('click', function (ev) {
            var node = $(ev.target);
            if (node.hasClass('comfirm-btn')) {
                modal && modal.close();
            }
        });
    };
    bindModelCloseEvent();

    /**
     * 获得提示层函数,创建一个600x320提示弹窗
     * @param {string} title 弹窗主标题
     * @param {string} label 弹窗副标题
     * @param {string} comment 弹窗备注
     * @param {boolean} isErr 是否是错误类型弹窗
     * @return void
     */
    function hint() {
        if (!modal) {
            modal = new XF.Modal({
                modalClass: "modal-custom user-pa-hint",
                hd: '<h3 class="title"></h3>',
                bd: $("#user-apply-modal"),
                width: '540',
                height: '320'
            });
        }
        return function (title, label, comment, isErr) {
            modal.open();
            var elm = modal.op.modal,
                titleElm = elm.find(".hd .title"),
                labelElm = elm.find(".am-msg-label"),
                commentElm = elm.find(".am-msg-comment"),
                boxElm = elm.find(".am-msg-box");
            boxElm.removeClass("am-msg-middle");
            if (!comment) {
                boxElm.addClass("am-msg-middle");
            }
            titleElm.html(title || "");
            labelElm.html(label || "");
            commentElm.html(comment || "");
        }
    }
    ns.Hint = hint();
    function showToast() {
      return function (text) {
        $('.toast').html(text);
        $('.toast').show();
        setTimeout(function (params) {
          $('.toast').hide();
        }, 2000);
      }
    }
    ns.ShowToast = showToast();
})(jQuery, XF.User, XF);
/**
 * 确认弹出层模块
 */
;
(function ($, ns, XF) {
    var modal = null;

    function bindModelCloseEvent() {
        $('body').on('click', function (ev) {
            var node = $(ev.target);
            if (node.hasClass('comfirm-btn')) {
                modal && modal.close();
            }
        });
    };
    bindModelCloseEvent();

    /**
     * 获得提示层函数,创建一个600x320提示弹窗
     * @param {string} title 弹窗主标题
     * @param {string} label 弹窗副标题
     * @param {string} tip 弹窗提示确认信息
     * @param {boolean} isErr 是否是错误类型弹窗
     * @return void
     */
    function confirm() {
        if (!modal) {
            modal = new XF.Modal({
                modalClass: "modal-custom user-confirm-hint",
                hd: '<h3 class="title"></h3>',
                bd: $("#user-confrim-modal"),
                width: '540',
                height: '320'
            });
        }
        return function (title, label, tip, confirmText, cancelText, confirmCallback, cancelCallback) {
            confirmCallback = typeof confirmCallback == "function" ? confirmCallback : function () {};
            cancelCallback = typeof cancelCallback == "function" ? cancelCallback : function () {};
            modal.open();
            var elm = modal.op.modal,
                titleElm = elm.find(".hd .title"),
                labelElm = elm.find(".user-confrim-label"),
                tipElm = elm.find(".user-confrim-tips"),
                confirmElm = elm.find(".user-confrim-btn"),
                cancelElm = elm.find(".user-cancel-btn");
            titleElm.html(title || "");
            labelElm.html(label || "");
            tipElm.html(tip ? "手机号：" + tip : "");
            confirmElm.html(confirmText);
            cancelElm.html(cancelText);
            $('#user-confrim-btn').off('click').on('click', function (event) {
                event.stopPropagation();
                modal.close();
                confirmCallback();
            });
            $('#user-concel-btn').off('click').on('click', function (event) {
              event.stopPropagation();
              modal.close();
              cancelCallback(2);
            });
            $('.close').on('click', function (event) {
              event.stopPropagation();
              if (cancelText) {
                cancelCallback(3);
              }
            });
        }
    }
    ns.Confirm = confirm();
})(jQuery, XF.User, XF);

/**
 * 手机号登录/绑定手机号模型
 */
;
(function ($, ns, XF) {
    var frame = null;
    var handle = null;
    var currentType = null;
    /**
     * 手机号输入框
     * @param  {string} type     业务分类
     * @param  {string} useStatus 当前用户状态 0，未登录， 1已登录未绑定手机号， 2已登录已绑定收
     * @param  {string} src    登录或绑定地址
     * @return {object}
     */
    function phoneFrame(type, useStatus, src, params) {
        if (useStatus == 2) {
            return true;
        }
        var flag = type + "" + useStatus,
            output = $.extend({}, {
                type: type,
                params: params || false,
                userInfo: false
            });
        currentType = type;
        if (!frame || (frame.data && frame.data("flag") != flag)) {
            var construct = useStatus == 1 ? window.IframeBindPhoneClass : window.IframeLoginClass;
            var classname = useStatus == 1 ? "iframe-bind-ifm" : "";
            frame = $('<iframe data-flag="' + flag + '" class="iframe-login-ifm ' + classname + '" src="' + src + '" frameborder="0" scrolling="no"></iframe>');
            frame.on("load", function () {
                $(document).trigger(ns.keys.frameLoad);
            });
            $("body").append(frame);
            handle = new construct({
                ifm: frame,
                onloginSuccess: function (rs) {
                    output.userInfo = rs;
                    if (window.gLogin && window.gLogin.updateLogin) {
                        window.gLogin.updateLogin(); //刷新用户身份
                    }
                    if (currentType == output.type) {
                        currentType = null;
                        $(document).trigger(ns.keys.loginSuccess, [output]);
                    }
                    return false;
                },
                onbindPhoneSuccess: function (rs) {
                    output.userInfo = rs;
                    if (currentType == output.type) {
                        currentType = null;
                        $(document).trigger(ns.keys.bindPhoneSuccess, [output]);
                    }
                    return false;
                }
            });
        }
        return {
            elm: frame,
            handle: handle
        }
    }

    ns.PhoneFrame = phoneFrame;
})(jQuery, XF.User, XF);;
(function ($, ns) {
    //存储配置数据
    var configure = {
        subAjaxUrl: '', //全报名类型接口
        userCenterHost: '', //用户中心连接
        phoneBindUri: '', //绑定手机号path
        phoneLoginUri: '', //用户手机登录path
        isBindPhone: false, //是否绑定手机号
        isLogin: false, //用户是否登录
        isOpenCity: false, //是否是开通城市
        isSaleOut: false //是否是售罄
    };

    /**
     * buildiframeURi
     * @param  {string} uri    url
     * @param  {string} type 分类和种类
     * @return {string} 链接
     */
    function buildUrl(type, ext) {
        var def = {
            step_over: 1,
            style: 1,
            forms: 10,
            third_parts: '000',
            other_parts: '000',
            forget_pwd: '0',
            hidehead: 1,
            submit_text: '提交',
            submiting_text: '提交中',
            submiting_bg: '#ddd',
            agreement: '',
            agreement_doc: ''
        };
        var params = $.extend({}, def, {
            submit_text: ns.GetBaseConfig(type).submitText || "提交"
        }, ext || {});
        var tmp = [];
        $.each(params, function (k, v) {
            if (v === "") {
                return;
            }
            tmp.push(k + "=" + encodeURIComponent(v));
        });
        var uri = configure.userCenterHost + (checkUser() == 1 ? configure.phoneBindUri : configure.phoneLoginUri);
        uri += "?" + tmp.join("&");
        return uri;
    }

    /**
     * 检查用户
     * @return {integer} 0未登录，1需要绑定手机号，2已登录并且有手机号
     */
    function checkUser() {
        if (configure.isLogin !== true) {
            return 0;
        }
        if (configure.isBindPhone !== true) {
            return 1;
        }
        return 2;
    }

    var showClass = "user-pa-show";
    var applyModal = null;
    var PA_TYPE = ns.PA_TYPE;
    var confrimModal = null;




    /**
     * 获取登录模块
     * this为ns.PhoneActivate
     * @param {string} type "zutuan,zhuanche,kanfang,youhui,subscribe,yuyuekanfang,yuyueguwen,signuser(纯登录)"
     * @return {function} 登录模块
     */
    function getFrameModal(type) {
        if (!applyModal) {
            applyModal = new XF.Modal({
                modalClass: "modal-custom",
                hd: '<h3 class="title"></h3>',
                bd: $("#phone-activate"),
                width: '540',
                height: '100%'
            });
        }
        return function (params, ext) {
            applyModal.open();
            var fm = ns.PhoneFrame(type, checkUser(), buildUrl(type, ext || {}), params);
            if (fm === true) {
                return;
            }
            var modalElm = applyModal.op.modal;
            var paFrameBox = modalElm.find("#pa-iframe-box");
            var paFrame = paFrameBox.find("iframe").get(0);
            var titleElm = modalElm.find(".hd .title");
            if (fm.elm.get(0) !== paFrame) {
                modalElm.find(".loading-wrap").show();
                paFrameBox.css("visibility", "hidden");
                paFrameBox.empty().append(fm.elm);
            }
            //清理展示样式
            modalElm.find("." + showClass).removeClass(showClass);
            //设置标题
            var config = ns.GetBaseConfig(type);
            titleElm.html(config.title);
            //设置title
            if (type == "subscribe") {
                openSubscribe(params, config, modalElm);
            } else if (type == "yuyuekanfang" || type == "yuyueguwen") {
                openYuyue(params, config, modalElm);
            } else if (type == "zutuan") {
                openZutuan(params, config, modalElm);
            } else if (type == "zhuanche") {
                openZhuanche(params, config, modalElm);
            } else if (type == "youhui" || type == 'signup') {
                openYouhui(params, config, modalElm);
            } else if (type == 'house') {
                openHouse(params, config, modalElm);
            } else if (type == "kanfang") {
                openKanfang(params, config, modalElm);
            } else if (type == "similarloupan") {
                openSimilarLoupan(params, config, modalElm)
            } else if (type == PA_TYPE.BOOKINGCALL) {
                openBookingCall(params, config, modalElm)
            } else if (type == 'signuser') {
                openSignUser(applyModal);
            } else if (type == 'wenda') {
                openWenda(params, config, modalElm);
            } else if (type == 'ugc') {
                openUgc(params, config, modalElm);
            } else if (type == 'market') {
                openBrandMarket(params, config, modalElm);
            } else if (type == 'live') {
                openLive(params, config, modalElm);
            } else {
                applyModal.close();
                return;
            }
            //重置窗口
            applyModal.open();
        }
    }
    /**
     * @description: 判断是否授权
     * @param {*} target_type 授权类型，1：楼盘评测 2：户型评测 3：光照模拟 4：区域评测 1000：电话 1001：IM 1002：VR带看 1003：云聚客abc套餐领取优惠 1004：超级旗舰店优惠 1005：运营活动 1006：认筹 1007：直播 1008： 线下客户 1009：一房一价报名 1010：云聚客abc套餐报名活动 1011：万易系统 1012：预约/专车看房 1013：线路看房 1014：楼盘评测 1015：户型评测 1016：区域评测 1017：日照 1018：关注 1019:摇号积分计算
     * @param {*} target_id 业务ID，一般为楼盘id
     * @param {*} cb 回调函数，传参授权状态和是否为试点城市
     * @return {*}
     */
    function getUserAuthorization(target_type, target_id, city_id, cb) {
      $.ajax({
        url: '/xinfang/graphql/getUserAuthorizationV2/?client_source=3',
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        crossDomain: true,
        xhrFields: {
            withCredentials: true,
        },
        data: JSON.stringify({
          variables: {
            target_type,
            target_id,
            city_id
          },
        }),
        success: function (rs) {
          var user_authorization = rs.data.user_authorization;
          if (user_authorization) {
            cb(user_authorization.is_authorization, user_authorization.is_pilot_city)
          } else {
            cb(false, 0);
          }
        },
        error: function () {
          cb(false, 0);
        }
      });
    }

    /**
     * @description: 记录授权信息
     * @param {*} loupan_id 楼盘ID
     * @param {*} type_id 授权类型，1：楼盘评测  2：户型评测  3：光照模拟  4：区域评测  1003：云聚客abc套餐领取优惠 1004：超级旗舰店优惠  1005：运营活动 1006：认筹  1007：直播 1008： 线下客户  1009：一房一价报名 1010：云聚客abc套餐报名活动 1011：万易系统 1012：预约/专车看房 1013：线路看房 1014：楼盘评测 1015：户型评测 1016：区域评测  1017：日照 1018：关注 1019：摇号积分计算
     * @param {*} is_authorize 记录类型，是否授权  0 = 未授权，1 = 已授权
     * @return {*}
     */
    function recordAuthorization(loupan_id, type_id, is_authorize) {
      var params = {
        type_id,
        is_authorize
      }
      if (loupan_id) {
        params.loupan_id = loupan_id
      }
      $.ajax({
        url: 'https://usergl.fang.anjuke.com/xinfang/graphql/user/record/loginInfo/?client_source=3',
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        crossDomain: true,
        xhrFields: {
            withCredentials: true,
        },

        data: JSON.stringify({
          variables: params,
        }),
        success: function () {},
        error: function () {}
      });
    }

    //预约回电
    function openBookingCall(params, config, elm) {
        var box = elm.find('.user-pa-booking-call');
        box.addClass(showClass);
    }
    //看房团
    function openKanfang(params, config, elm) {
        var box = elm.find('.user-pa-kanfang');
        box.addClass(showClass);
        box.find(".pa-base").html(config.subHead);
    }

    //领取优惠
    function openYouhui(params, config, elm) {
        var box = elm.find('.user-pa-youhui');
        if (params.tuanType && params.tuanType != 0) {
            box.addClass('new-type');
        }
        box.addClass(showClass);
        box.find(".pa-label-sec").html(params.ext || "");
        box.find(".pa-base").html(`${config.subHead}` + (params.hk_station_url ? ` 大陆手机号请直接登录，如为港澳台手机号请点击<a href=${params.hk_station_url}>联系售楼处</a>` : ``));
        //tuantype ==1 获取优惠 ==2 立即报名，但是接口是都团购

    }

    //房源领取优惠
    function openHouse(params, config, elm) {
        var box = elm.find('.user-pa-house');
        box.addClass(showClass);
        var msg = '';
        msg = '领取' + params.discount_desc + `房源优惠。` + (params.hk_station_url ? `如您有大陆手机号，请直接登录领取，若为港澳台手机用户，请点击<a href=${params.hk_station_url}>联系售楼处</a>` : ``);
        box.find(".pa-base").html(msg);
    }
    // 主题营销
    function openBrandMarket(params, config, elm) {
        var box = elm.find('.user-pa-market');
        box.addClass(showClass);
    }

    // 预约直播
    function openLive(param, config, elm) {
        var box = elm.find('.user-pa-live');
        box.addClass(showClass);
    }

    //专车看房
    function openZhuanche(params, config, elm) {
        var box = elm.find('.user-pa-zhuanche');
        box.addClass(showClass);
        box.find(".pa-base").html(params.loupan_name);
    }

    //组团看房
    function openZutuan(params, config, elm) {
        var box = elm.find('.user-pa-zutuan')
        box.addClass(showClass);
        box.find(".pa-base").html("组团楼盘&nbsp;-&nbsp" + params.loupan_name);
    }

    //打开预约功能
    function openYuyue(params, config, elm) {
        var info = params.info;
        var mainElm = elm.find('.user-pa-book')
        mainElm.addClass(showClass);
        var pabook = elm.find(".pa-book");
        mainElm.find(".pa-label-sec").eq(0).html(params.ext || "");

        function html(icon, title, desc) {
            var html = '<div class="pa-book-row clearfix">' +
                '<div class="pa-book-one iconfont">' + icon + '</div>' +
                '<div class="pa-book-one pa-book-title">' + title + '</div>' +
                '<div class="pa-book-one">' + desc + '</div>' +
                '</div>';
            return html;
        }
        var listHtml = "",
            tmp;
        if (info) {
            $.each([
                ["&#xea8d;"],
                ["&#xea8e;"],
                ["&#xea8f;"],
                ["&#xea90;"]
            ], function (k, v) {
                if (tmp = info[k + 1]) {
                    listHtml += html(v, tmp['title'], tmp['desc']);
                }
            });
            pabook.height(54 * $(listHtml).length);
            pabook.empty().append(listHtml);
            pabook.show();
        } else {
            pabook.hide();
        }
    }

    //订阅相似楼盘动态
    function openSimilarLoupan(params, config, elm) {
        var box = elm.find('.user-pa-similarloupan')
        box.addClass(showClass);
    }

    //打开sub订阅逻辑存窗口
    function openSubscribe(params, config, elm) {
        elm.find('.user-pa-subscribe').addClass(showClass);
        //开放式联动选择
        var category = params.category;
        if (category.indexOf(8) > -1 || category.indexOf(9) > -1) {
            elm.find('.pa-notice').hide();
        }
        var cks = elm.find(".pa-notice input");
        cks.prop("checked", false);
        cks.each(function (k, v) {
            var id = $(v).val();
            var inArr = false;
            $.each(category, function (ik, iv) {
                if (id == iv) {
                    inArr = true;
                }
            });
            inArr && $(v).prop("checked", true);
        });
    }

    //纯登录
    function openSignUser(elm) {
        elm = elm.op.modal;
        // elm.find(".hd").hide();
    }

    //问答
    function openWenda(params, config, elm) {
        var label = elm.find('.user-pa-wenda');
        label.addClass(showClass);
        var currentText = label.find(".pa-label").text()
        label.find(".pa-label").html(currentText + (params.hk_station_url ? `如您为港澳台手机用户，请点击<a href=${params.hk_station_url}>联系售楼处</a>` : ``))
    }

    //点评
    function openUgc(params, config, elm) {
        var label = elm.find('.user-pa-ugc');
        label.addClass(showClass);
    }

    ns.PhoneActivate = function (data) {
        configure = $.extend({}, configure, data);
        this.ai = ns.ApplyInterface.setAjaxUrl(configure.subAjaxUrl);
        this.init();
        this.hasBindSubscribeCheckEvent = false;
    };
    ns.PhoneActivate.prototype = {
        constructor: ns.PhoneActivate,
        init: function () {
            this.onRefreshEvent();
            //登录或绑定监听
            this.loginBindSuccess();
            //closeLoading
            this.closeLoading();
            if (configure.isOpenCity) { //开通城市
                //订阅行为
                this.subscribeEvent();
                //组团看房
                this.zutuanEvent();
                //专车看房
                this.zhuancheEvent();
                //看房团
                this.kanfangEvent();
                //优惠
                this.youhuiEvent();
                // 房源
                this.houseEvent();
                // 房源单页优惠领取
                this.houseViewEvent();
                //预约看房/预约顾问
                this.yuyueEvent();
                //纯登录
                this.signuserEvent();
                //问答登陆
                this.wendaEvent();
                //点评登陆
                this.ugcEvent();
                //主题营销领取优惠
                this.marketEvent();
                // 预约直播提醒
                this.liveEvent();
            }
            if (configure.isSaleOut) { //售罄盘全部都要，不分城市
                // 订阅相似楼盘动态
                this.similarloupanEvent();
            }
            if (configure.isBookingCall) {
                this.bookingcallEvent();
            }
            if (configure.isOneKeySub) {
                this.oneKeySubscribeEvent();
            }
        },
        // 刷新
        onRefreshEvent: function (params) {
            var that = this;
            $(document).on('refreshSignEvent', function (e, params) {
                switch (params.type) {
                    case 'live':
                        that.liveEvent();
                        break;
                    default:
                        break;
                }
            })
        },
        //提交申请
        userDoApply: function (type, params, isFirst) {
            var that = this;
            if (!ns.IsSwitcher()) {
                return false;
            }
            var config, conf;
            var isOneKeySub = (params.category || []).indexOf(28) > -1;
            var loupancitySub = (params.category || []).indexOf(8) > -1;
            var loupanregionSub = (params.category || []).indexOf(9) > -1;

            if (isOneKeySub) {
                config = conf = ns.GetBaseConfig(PA_TYPE.ONEKEYSUBSCRIBE);
            } else {
                config = conf = ns.GetBaseConfig(type);
            }
            //点击发码
            ns.Soj.send(config.apiType, params.sojTap, false);

            function do_subscribe(params, conf) {
                var isOneKeySub = (params.category || []).indexOf(28) > -1,
                    isBookingCall = (params.category || []).indexOf(27) > -1;
                that.ai.subscribe(params, function (err, rs) {
                    ns.Soj.send(config.apiType, params.sojApply, true);
                    if (rs && rs.status == 0) {
                        ns.Hint(conf.title, conf.mainHead, conf.subHead);
                    } else {
                        ns.Hint(conf.title, '', rs.msg);
                    }
                });
            }

            function do_appoint(params, conf) {
                that.ai.appoint(params, function (err, rs) {
                    ns.Soj.send(config.apiType, params.sojApply, true);
                    if (rs && rs.status == 0) {
                        ns.Hint(conf.title, conf.mainHead, conf.subHead);
                    } else {
                        ns.Hint(conf.title, '', rs.msg);
                    }
                });
            }

            function do_applycar(params, conf) {
                that.ai.applycar(params, function (err, rs) {
                    ns.Soj.send(config.apiType, params.sojApply, true);
                    if (rs && rs.status == 0) {
                        ns.Hint(conf.title, conf.mainHead, conf.subHead);
                    } else {
                        ns.Hint(conf.title, '', rs.msg || rs.err_msg);
                    }
                });
            }

            function do_zutuan(params, conf) {
                that.ai.applygroup(params, function (err, rs) {
                    ns.Soj.send(config.apiType, params.sojApply, true);
                    if (rs && rs.status == 0) {
                        ns.Hint(conf.title, conf.mainHead, conf.subHead);
                    } else {
                        ns.Hint(conf.title, '', rs.msg);
                    }
                });
            }

            function do_tuangou(params, conf, is_authorization) {
              is_authorization && recordAuthorization(params.loupan_id, params.target_type, 1);
                that.ai.tuangou(params, function (err, rs) {
                    ns.Soj.send(config.apiType, params.sojApply, true);
                    if (rs && rs.status == 0) {
                        ns.ShowToast(conf.mainHead);
                        const currentBtn = $(`[tuan-btn][data-tid='${params.tid}']`)
                        if (currentBtn.data('type') == 1) {
                            currentBtn.html('已领取');
                        } else {
                            currentBtn.html('已报名');
                        }
                        currentBtn.addClass('end signup-btn-end');
                        currentBtn.removeAttr("tuan-btn");
                    } else {
                        ns.ShowToast(rs.msg || rs.message);
                    }
                });
            }

            function do_applycheck(params, conf, is_authorization) {
              is_authorization && recordAuthorization(params.loupan_id, params.target_type, 1);
                that.ai.applycheck(params, function (err, rs) {
                    ns.Soj.send(config.apiType, params.sojApply, true);
                    if (rs && rs.status == 0) {
                      ns.ShowToast(conf.mainHead);
                    } else {
                        ns.Hint(conf.title, '', rs.msg);
                        ns.ShowToast(rs.msg);
                    }
                });
            }

            // 获取主题营销报名优惠
            function do_market(params, conf) {
                var modal, imageUrl;
                var tpl = XF.Tool.tpl.template($('script#market-result-tpl').html(), { variable: 'marketResult' });
                if (!modal) {
                    modal = new XF.Modal({
                        modalClass: "market-modal",
                        hd: '',
                        bd: $(".user-market-sign-up-modal"),
                        width: '352',
                        height: '492'
                    });
                }
                $.ajax({
                    url: __base_url + '/ajax/market/enroll/',
                    type: 'GET',
                    dataType: 'json',
                    data: {
                      enrollment_id: params.enrollment_id,
                      site_id: params.site_id,
                      campaign_id: params.campaign_id,
                      loupan_id: params.loupan_id
                    },
                    success: function (data) {
                        var result = data.result;
                        if (data.status == true) {
                            $('.user-market-sign-up-modal').html(tpl(result));
                            modal.open();
                            if (result.status == 7) {
                              $("html").trigger("getEnrollement", [params.elm]);
                            }
                        }
                    },
                    error: function () {}
                });
            }

            // 获取房源优惠
            function do_house(params, conf) {
                $.ajax({
                    url: __base_url + '/ajax/house/coupon/',
                    type: 'GET',
                    dataType: 'json',
                    data: params,
                    success: function (data) {
                        if (data.status == true) {
                            ns.Hint(conf.title, conf.mainHead, conf.subHead);
                        } else {
                            ns.Hint(conf.title, '', data.message);
                        }
                        $("html").trigger("getSpecialData");
                    },
                    error: function () {}
                });
            }
            if (checkUser() == 2) { //已登陆状态
                if (type == "subscribe") { //变价通知 优惠通知 开盘通知 最新动态 看房通知 楼盘列表城市（区域）免费订阅 2 / 15 / 1 / 3 / 4 / 8（9）
                    if (isFirst) {
                        if (isOneKeySub) {
                            params.category = [28];
                        } else {
                            params.category = [];
                        }
                        if (loupancitySub) {
                            params.category = [8];
                        } else if (loupanregionSub) {
                            params.category = [9];
                        }
                        var nodes = $(".user-pa-subscribe .pa-notice").find("input");
                        nodes.each(function (k, v) {
                            if ($(v).prop("checked")) {
                                params.category.push($(v).val());
                            }
                        });
                        do_subscribe(params, conf);
                    } else {
                        that.ai.subscribe($.extend({}, params, {
                            "check": 1
                        }), function (err, rs) {
                            if (rs && rs.status == 0) { //未订阅过
                                ns.Confirm(conf.title, conf.confirmTip, rs.phone, conf.confirmBtnText, conf.cancelBtnText, function () {
                                    do_subscribe(params, conf);
                                });
                            } else if (rs && rs.status == 1) {
                                ns.Hint(conf.title, '', rs.msg);
                            }
                        });
                    }
                } else if (type == "yuyuekanfang" || type == "yuyueguwen") {
                    if (isFirst) {
                        do_appoint(params, conf);
                    } else {
                        that.ai.appoint($.extend({}, params, {
                            "check": 1
                        }), function (err, rs) {
                            if (rs && rs.status == 0) { //未订阅过
                                ns.Confirm(conf.title, conf.confirmTip, rs.phone, conf.confirmBtnText, conf.cancelBtnText, function () {
                                    do_appoint(params, conf);
                                });


                            } else if (rs && rs.status == 1) {
                                ns.Hint(conf.title, '', rs.msg);
                            }
                        });
                    }
                } else if (type == "zhuanche") {
                    if (isFirst) {
                        do_applycar(params, conf);
                    } else {
                        that.ai.applycar($.extend({}, params, {
                            "check": 1
                        }), function (err, rs) {
                            if (rs && rs.status == 0) { //未订阅过
                                ns.Confirm(conf.title, conf.confirmTip, rs.phone, conf.confirmBtnText, conf.cancelBtnText, function () {
                                    do_applycar(params, conf);
                                });
                            } else if (rs && rs.status == 1) {
                                ns.Hint(conf.title, '', rs.msg);
                            }
                        });
                    }
                } else if (type == "zutuan") {
                    if (isFirst) {
                        do_zutuan(params, conf);
                    } else {
                        that.ai.applygroup($.extend({}, params, {
                            "check": 1
                        }), function (err, rs) {
                            if (rs && rs.status == 0) { //未订阅过
                                ns.Confirm(conf.title, conf.confirmTip, rs.phone, conf.confirmBtnText, conf.cancelBtnText, function () {
                                    do_zutuan(params, conf);
                                });
                            } else if (rs && rs.status == 1) {
                                ns.Hint(conf.title, '', rs.msg);
                            }

                        });
                    }
                } else if (type == "youhui" || type == 'signup') { //优惠和活动中间确认层文案走可配置
                    if (isFirst) {
                        XF.Soj.send({
                          loupan_id: params.loupan_id || 0,
                          type: 2
                        }, {
                          action: 'weapp_click_dltc'
                        });
                        getUserAuthorization(params.target_type, params.loupan_id || params.city_id, params.city_id, function (is_authorization, is_pilot_city) {
                          do_tuangou(params, conf, true);
                        });
                    } else {
                        that.ai.tuangou($.extend({}, params, {
                            "check": 1
                        }), function (err, rs) {
                            if (rs && rs.status == 0) { //未订阅过
                                getUserAuthorization(params.target_type, params.loupan_id || params.city_id, params.city_id, function (is_authorization, is_pilot_city) {
                                  if (is_pilot_city == 1) {
                                    if (is_authorization) {
                                      do_tuangou(params, conf, false);
                                    } else {
                                      ns.Confirm(conf.title, conf.confirmTip, '', conf.confirmBtnText, conf.cancelBtnText, function () {
                                        XF.Soj.send({
                                          loupan_id: params.loupan_id || 0,
                                          button_type: 1,
                                          type: 2
                                        }, {
                                          action: 'weapp_click_sqtc'
                                        });
                                        do_tuangou(params, conf, true);
                                      }, function (button_type) {
                                        XF.Soj.send({
                                          loupan_id: params.loupan_id || 0,
                                          button_type,
                                          type: 2
                                        }, {
                                          action: 'weapp_click_sqtc'
                                        });
                                      });
                                    }
                                  } else {
                                    do_tuangou($.extend({}, params, {authorize_status: 2}), conf, false);
                                  }
                                });

                            } else if (rs && rs.status == 1) {
                                ns.ShowToast(rs.msg);
                            }
                        });
                    }
                } else if (type == "kanfang") {
                    if (isFirst) {
                      XF.Soj.send({
                        loupan_id: params.loupan_id || 0,
                        type: 2
                      }, {
                        action: 'weapp_click_dltc'
                      });
                      getUserAuthorization(params.target_type, params.loupan_id || params.city_id, params.city_id, function (is_authorization, is_pilot_city) {
                        do_applycheck(params, conf, true);
                      });
                    } else {
                        that.ai.applycheck($.extend({}, params, {
                            "check": 1
                        }), function (err, rs) {
                          getUserAuthorization(params.target_type, params.loupan_id || params.city_id, params.city_id, function (is_authorization, is_pilot_city) {
                            if (rs && rs.status == 0) { //未订阅过
                              if (is_pilot_city == 1) {
                                if (is_authorization) {
                                  do_applycheck(params, conf, false);
                                } else {
                                  ns.Confirm(conf.title, conf.confirmTip, '', conf.confirmBtnText, conf.cancelBtnText, function () {
                                    XF.Soj.send({
                                      loupan_id: params.loupan_id || 0,
                                      button_type: 1,
                                      type: 2
                                    }, {
                                      action: 'weapp_click_sqtc'
                                    });
                                    do_applycheck(params, conf, true);
                                  }, function (button_type) {
                                    XF.Soj.send({
                                      loupan_id: params.loupan_id || 0,
                                      button_type,
                                      type: 2
                                    }, {
                                      action: 'weapp_click_sqtc'
                                    });
                                  });
                                }
                              } else {
                                do_applycheck($.extend({}, params, {authorize_status: 2}), conf, false);
                              }
                            } else if (rs && rs.status == 1) {
                                ns.ShowToast(rs.msg);
                            }
                          });
                        });
                    }
                } else if (type == "similarloupan") {
                    if (isFirst) {
                        do_subscribe(params, conf);
                    } else {
                        that.ai.subscribe($.extend({}, params, {
                            "check": 1
                        }), function (err, rs) {
                            if (rs && rs.status == 0) { //未订阅过
                                ns.Confirm(conf.title, conf.confirmTip, rs.phone, conf.confirmBtnText, conf.cancelBtnText, function () {
                                    do_subscribe(params, conf);
                                });

                            } else if (rs && rs.status == 1) {
                                ns.Hint(conf.title, '', rs.msg);
                            }
                        });
                    }
                } else if (type == PA_TYPE.BOOKINGCALL) { //预约回电
                    if (isFirst) {
                        do_subscribe(params, conf);
                    } else {
                        that.ai.subscribe($.extend({}, params, {
                            "check": 1
                        }), function (err, rs) {
                            if (rs && rs.status == 0) { //未订阅过
                                ns.Confirm(conf.title, conf.confirmTip, rs.phone, conf.confirmBtnText, conf.cancelBtnText, function () {
                                    do_subscribe(params, conf);
                                });

                            } else if (rs && rs.status == 1) {
                                ns.Hint(conf.title, '', rs.msg);
                            }
                        });
                    }
                } else if (type == 'signuser') { //纯用户登录
                    $(document).trigger('signuser', [$.extend(true, {}, window.signUserInfo, params)]);
                } else if (type == 'wenda') {
                    if (params.quesval) {
                        $(document).trigger('ask', [$.extend(true, {}, params)]);
                    } else {
                        $(document).trigger('jumptoask', [$.extend(true, {}, params)]);
                    }
                    if (params.answval) {
                        $(document).trigger('answer', [$.extend(true, {}, params)]);
                    } else {
                        $(document).trigger('jumptoanswer', [$.extend(true, {}, params)]);
                    }
                } else if (type == 'ugc') {
                    if (params.inputval) {
                        $(document).trigger('ugc', [$.extend(true, {}, params)]);
                    }
                } else if (type == 'market') {
                    do_market({
                        enrollment_id: params.enrollment_id,
                        site_id: params.site_id,
                        campaign_id: params.campaign_id,
                        loupan_id: params.loupan_id,
                        elm: params.elm
                    });
                } else if (type == 'house') {
                    do_house({
                        house_id: params.house_id
                    }, conf);
                } else if (type == 'live') {
                    $(document).trigger('sign4live', [$.extend(true, {}, window.signUserInfo, params)]);
                }
                return false;
            } else {
                return true;
            }
        },
        loginBindSuccess: function () {
            var that = this;
            $(document).on(ns.keys.loginSuccess + " " + ns.keys.bindPhoneSuccess, function (e, rs) {
                if (rs.userInfo && rs.userInfo.phone_num) {
                    //设置手机号
                    configure.isBindPhone = rs.userInfo.phone_num ? true : false;
                    configure.isLogin = true;
                    //触发报名行为
                    applyModal.close();
                    that.userDoApply(rs.type, rs.params, true);
                }
            });
        },
        closeLoading: function () {
            var that = this;
            $(document).on(ns.keys.frameLoad, function () {
                var modalElm = applyModal.op.modal;
                modalElm.find(".loading-wrap").hide();
                modalElm.find("#pa-iframe-box").css("visibility", "");
            });
        },
        bookingcallEvent: function () {
            var that = this;
            var type = PA_TYPE.BOOKINGCALL;
            $(".pa-btns-bookingcall").off("click").on("click", function () {
                var params = {};
                params.subFrom = $(this).data("sub_from") || 201;
                params.loupanId = $(this).data("loupan_id") || 0;
                params.sojTap = $(this).data("soj") || "";
                that.senSoj(params.sojTap || 'bookcall');
                params.category = [27];
                params.isShow = true;
                if (that.userDoApply(type, params)) {
                    params.isShow = false;
                    //是否已经登录有手机号
                    getFrameModal(type)(params);
                }
            });
        },
        subscribeCheckEvent: function () {
            $(".user-pa-subscribe .pa-notice").find("input").on("click", function () {
                var cks = $(this).parent().parent().find("input").filter(":checked").prop('checked', true);
                if (cks.length < 1) {
                    $(this).prop("checked", true);
                }
            });
        },
        oneKeySubscribeEvent: function () {
            var that = this;
            var type = PA_TYPE.SUBSCRIBE;
            $('.pa-btns-onekey-subcribe').off('click').on('click', function () {
                var category = [28, 3];
                var params = {};
                params.category = category;
                params.subFrom = $(this).data("sub_from") || 101;
                params.loupanId = $(this).data("loupan_id") || 0;
                params.sojTap = $(this).data("soj") || "";
                that.senSoj(params.sojTap || 'onekeysub');
                params.isShow = true;
                if (that.userDoApply(type, params)) {
                    params.isShow = false;
                    //是否已经登录有手机号
                    getFrameModal(type)(params)
                }
            });
            if (!this.hasBindSubscribeCheckEvent) {
                this.subscribeCheckEvent();
            }
        },
        senSoj: function (soj) {
            XF.Soj.send('{from:' + soj + '}', XF.Soj.param);
        },
        //获取专车.预约看房二维码
        // 需要type,loupanid的对象
        getQrcode: function (params, cb) {
            $.post('https://m.anjuke.com/xinfang/graphql/GetAppointmentQrCode/?weapp_source=ajk_xinfang', {
                variables: params
            }, function (data) {
                if (data.data.appointment_qr_code.image_url) {
                    cb(data.data.appointment_qr_code.image_url)
                }
            })
        },
        subscribeEvent: function () {
            var that = this;
            var type = 'subscribe';
            //解除订阅类按钮事件
            var btns = ".subscribe-link,.subscribe-open-a .acti-group,.subscribe-open-btn,.loupanlistsubs";
            $(btns).off('click').on("click", function () {
                var subData = $(this).attr('sub-data');
                var params = {};
                var category = [];
                var conf = [0, 2, 15, 1, 3, 4, 8, 9];
                $.each(subData.split(","), function (k, v) {
                    conf[v] && category.push(conf[v]);
                });
                params.category = category;
                params.subFrom = $(this).data("sub_from") || 101;
                params.loupanId = $(this).data("loupan_id") || 0;
                params.sojTap = $(this).data("soj") || "";
                params.isShow = true;
                if (that.userDoApply(type, params)) {
                    params.isShow = false;
                    getFrameModal(type)(params);
                }
            });
            //选择类订阅
            $(document).off('click', '.subscribe-mix .btn');
            $(".pa-btns-group").on("click", function () {
                var cks = $(this).parent().parent().find("input").filter(":checked").prop('checked', true);
                var category = [];
                var params = {};
                cks.each(function (k, v) {
                    category.push($(v).val());
                });
                params.category = category;
                params.subFrom = $(this).data("sub_from") || 101;
                params.loupanId = $(this).data("loupan_id") || 0;
                params.sojTap = $(this).data("soj") || "";
                params.isShow = true;
                if (that.userDoApply(type, params)) {
                    params.isShow = false;
                    //是否已经登录有手机号
                    getFrameModal(type)(params);
                }
            });
            //强制设置必须选择一个checkbox
            $(".pa-btns-group").parent().parent().find(".sub-list li input").on('click', function () {
                var cks = $(this).parent().parent().find("input").filter(":checked").prop('checked', true);
                if (cks.length < 1) {
                    $(this).prop("checked", true);
                }
            });

            if (!this.hasBindSubscribeCheckEvent) {
                this.subscribeCheckEvent();
            }

        },
        youhuiEvent: function () {
            var that = this;
            // var type = "youhui";
            var btns = $("[tuan-btn]");
            var data = XF.Vars.tuanData;

            $.each(btns, function (index, v) {
                var box = $('.discount-box,.surroundactivity-box'),
                    elm_del = v; //委托事件的dom
                if (box.length > 0) { //异步加载的模块
                    if ($(v).parents('.discount-box').length > 0) {
                        elm_del = $(v).parents('.discount-box');
                    }
                    if ($(v).parents('.surroundactivity-box').length > 0) {
                        elm_del = $(v).parents('.surroundactivity-box');
                    }
                }
                //团购
                $(elm_del).on("click", v, youhuievent);

                function youhuievent(event) {
                    event.stopPropagation();
                    $(elm_del).off("click", youhuievent);
                    $(v).on("click", youhuievent);
                    if ($(event.target).attr('tuan-btn') == undefined) {
                        return;
                    }
                    var type = 'youhui';
                    var elm = $(this);
                    if ($(this).hasClass('discount-box') || $(this).hasClass('surroundactivity-box')) { //代理到外层
                        elm = $(this).find('[tuan-btn]');
                    }
                    var row;
                    var params = {};
                    if (!data || !data.length) {
                        return;
                    }
                    if (data.length === 1) {
                        row = data[0];
                    } else {
                        row = data[index];
                    }
                    var ckb = $(".check-box");
                    params.loupan_name = row.data.loupan_name;
                    params.tid = elm.data("tid") || row.tid;
                    params.loupan_id = row.data.loupan_id;
                    params.tuangou = elm.data("from") || 0;
                    params.tuanType = elm.data('type') || 0; //1 优惠  2 活动
                    params.target_type = elm.data('target_type');
                    params.city_id = elm.data('city_id');
                    params.join_kft = 1;
                    params.line_id = 0;
                    params.kft_join_id = 0;
                    params.kft_type = ckb.find('input[name=kft_type]').val();
                    params.bind_id = ckb.find('input[name=kft_id]').val();
                    params.sojTap = elm.data('soj');
                    params.sojApply = elm.data('soj');
                    params.ext = elm.data("ext") || "";
                    params.isShow = false;
                    params.hk_station_url = elm.data("hk_station_url")
                    if (params.tuanType != 0) { //为1和2时 已登录状态下需要预先弹出一个提示，确认后报名， 为2的 title 为活动报名 ，但是接口就是团购的
                        params.isShow = true;
                    }
                    if (params.tuanType == 2) { //团购活动报名
                        type = 'signup';
                    }
                    if (that.userDoApply(type, params)) { //未登录状态下不需要确认弹层
                        params.isShow = false;
                        getFrameModal(type)(params);
                    }
                }
            })
        },

        houseEvent: function () {
            var that = this;
            var btns = $("[house-btn]");

            $.each(btns, function (index, v) {
                $(v).on("click", houseievent);

                function houseievent(event) {
                    event.stopPropagation();
                    XF.Soj.send({}, {
                        action: 'xf_loupanhome_tefy_fangyuan_click'
                    });
                    if ($(event.target).attr('house-btn') == undefined) {
                        return;
                    }
                    var type = 'house';
                    var elm = $(this);
                    if ($(this).hasClass('special-house-mod')) { //代理到外层
                        elm = $(this).find('[house-btn]');
                    }
                    if (elm.data('discount_state') == 2) return;
                    var params = {};
                    params.house_id = elm.data('house_id');
                    params.discount_desc = elm.data('discount_value').value + elm.data('discount_value').unit;
                    params.hk_station_url = elm.data('hk_station_url');
                    params.isShow = true;
                    if (that.userDoApply(type, params)) { //未登录状态下不需要确认弹层
                        params.isShow = false;
                        getFrameModal(type)(params);
                    }
                }
            })
        },
        houseViewEvent: function () {
            var that = this;
            var btns = $("[house-receive-btn]");
            $(btns).on("click", houseievent);

            function houseievent(event) {
                event.stopPropagation();
                XF.Soj.send({}, {
                    action: 'xf_fangyuan_fxyh_lingqu_click'
                });
                var type = 'house';
                var elm = $(this);
                if (elm.data('discount_state') == 2) return;
                var params = {};
                params.house_id = elm.data('house_id');
                params.discount_desc = elm.data('discount_desc');
                params.hk_station_url = elm.data('hk_station_url')
                params.isShow = true;
                if (that.userDoApply(type, params)) { //未登录状态下不需要确认弹层
                    params.isShow = false;
                    XF.Soj.send({}, {
                        action: 'xf_fangyuan_fxyh_lingqu_signup'
                    });
                    getFrameModal(type)(params);
                }
            }
        },
        kanfangEvent: function () {
            var that = this;
            var type = "kanfang";
            var btns = $("[kft-sign]");
            var data = XF.Vars.kftData2 || XF.Vars.kftData;

            $.each(btns, function (index, v) {
                //看房团
                var box = $('.kft-box'),
                    elm_del = v; //委托事件的dom
                if (box.length > 0) { //异步加载的模块
                    if ($(v).parents('.kft-box').length > 0) {
                        elm_del = $(v).parents('.kft-box');
                    }
                }

                $(elm_del).on("click", v, kftevent);

                function kftevent(event) {
                    event.stopPropagation();
                    $(elm_del).off("click", kftevent);
                    $(v).on("click", kftevent);
                    if ($(event.target).attr('kft-sign') == undefined) {
                        return;
                    }
                    var elm = $(this);
                    if ($(this).hasClass('kft-box')) { //代理到外层
                        elm = $(this).find('[kft-sign]');
                    }
                    var row;
                    var params = {};
                    if (!data || !data.length) {
                        return;
                    }
                    if (data.length === 1) {
                        row = data[0];
                    } else {
                        row = data[index];
                    }
                    params.time = row.data.time;
                    params.line_name = row.data.line_name;
                    params.line_id = row.lid;
                    params.apply_source = $(".int-text-from").val();
                    params.tuangou_id = row.data.tuangou_id;
                    params.target_type = 1013;
                    params.city_id = elm.data('city_id');
                    params.sojTap = elm.data("soj");
                    params.isShow = true;
                    if (that.userDoApply(type, params)) {
                        params.isShow = false;
                        getFrameModal(type)(params);
                    }
                }
            });
        },
        zhuancheEvent: function () {
            var that = this;
            var type = "zhuanche";
            var btns = $("[kft-car-btn]");
            var data = XF.Vars.kftCarData;
            var modal;
            //专车
            $.each(btns, function (index, v) {
                var box = $('.kft-box'),
                    elm_del = v; //委托事件的dom
                if (box.length > 0) { //异步加载的模块
                    if ($(v).parents('.kft-box').length > 0) {
                        elm_del = $(v).parents('.kft-box');
                    }
                }

                $(elm_del).on("click", v, zhuancheevent);

                function zhuancheevent(event) {
                    event.stopPropagation();
                    $(elm_del).off("click", zhuancheevent);
                    $(v).on("click", zhuancheevent);
                    if ($(event.target).attr('kft-car-btn') == undefined) {
                        return;
                    }
                    var elm = $(this);
                    if ($(this).hasClass('kft-box')) { //代理到外层
                        elm = $(this).find('[kft-car-btn]');
                    }
                    var params = {};

                    params.loupanId = $(this).data("loupan_id") || 0;
                    params.type = $(this).data("type") || 1;
                    params.from = $(this).data("soj") || ''
                    params.action = $(this).data("action")
                    if (!ns.IsSwitcher()) {
                        return
                    }
                    if (!modal) {
                        modal = new XF.Modal({
                            modalClass: "modal-custom zhuanche-custom",
                            bd: $("#phone-activate .user-pa-zhuanche"),
                            width: '570',
                            height: '320'
                        })
                    }
                    XF.Soj.send({
                        from: params.from,
                        loupanId: params.loupanId
                    }, {
                        action: params.action
                    })
                    that.getQrcode({
                        loupanId: params.loupanId,
                        type: params.type
                    }, function (img_url) {
                        modal.open();
                        $('.user-pa-zhuanche .qrcode').attr('src', img_url);
                        // 专车看房：1 预约看房：2 专车看房团列表协议:3
                        if (params.type == 1) {
                            $('.user-pa-zhuanche .des-1').html('随时看房 全城免费往返接送');
                            $('.user-pa-zhuanche .des-2').html('任意地点接您，随时出发\n不花一分钱，让看房更简单');
                        }
                        if (params.type == 2) {
                            $('.user-pa-zhuanche .des-1').html('提前预约 看好房不用等');
                            $('.user-pa-zhuanche .des-2').html('好房不容错过，预约实地看房');
                        }
                    })
                }

            });
        },
        zutuanEvent: function () {
            var that = this;
            var type = "zutuan";
            var data = XF.Vars.groupkftData;
            $("[kft-group-sign]").off("click");
            $("body").off('click.groupSign', "[kft-group-sign],[kft-group-sign-top]");
            $("body").on("click.groupSign", "[kft-group-sign]", function (e) {
                var elm = $(this);
                var index = 0;
                var params = {};
                $.each($("[kft-group-sign]"), function (k, v) {
                    if (v === elm.get(0)) {
                        index = k;
                    }
                });
                if (!data || !data[index]) {
                    params.gid = elm.data('gid');
                    params.loupan_name = elm.data("loupanname");
                } else {
                    params.gid = data[index].gid;
                    params.loupan_name = data[index].data.loupan_name;
                }
                params.apply_source = $(".int-text-from").val() || XF.Vars.groupJoinFromTop || 5;
                params.sojTap = $(this).data("soj");
                params.isShow = true;
                if (that.userDoApply(type, params)) {
                    params.isShow = false;
                    getFrameModal(type)(params);
                }
            });
            //列表组团侧栏
            var btnsTop = $("[kft-group-sign-top]");
            var dataTop = XF.Vars.groupkftTopData;
            $.each(btnsTop, function (k, v) {
                $(this).on("click", function () {
                    if (!dataTop || !dataTop[k]) {
                        return;
                    }
                    var row = dataTop[k];
                    var params = {};
                    params.gid = row.gid;
                    params.loupan_name = row.data && row.data.loupan_name ? row.data.loupan_name : "";
                    params.apply_source = $(".int-text-from").val() || XF.Vars.groupJoinFromTop || 5;
                    params.sojTap = $(this).data("soj");
                    params.isShow = true;
                    if (that.userDoApply(type, params)) {
                        params.isShow = false;
                        getFrameModal(type)(params);
                    }
                });
            });
        },
        yuyueEvent: function () {
            var that = this;
            var type = "yuyuekanfang";
            var btns = "#j-btn-bespoken,#j-btn-kft,.consult-btn";
            $(btns).off("click").on("click", function () {
                var elm = $(this);
                var params = {};
                params.loupanId = elm.data("loupan_id") || 0;
                params.consultantId = elm.data("consultant_id") || 0;
                params.info = $("#appoint-info").data("info") || "";
                params.type = elm.data("type") || 5;
                params.ext = elm.data("ext") || "";
                if (params.consultantId) {
                    type = "yuyueguwen";
                    params.sojTap = "loupan_index_zygw_wz" + params.type;
                }
                params.isShow = true;
                if (that.userDoApply(type, params)) {
                    params.isShow = false;
                    getFrameModal(type)(params);
                }
            });
        },
        similarloupanEvent: function () {
            var that = this;
            var type = "similarloupan";
            var btns = "#similarloupansubs";
            $(btns).off("click").on("click", function () {
                var elm = $(this);
                var params = {};
                params.category = [26]; //售罄盘的定义周边
                params.subFrom = $(this).data("sub_from") || 101;
                params.loupanId = $(this).data("loupan_id") || 0;
                params.sojTap = $(this).data("soj") || "";
                params.isShow = true;
                if (that.userDoApply(type, params)) {
                    params.isShow = false;
                    getFrameModal(type)(params);
                }
            });
        },
        signuserEvent: function () {
            var that = this;
            var type = "signuser";
            var prize_btns = $("[getprize]");
            var history_btn = $("#prize-history");
            prize_btns.off("click");
            window.signUserInfo = null;
            //用户登录
            $.each(prize_btns, function (index, v) {
                $(v).on("click", function (event) {
                    event.stopPropagation();
                    var elm = $(this);
                    var ext = {
                        css: elm.data("style") || ""
                    };
                    var loupan_id = $(this).data('loupanid');
                    var city_id = $(this).data('cityid');
                    window.signUserInfo = {
                        loupanid: loupan_id,
                        cityid: city_id
                    }
                    if (that.userDoApply(type, {})) {
                        getFrameModal(type)({}, ext);
                    }
                })
            });
            history_btn.off("click");
            history_btn.on("click", function (event) {
                event.stopPropagation();
                event.preventDefault();
                var elm = $(this);
                var ext = {
                    css: elm.data("style") || ""
                };
                var url = $(this).data("href");
                window.signUserInfo = {
                    href: url
                };
                if (that.userDoApply(type, {})) {
                    getFrameModal(type)({}, ext);
                }
            });
        },
        wendaEvent: function () {
            var that = this;
            var type = "wenda";
            var ques_btns = $('.ques-btn'),
                answ_btns = $('.answ-btn');
            $.each(ques_btns, function (index, v) {
                $(v).on("click", function (event) {
                    event.stopPropagation();
                    var elm = $(this);
                    var params = {};
                    if ($(".ques-textarea").size() > 0) {
                        params.quesval = $(".ques-textarea").val();
                    } else {
                        params.link = elm.data("link");
                        params.soj = elm.data("soj");
                    }
                    params.hk_station_url = elm.data("hk_station_url")
                    if (that.userDoApply(type, params)) {
                        getFrameModal(type)(params);
                    }
                });
            });
            $.each(answ_btns, function (index, v) {
                $(v).on("click", function (event) {
                    event.stopPropagation();
                    var elm = $(this);
                    var params = {};
                    if ($(".answ-textarea").size() > 0) {
                        params.answval = $(".answ-textarea").val();
                    } else {
                        params.link = elm.data("link");
                        params.soj = elm.data("soj");
                    }
                    if (that.userDoApply(type, params)) {
                        getFrameModal(type)(params);
                    }
                })
            });
        },
        ugcEvent: function () {
            var that = this;
            var type = "ugc";
            var dianping_btns = $('#j-dp-dpremark');
            $.each(dianping_btns, function (index, v) {
                $(v).on("click", function (event) {
                    event.stopPropagation();
                    var elm = $(this);
                    var params = {};
                    if ($("#j-remark-infos").size() > 0) {
                        params.inputval = $("#j-remark-infos").val();
                    }
                    if (that.userDoApply(type, params)) {
                        getFrameModal(type)(params);
                    }
                })
            });
        },
        marketEvent: function () {
            var that = this;
            var type = "market";
            var sign_up_cards = $('.sign-up');
            $.each(sign_up_cards, function (index, v) {
                $(v).on("click", function (event) {
                    event.stopPropagation();
                    var elm = $(this);
                    var params = {};
                    params.soj = elm.data('soj');
                    params.type = elm.data('type');
                    params.enrollment_id = elm.data('enrollment_id');
                    params.site_id = elm.data('site_id');
                    params.campaign_id = elm.data('campaign_id');
                    params.loupan_id = elm.data('loupan_id');
                    params.elm = $(this);
                    if (that.userDoApply(type, params)) {
                        getFrameModal(type)(params);
                    }
                });
            });
        },
        liveEvent: function () {
            var that = this;
            var type = "live";
            var live_btns = $(".sub-live");
            live_btns.off("click");
            window.signUserInfo = null;
            //用户登录
            $.each(live_btns, function (index, v) {
                $(v).on("click", function (event) {
                    event.stopPropagation();
                    var elm = $(this);
                    var liveid = $(this).data("liveid"); // 可用于判断点的是哪个按钮
                    var ext = {
                        css: elm.data("style") || ""
                    };
                    var loupan_id = $(this).data('loupanid');
                    var city_id = $(this).data('cityid');
                    window.signUserInfo = {
                        loupanid: loupan_id,
                        cityid: city_id
                    }
                    if (that.userDoApply(type, {
                            liveid: liveid
                        })) {
                        getFrameModal(type)({
                            liveid: liveid
                        });
                    }
                })
            });
        }
    };
})(jQuery, XF.User);
/*
 * @Author: yechunxi 
 * @Date: 2019-06-19 18:12:59 
 * @Last Modified time: 2019-06-19 18:12:59  
 *  58 登录，订阅逻辑
 */
XF.nameSpace('XF.User');

(function($,ns){
    //存储配置数据
    var configure = {
        subAjaxUrl: '', //全报名类型接口
        isLogin: false, //用户是否登录
        isOpenCity: false, //是否是开通城市
        isSaleOut: false //是否是售罄
    };
    var modal = null;

    ns.PhoneActivate58 = function(data) {
        configure = $.extend({}, configure, data);
        this.init();
    };
    ns.PhoneActivate58.prototype = {
        constructor: ns.PhoneActivate58,
        init: function() {
            this.api = ns.ApplyInterface.setAjaxUrl(configure.subAjaxUrl);
            if (configure.isOpenCity) { //开通城市
                //订阅行为
                this.subscribeEvent(); 
                //获取优惠/报名活动
                this.youhuiEvent();
                //（58分销盘）特惠关注
                this.tehuiFxEvent();
            }
            if (configure.isSaleOut) { //售罄盘全部都要，不分城市
                // 订阅相似楼盘动态
                this.similarloupanEvent();
            }
        },
        subscribeEvent:function(){
            var self = this;
            var btns = ".subscribe-link,.subscribe-open-a .acti-group,.subscribe-open-btn,.loupanlistsubs";
            $(btns).off('click').on("click", function() {
                var subData = $(this).attr('sub-data');
                var params = {};
                var category = [];
                var conf = [0, 2, 15, 1, 3, 4,8,9];
                $.each(subData.split(","), function(k, v) {
                    conf[v] && category.push(conf[v]);
                });
                params.category = category;
                params.subFrom = $(this).data("sub_from") || 101;
                params.loupanId = $(this).data("loupan_id") || 0;
                var soj = $(this).data("soj58") || "",
                    custom =$(this).data().sojcustom || "";
                self.sendSoj(soj,custom);
                if (!configure.isLogin) {//未登录
                    self.showLogin58Modal(params,'subscribe');
                    // self.showHint();
                }else{
                    self.doSubscribe(params,'subscribe');
                }
                
            });

            $(document).off('click', '.subscribe-mix .btn');
            $(".pa-btns-group").on("click", function() {
                var cks = $(this).parent().parent().find("input").filter(":checked").prop('checked', true);
                var category = [];
                var params = {};
                cks.each(function(k, v) {
                    category.push($(v).val());
                });
                params.category = category;
                params.subFrom = $(this).data("sub_from") || 101;
                params.loupanId = $(this).data("loupan_id") || 0;
                var soj = $(this).data("soj58") || "",
                    custom =$(this).data().sojcustom || "";
                self.sendSoj(soj,custom);
                if (!configure.isLogin) {
                   self.showLogin58Modal(params,'subscribe');
                }else{
                    self.doSubscribe(params,'subscribe');
                }
            });

             //强制设置必须选择一个checkbox
             $(".pa-btns-group").parent().parent().find(".sub-list li input").on('click', function() {
                var cks = $(this).parent().parent().find("input").filter(":checked").prop('checked', true);
                if (cks.length < 1) {
                    $(this).prop("checked", true);
                }
            });
        },
        similarloupanEvent:function(){
            var self = this;
            var type = "similarloupan";
            var btns = "#similarloupansubs";
            $(btns).off("click").on("click", function() {
                var elm = $(this);
                var params = {};
                params.category = [26]; //售罄盘的定义周边
                params.subFrom = $(this).data("sub_from") || 101;
                params.loupanId = $(this).data("loupan_id") || 0;
                params.isShow = true;
                if (!configure.isLogin) {
                    self.showLogin58Modal(params,'subscribe');
                 }else{
                     self.doSubscribe(params,'subscribe');
                 }
            });
        },
        youhuiEvent:function(){
            var self = this;
            var btns = $("[tuan-btn]");
            var data = XF.Vars.tuanData;
            $.each(btns, function(index, v) {
                var box = $('.discount-box,.surroundactivity-box'),
                elm_del=v;//委托事件的dom
                if(box.length>0){ //异步加载的模块
                    if($(v).parents('.discount-box').length > 0){
                        elm_del = $(v).parents('.discount-box');
                    }
                    if($(v).parents('.surroundactivity-box').length > 0){
                        elm_del = $(v).parents('.surroundactivity-box');
                    }
                }
                //团购
                $(elm_del).off('click').on("click",v,youhuievent);

                function youhuievent(event){
                    event.stopPropagation();
                    $(elm_del).off("click",youhuievent);
                    $(v).on("click",youhuievent);
                    if($(event.target).attr('tuan-btn') == undefined){
                        return;
                    }
                    var type = 'youhui';
                    var elm = $(this);
                    if($(this).hasClass('discount-box')||$(this).hasClass('surroundactivity-box')){ //代理到外层
                        elm = $(this).find('[tuan-btn]');
                    }
                    var row;
                    var params = {};
                    if (!data || !data.length) {
                        return;
                    }
                    if (data.length === 1) {
                        row = data[0];
                    } else {
                        row = data[index];
                    }
                    var ckb = $(".check-box");
                    params.loupan_name = row.data.loupan_name;
                    params.discount = row.data.fanli ? row.data.fanli_title : row.data.discount;
                    params.tid = elm.data("tid") || row.tid;
                    params.loupan_id = row.data.loupan_id;
                    params.tuangou = elm.data("from") || 0;
                    params.tuanType = elm.data('type') || 0;//1 优惠  2 活动
                    params.join_kft = 1;
                    params.line_id = 0;
                    params.kft_join_id = 0;
                    params.kft_type = ckb.find('input[name=kft_type]').val();
                    params.bind_id = ckb.find('input[name=kft_id]').val();
                    params.sojTap = elm.data('soj58');
                    params.sojApply = elm.data('soj58');
                    params.ext=elm.data("ext") || "";
                    params.isShow = false;
                    if(params.tuanType != 0){//为1和2时 已登录状态下需要预先弹出一个提示，确认后报名， 为2的 title 为活动报名 ，但是接口就是团购的 
                         params.isShow = true;
                    }
                    if(params.tuanType ==2) {//团购活动报名
                        type ='signup';
                    }
                    if (!configure.isLogin) {
                        self.showLogin58Modal(params,type);
                     }else{
                         self.doSubscribe(params,type);
                     }
                }
            });
        },
        tehuiFxEvent:function(){
            var self = this;
            var btns = ".follow-btn";
            var type = "th_follow";
            $(btns).off('click').on("click", function() {
                var params = {};
                params.sourceId = $(this).data("source_id") || 0;
                params.tehuiData = JSON.parse($(this).attr('data-tehuiData')) || {};
                if (!configure.isLogin) {
                    self.showLogin58Modal(params,type);
                 }else{
                     self.doSubscribe(params,type);
                 }
            });
        },
        sendSoj:function(soj,custom) {
            XF.Soj.send(custom,{action:soj || ''});
        },
        showLogin58Modal:function(params,type){
            var self = this;
            //58弹窗
            pop_init({
                source:"58-xinfang-pc",
                loginMode: [0, 1, 2, 3],
                domain:'58.com',
                callback:function(res){//登录成功
                    if(res.code == 0){
                        self.doSubscribe(params,type);
                        configure.isLogin = true;
                    }
                    
                } 
            });
        },
        doSubscribe:function(params,type){
            var self = this;
            if(type == 'subscribe'){
                this.api.subscribe(params,function(err,rs){
                    if (rs && rs.status == 0) {
                        self.showHint();
                    }else{
                        self.showHint('订阅成功','已订阅');
                    }
                });
            }else if(type == 'youhui'){
                this.api.tuangou(params,function(err,rs){
                    if (rs && rs.status == 0) {
                        self.showHint('领取成功','稍后获取优惠短信会发送至您的手机~');
                    }else{
                        self.showHint('领取成功','已领取');
                    }
                });
            }else if(type == 'signup'){
                this.api.tuangou(params,function(err,rs){
                    if (rs && rs.status == 0) {
                        self.showHint('报名成功','稍后活动报名短信会发送至您的手机~');
                    }else{
                        self.showHint('报名成功','已报名');
                    }
                });
            }else if(type == 'th_follow'){
                var follow_num = parseInt($('.tehui-actions').find('em').text(),10);
                this.api.follow(params,function(err,rs){
                    if(rs && rs.status == 0){ 
                        if(!!params.tehuiData.adviser&&params.tehuiData.adviser.name!= ""){
                            self.showThHint('关注成功','楼盘优惠信息将第一时间推送给你，你也可以电话联系我了解更多详细信息',params.tehuiData);
                            $('.tehui-actions').find('em').html(follow_num+1);
                        }else{
                            self.showThHint('关注成功','楼盘优惠信息将第一时间推送给你，你也可以致电售楼处了解详细信息',params.tehuiData);
                            $('.tehui-actions').find('em').html(follow_num+1);
                        }
                    }else if(rs && rs.status == 1){
                        self.showHint('','你已关注购房特惠');
                    }
                });
            }
        },
        showHint:function(title,comment,icon){
            modal = new XF.Modal({
                modalClass: "modal-custom user-pa-hint",
                bd: $("#user-apply-modal"),
                width: '540',
                height: '320'
            });
            //
            $('.modal-mask').off("click").on("click", function() {
                modal.close();
            });
            
            modal.open();
            var elm = modal.op.modal,
                titleElm = elm.find(".modal-content .msg-title"),
                commentElm = elm.find(".am-msg-comment"),
                iconElm = elm.find(".suc-icon");
            titleElm.html(title || "");
            commentElm.html(comment || "最新楼盘动态以短信方式推送给您~");
            iconElm.html(icon || '&#xea08;');
            
        },
        showThHint:function(title,comment,data){
            modal = new XF.Modal({
                modalClass: "modal-custom tehui-hint",
                bd: $("#user-apply-tehui-modal"),
                width: '488',
                height: '338'
            });
            
            var tehui_pop_tpl = $("#tehui-pop-tpl").html();
            var tehui_pop_html= XF.Tool.tpl.template(tehui_pop_tpl)({tehui:data})
            $("#user-apply-tehui-modal").append(tehui_pop_html);

            this.getWchatQR();
            modal.open();

            var elm = modal.op.modal,
                titleElm = elm.find(".modal-content .msg-title"),
                commentElm = elm.find(".am-msg-comment");
                iconElm = elm.find(".suc-icon");
            titleElm.html(title);
            commentElm.html(comment);
            iconElm.html('&#xea08;');


        },
        getWchatQR:function(){
            var self=this,
            qrBox = $('.wchar-qr'),
            params = {
                'from':'loupan_view',
                'loupan_id': XF.Vars.loupan_id
            };
            var imgUrl = '';
            var broker = $('.adviser-phone-box').attr('data-broker');
            if(XF.Vars.is58Pc&&$('.adviser-phone-box').length > 1&&broker){
                params = {
                    broker_id: broker.broker_id,
                    from: 'broker',
                    encrypted_phone: broker.wuba_mobile||broker.phone,
                    loupan_id: XF.Vars.loupan_id,
                    city_id: broker.city_id
                }
            }
            if(window.QrCodeImg){
                imgUrl = window.QrCodeImg;
                qrBox.find('img').attr('src', imgUrl);
            }else{
                $.ajax({
                    url: __base_url + '/aifang/web/ajax/getQrCode/',
                    type: 'GET',
                    dataType: 'json',
                    data: params,
                    context: qrBox,
                    success: function(data){
                        if(data.status == true) {
                            imgUrl = data.image_url;
                            window.QrCodeImg = imgUrl;
                            if(imgUrl){
                                if(params.from == 'broker'){
                                    qrBox.find('#qr-pos-ct').attr('src', imgUrl);
                                }else if(params.from == 'loupan_view'){
                                    qrBox.find('#qr-pos-lp').attr('src', imgUrl);
                                }
                            }
                        }
                    },
                    error:function() {
                    }
                });
            }

        }
    };
})(jQuery,XF.User);//<div class="resource_tp" data-id="31"></div>
/**
 * 异步获取资源位内容
 */
;(function($, window) {
    /**
     * 资源位样式名
     */
    var _class = ".resource-ifx";
    var _filterClass = "resource-ifx-filter"

    /**
     * 资源位扫描处理队列
     */
    var _queue = [];

    /**
     * 扫描资源位
     */
    function scan() {
        $(_class).each(function(k, v) {
            var elm = $(v);
            var data = elm.data();
            if(elm.hasClass(_filterClass) || !data.resource_id) {
                return;
            }
            _queue.push({
                elm : elm,
                data : data
            });
            elm.addClass(_filterClass);
        });
    }

    /**
     * 加载资源位数据
     */
    function loadResource(url, data, elm, cb) {
        cb = typeof cb == "function" ? cb : function() {};
        var time = new Date(),
            timetmp = time.getTime();
        url = url+'?t='+timetmp;
        $.ajax({
            url : url,
            data: data,
            dataType : "text",
            success : function(rs) {
                cb(null, rs);
                elm.append(rs);
            },
            error : function(e) {
                cb(e);
            }
        });
    }

    /**
     * 监听模块a链接soj组装
     */
    $(_class).on("click", "a", function(e){
        var el = $(this);
        var href = el.attr("href");
        var soj = el.attr("soj") || el.data("soj") || "";
        var fromExp = /(&|\?)from=([^&#]+)/;
        var hashExp = /^[^#]+(#.*?)$/;
        if(!href || !soj) return;
        var hash = "";
        if(hashExp.test(href) ) {
            hash = RegExp.$1 || "";
            href = href.replace(hash,"");
        }
        if(fromExp.test(href)) {
            //直接替换
            href = href.replace(fromExp, "$1from=" + soj);
        } else {
            href += (href.indexOf("?") >= 0 ? "&" : "?") + "from=" + soj + hash;
        }
        el.attr("href", href);
        //清理设置
        el.removeAttr("soj");
        el.removeAttr("data-soj");
    });

    /**
     * 资源位扫描处理队列
     */
    function bootstrap(options) {
        this.url = options.url || "";
        this.scan();
    }

    bootstrap.prototype = {
        num : 0,
        max : 4,
        constructor : bootstrap,
        /**
         * 处理
         */
        process : function() {
            var that = this;
            if(_queue.length < 1 || that.num >= that.max) return;
            var s = _queue.shift();
            if(!s.data || !s.elm) return;
            that.num++;
            loadResource(that.url, s.data, s.elm, function(err, rs) {
                that.num--;
                that.process();
            });
            that.process();
        },
        scan: function() {
            scan();
            this.process();
        }
    }



    window.AsyncResource = bootstrap;
})(window.jQuery || window.Zepto || function() {}, window);;(function ($) {

function initTelPage() {
    var errTxt = '当前楼盘正忙';
    var lock = false;
    function getPhone(phoneConfig,cb,err) {
        var isMobile = arguments.length > 3 && arguments[1] !== undefined ? arguments[1] : '';

        var pre = isMobile ? '/xinfang/api' : __base_url+'';
        var param2 = {};
        if ((phoneConfig.is_fenxiao_loupan == 1 || phoneConfig.params.brokerId) && phoneConfig.is58Pc) {
            if (phoneConfig.is_fenxiao_loupan == 1) {
                param2['loupan_id'] = phoneConfig.params.loupanId;
            }
            if (phoneConfig.params.brokerId) {
                param2['city_id'] = phoneConfig.params.cityId;
                param2['broker_id'] = phoneConfig.params.brokerId;
                param2['encrypted_phone'] = phoneConfig.params.wubaMobile;
            }
            $.ajax({
                url: pre + '/broker/secret/phonenum/',
                method: 'GET',
                dataType: 'json',
                data: param2,
                success: function(rs) {
                    cb(rs);
                },
                error: function() {
                    err();
                }
            });
        } else {
            if (phoneConfig.params.loupanId) {
                param2['loupan_id'] = phoneConfig.params.loupanId;
                $.ajax({
                    url:pre + '/dynamic/loupan/phonenum/',
                    method: "GET",
                    dataType: "json",
                    data: param2,
                    success: function(rs) {
                        cb(rs);
                    },
                    error: function() {
                        err();
                    }
                });
            }
            if (phoneConfig.params.consultantId) {
                param2['consultant_id'] = phoneConfig.params.consultantId;

                $.ajax({
                    url:pre + '/dynamic/consultant/phonenum/',
                    method: "GET",
                    dataType: "json",
                    data: param2,
                    success: function(rs) {
                        cb(rs);
                    },
                    error: function() {
                        err();
                    }
                });
            }
        }
    }

    $('[data-phone]').each(function (i, phone) {
      var telPhone = $(this).data('tel');
      phone.style.opacity = 1;
      bindTel(phone,telPhone);
    });

    function bindTel(phone,telPhone) {
        var phoneConfig = JSON.parse(phone.dataset.phone);
        var errTxt = '当前楼盘正忙,请稍后再说';

        if (+phoneConfig.hasPhone) {
            if (+phoneConfig.isShow) {
                if(!phoneConfig.noTxtDes){
                    var servicePhoneTxt = '点击查看电话';//点击查看售楼处电话
                    if(phoneConfig.isUnlicensed == 1){
                        servicePhoneTxt = '点击查看咨询电话';
                    }
                    genPcUi(phone, phoneConfig.ui == 1 ? '点击查看电话' : (phoneConfig.phoneTitle || servicePhoneTxt), phoneConfig.ui == 1 ? '' : phoneConfig.phoneDesc, phoneConfig.ui);
                }
                pcBindTel(phone, phoneConfig,telPhone);
            }
            if (phoneConfig.isMobile) {
                mobileBindTel(phone, phoneConfig);
            }
        }
    }

    function pcBindTel(phone, phoneConfig,telPhone) {
        phone.onclick = function () {
            try {
                window.XF.Soj.send(phoneConfig.soj, window.XF.Soj.param);
            } catch (e) {}
            if (lock) {
                return;
            }
            lock = true;
            var errTxt = '当前楼盘正忙,请稍后再拨';


            getPhone(phoneConfig,function (res) {
                lock = false;
                if (+res.result.status == 0) {
                    var phoneUi = res.result.num.toString().substring(0, 3) + ' ' + res.result.num.toString().substring(3, 7) + ' ' + res.result.num.toString().substring(7);
                    if(phoneConfig.ui == 5){
                        phoneUi = res.result.num;
                    }
                    genPcUi(phone, phoneUi, phoneConfig.phonePop, phoneConfig.ui, 'after');
                } else if(+res.result.status == 2){
                    if (phoneConfig.ui == '5') {
                        genPcUi(phone,telPhone,'获取电话失败，请稍后再试', phoneConfig.ui);
                    }else{
                        genPcUi(phone,telPhone, phoneConfig.phoneDesc, phoneConfig.ui);
                    }
                }else if (+res.result.status == 1) {
                        if (phoneConfig.ui == '3') {
                            genPcUi(phone, '<span style="color: #a7a7a7">'+ (res.result.tips || errTxt)+'</span>', '', phoneConfig.ui);
                        } else if(phoneConfig.ui == '1'){
                            genPcUi(phone,  '<span style="font-size: 12px">'+ (res.result.tips || errTxt)+'</span>', '', phoneConfig.ui);
                        } else {
                            genPcUi(phone, res.result.tips || errTxt, '', phoneConfig.ui);
                        }
                }
            },function(){
                lock = false;
                genPcUi(phone,'',errTxt, phoneConfig.ui);
            });
        };
    }

    function mobileBindTel(phone, phoneConfig) {
        var hrefOrg = null;
        phone.ontouchstart = function () {
            if (phone.querySelector('a')) {
                hrefOrg = phone.querySelector('a').href;
                phone.querySelector('a').onclick = function () {
                    event.preventDefault();
                };
            }
            event.preventDefault();
        };
        phone.ontouchend = fetchTel;

        function fetchTel() {

            if (lock) {
                return;
            }
            lock = true;
            var tel = '';
            var errTxt = '当前楼盘正忙,请稍后再拨';
            getPhone(phoneConfig.params, phoneConfig.isMobile,function (res) {
                lock = false;
                if (+res.result.status == 0) {
                    tel = 'tel:' + res.result.num;
                    doCall(tel);
                } else if (+res.result.status == 1) {
                    alert(res.result.tips || errTxt);
                } else if (+res.result.status == 2) {
                    tel = hrefOrg;
                    doCall(tel);
                }
            },function(){
                lock = true;
            });

            function doCall(tel) {
                if (!phone.querySelector('a')) {
                    phone.innerHTML += '<a style="visibility:hidden;" href="' + tel + '"></a>';
                } else {
                    phone.querySelector('a').href = '' + tel;
                }
                requestAnimationFrame(function () {
                    phone.querySelector('a').onclick = null;
                    var evt = document.createEvent('MouseEvents');
                    evt.initMouseEvent('click', false, true);
                    phone.querySelector('a').dispatchEvent(evt);
                });
            }
        }
    }

    function genPcUi(phone, txt, subTxt, ui,time) {
        var fragment = document.createDocumentFragment();
        var main = document.createElement('div');
        var classSuffix = (ui?ui:'none')+(time?'_'+time:'')
        main.setAttribute("class", "pcLittlePhoneMain pcLittlePhoneMainUi"+classSuffix)
        var icon = '<i class="icon-ea65" style="margin-right: 9px;"></i>';
        var sub = document.createElement('div');
        sub.setAttribute("class", "pcLittlePhoneSub pcLittlePhoneSubUi"+classSuffix)
        phone.setAttribute("class", phone.getAttribute('class')+" pcLittlePhoneWrap pcLittlePhoneWrapUi"+classSuffix)
        if (ui == 2) {
            var href = window.location.href;
            //截取掉from码
            if(href.indexOf('ditu')>-1) {
                phone.parentNode.style.cssText = 'height:92px;display:flex;align-items:center;';
            }
        } else if (ui == 4) {
            try {
                phone.querySelector('.num').innerHTML = txt;
                phone.querySelector('.num').style.fontSize = '1.8rem';
                phone.querySelector('.ui-line-overflow').innerHTML = subTxt;
            } catch (e) {
                phone.querySelector('.tel-info').querySelector('span').innerHTML = txt;
                phone.querySelector('.tel-info').querySelector('.tel-desc').innerHTML = subTxt;
            }
            return;
        } else if (ui == 5) {
            if(txt ==""){ //接口异常，显示提示文字
                phone.querySelector('.num').innerHTML = subTxt;
                phone.querySelector('.num').style.fontSize = '18px';
            }else{
                phone.querySelector('.num').innerHTML = txt;
                phone.querySelector('.num').style.fontSize = '24px';
            }
            phone.querySelector('.num').style.cssText +='white-space: nowrap;'
        }

        if(ui!=5){
            sub.innerHTML = subTxt;
            main.innerHTML = icon + txt;
            phone.innerHTML = '';
            if(!ui&&time == 'after'){
                main.querySelector('i').style.fontSize = '28px';
            }

            fragment.appendChild(main);
            fragment.appendChild(sub);
            phone.appendChild(fragment);
        }else{
            main.innerHTML = txt;
        }
    }
}

initTelPage();

})(jQuery);
XF.nameSpace('XF.ImgLazyLoad');
;(function ($,_lazy){
	_lazy.DelayModular = function(option){
		var self = this;
		self.op = {
			imgContainer :'',
			duration     : 200,
			attrName     :'imglazyload-src'
		};
        self._isWebPSupport = false;
		$.extend(self.op,option||{});
        self.isWebpSupport();
		self.init();
		self.handleScroll();
	};
    _lazy.DelayModular.prototype.isWebpSupport = function () {
        var self = this,
            isSupport = window.localStorage && window.localStorage.getItem("webpsupport"),
            isIE = navigator.userAgent && /MSIE/.test(navigator.userAgent);

        isSupport = isIE ? false : isSupport;
        if(null === isSupport && !isIE){
            var img = new Image();
            img.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
            if(img && 2 === img.width && 2 === img.height){
                isSupport = true;
            }
        }
        window.localStorage && window.localStorage.setItem("webpsupport",isSupport);
        self._isWebPSupport = "true" === isSupport;
    };
	_lazy.DelayModular.prototype.init = function(){
		var self = this;
		self.imgs = $(self.op.imgContainer).find("img["+self.op.attrName+"]");
		self.timer = null;
		if(self.imgs.length){
			self.isDelayImages();
		}
	}
    _lazy.DelayModular.prototype.handleScroll = function(){
    	var self = this;
    	if(self.imgs.length){
	    	$(window).on('scroll.allSite',function(){
	           self.isDelayImages();
	    	});
    	}
    }
    _lazy.DelayModular.prototype.isDelayImages = function(){
    	var self = this;    	
    	if(self.timer){
            clearTimeout(self.timer);
        }
        self.timer = setTimeout(function(){
	        self.imgs.each(function(index){
	         	var _self = $(this);
	         	var _win = $(window);
	         	var scrollTop = _win.scrollTop();
	         	var winH = _win.height();
	         	var triggerPos = _self.offset().top;
	         	var imgHei  = _self.outerHeight();
         		if((winH > triggerPos - scrollTop) &&(scrollTop < triggerPos + imgHei)){
         			var delaySrc = _self.attr('imglazyload-src');
                    if(delaySrc && self._isWebPSupport){
                        delaySrc && (/pic1\.ajkimg\.com(.*)\.(jpg|png)/.test(delaySrc)) && !(delaySrc.match(/\?t=(\d)/i) > 0) && (delaySrc += "?t=5");
                    }
                    _self.attr('src',delaySrc);
                    _self.removeAttr("imglazyload-src");
         		}
	        });
        },self.duration);
    }
})(jQuery,XF.ImgLazyLoad);;(function($) {

    APF.Namespace.register("aifang.loupan.view.ConsultantPhoneNumber");

    aifang.loupan.view.ConsultantPhoneNumber = function(params) {
        var self = this;
        self.input = params.input_class_name;
        self.loupan_id = params.loupan_id;
        self.ajax_url = "/aifang/web/loupan/ajax/PhoneConsultant/";
        if(self.input) {
            self.replace_ids = self.get_replace_ids(self.input);
            self.replace_phone(self.replace_ids);
        }
    };
    aifang.loupan.view.ConsultantPhoneNumber.prototype.get_replace_ids = function(class_name) {
            var rs = [];
            var obj = $('.'+class_name);
            if(obj.length > 0) {
                for(var k=0;k<obj.length;k++) {
                    rs[k]=obj.eq(k).val();
                }
            }
            return rs;
    };

    aifang.loupan.view.ConsultantPhoneNumber.prototype.replace_phone = function(list){
        var self = this;
        var data = {
            'r' : Math.random(),
            'loupan_id' : self.loupan_id
            };
        $.ajax({
            type: "POST",
            url: self.ajax_url,
            cache : false,
            data: data,
            dataType: 'json',
            success: function(rs){
                if(rs.switch_status == 'on' && rs.number) {
                    for(var k=0;k<self.replace_ids.length;k++) {
                        $(self.replace_ids[k]).html(rs.number);
                    }
                }
           }
        });
    };
})(jQuery);
;
(function ($) {
	"use strict";
	XF.nameSpace('XF.CountDown');
	XF.CountDown = function (op) {
		var self = this;
		self.op = $.extend({}, XF.CountDown._default, op);
		self._init();
	};
	XF.CountDown._default = {
		timerST : '',//“计时器”选择器，String
		dayST   : '.time-day',//“天”选择器，String
		hourST  : '.time-hour',//“时”选择器，String
		minuteST: '.time-minute',//“分”选择器，String
		secondST: '.time-second',//“秒”选择器，String
		endTime : null,//结束时间，Date
    plusTime: null, // 剩余时间
	};
	XF.CountDown.prototype._init = function () {
		var self = this, op = self.op;
		//获取DOM“天，时，分，秒”
		var $timer = $(op.timerST),
			$day = $timer.find(op.dayST),
			$hour = $timer.find(op.hourST),
			$minute = $timer.find(op.minuteST),
			$second = $timer.find(op.secondST);
		//设置“op.interval”间隔每秒（1000ms）执行
		op.interval = setInterval(function () {
			//“leftTime”时间差，单位毫秒，结束时间减去当前时间

      var leftTime = (op.plusTime > 0) ? Date.parse(op.plusTime) : (Date.parse(op.endTime) - Date.parse(new Date()));//兼容低版本IE浏览器，用Date.parse()函数替代getTime(),并且使用YYYY/MM/DD日期字符串格式（ie上不支持YYYY-MM-DD）
			if (leftTime > 0) {
				//将时间差，转为“天，时，分，秒”
				var leftSecond = parseInt(leftTime / 1000),
					day = Math.floor(leftSecond / (60 * 60 * 24)),
					hour = Math.floor((leftSecond - day * 24 * 60 * 60) / 3600),
					minute = Math.floor((leftSecond - day * 24 * 60 * 60 - hour * 3600) / 60),
					second = Math.floor(leftSecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
				//改变“天，时，分，秒”对应DOM元素的文本，小于10，前面补“0”
				$day.text(day < 10 ? "0" + day : day);
				$hour.text(hour < 10 ? "0" + hour : hour);
				$minute.text(minute < 10 ? "0" + minute : minute);
				$second.text(second < 10 ? "0" + second : second);
			} else {
				//倒计时结束，清除“op.interval”，并触发自定义“over”事件（在实例对象上通过on方法绑定）
				clearInterval(op.interval);
				$(self).trigger('over');
			}
		}, 1000);
	};
})(jQuery);;(function ($,module) {
    var Ifx = function () {
    };
    Ifx.prototype = {
        constructor:Ifx,
        add:function (info) {
            var url,
                id;
            if($.type(info) === 'string'){
                url = info;
            }else if($.type(info) === 'object'){
                url = info.url;
                id = info.id;
            }
            $.getScript(url, function() {
                if(id){
                    $(document).trigger('ifxload',{
                        id:id
                    });
                }
            });
        }
    };
    module.ifx = new Ifx();
})(jQuery,XF.nameSpace('XF.module'));;
(function ($) {
	"use strict";
	XF.nameSpace('XF.Switch');
	XF.Switch = function (op) {
		var self = this;
		self.op = $.extend({}, XF.Switch._default, op);
		self._isWebPSupport = false;
		self.isWebpSupport();
		self._init();
	};
	XF.Switch._default = {
		switchST : '', //Switch selector
		clipST   : '.clip', //clip selector
		conST    : '.con', //con selector
		itemST   : '.item', //item selector
		prevST   : '.prev', //prev selector
		nextST   : '.next', //next selector
		pnavST   : '.pnav', //pnav selector
		effect   : 'slide', //slide,fade,none
        mouseLock: false, //当视频播放时，将禁用掉鼠标事件，此时必须点击才能出发鼠标事件
		event    : 'click', //click,mouseenter
		current  : 'cur',
		circle   : false, //true,false
		vertical : false, //true,false
		auto     : false, //true,false
		start    : 0, //int(0=1st)
		duration : 400, //millisecond
		interval : 5000, //millisecond
		switchNum: 1, //Number
		clipNum  : 1, //Number
		slideMode:'single'//'single'：单帧滑一个item,'multi':单帧滑多个item,数量由switchNum指定

	};
	XF.Switch.prototype._init = function () {
		var self = this, op = self.op;
		/*相关元素获取*/
		op.sw = $(op.switchST);
		op.clip = op.sw.find(op.clipST);
		op.con = op.clip.find(op.conST).css({'position': 'relative'});
		op.item = op.con.find(op.itemST);
		op.prev = op.prevST == '.prev' ? op.sw.find(op.prevST) : $(op.prevST);
		op.next = op.nextST == '.next' ? op.sw.find(op.nextST) : $(op.nextST);
		op.pnav = op.pnavST == '.pnav' ? op.sw.find(op.pnavST) : $(op.pnavST);
		op.itemLen = op.item.length;
		if(op.slideMode == 'single'){
			op.switchNum > op.clipNum && (op.switchNum = op.clipNum);
		}
		op.itemLen < op.clipNum && (op.itemLen = op.clipNum);
		if (op.effect != 'slide') {
			op.switchNum = 1;
			op.clipNum = 1;
		}
		/*切换到边界时，添加的禁用类名*/
		op.prevDisClass = $.trim(op.prevST).match(/\w\S*$/) + '-dis';
		op.nextDisClass = $.trim(op.nextST).match(/\w\S*$/) + '-dis';
		/*定义合法的开始Num*/
		op.start = parseInt(op.start, 10);
		op.start = (op.start >= 0 && op.start < op.itemLen) ? op.start : 0;
		if (op.effect == 'slide') {
			/*垂直滚动，水平滚动*/
			op.vertical || op.item.css({'float': 'left'});
			op.leftOrTop = op.vertical ? 'top' : 'left';
			op.widthOrHeight = op.vertical ? op.item.outerHeight(true) : op.item.outerWidth(true);
			if(op.slideMode == 'single'){
				op.conSize = op.widthOrHeight * op.itemLen;
			}else if(op.slideMode == 'multi'){
				var realpage = Math.ceil(op.itemLen/op.switchNum);
				if(op.itemLen>op.switchNum){
					op.itemLen = realpage*op.switchNum;
				}
				op.conSize = op.widthOrHeight * op.switchNum * realpage;
			}
			op.vertical ? op.con.css({'height': op.conSize}) : op.con.css({'width': op.conSize});
		} else if (op.effect == 'fade') {
			/*渐隐渐现（无效果则是时间为0）*/
			op.item.not(op.item.eq(op.start).show()).hide().css({'position': 'absolute','visibility': 'hidden'});
		} else {
			op.item.not(op.item.eq(op.start).show()).hide().css({'visibility': 'hidden'});
			op.effect = 'none';
			op.duration = 0;
		}
		/*设置记时，用于自动播放*/
		function setTimer() {
			op.timer = setInterval(function () {
				op.showpage >= op.itemLen - op.clipNum ? self.switchTo(0) : self.next();
			}, op.interval);
		}

		function clearTimer() {
			clearInterval(op.timer);
		}

		clearTimer();
		/*不满足运行情景则停止运行，返回值用于用户是否隐藏翻页导航*/
		if (op.itemLen <= op.clipNum) {
			op.stopRun = true;
			self.switchTo(0);
			return;
		}
		self.switchTo(op.start);
		/*绑定prev，next，pnav按钮事件*/
		op.prev.off('click.switch').on('click.switch', function () {
			$(this).hasClass(op.prevDisClass) || self.prev();
		});
		op.next.off('click.switch').on('click.switch', function () {
			$(this).hasClass(op.nextDisClass) || self.next();
		});
		op.pnav.each(function (index) {
			$(this).off(op.event + '.switch').on(op.event + '.switch', function () {
                !op.mouseLock && !$(this).hasClass('cur') && self.switchTo(index);
			});
			op.event === 'mouseenter' && $(this).off('click.switch').on('click.switch', function () {
				!$(this).hasClass('cur') && self.switchTo(index);
				if(op && op.clickSoj){//点击小图发码
					XF.Soj.send('',{action:op.clickSoj});
				}
			});
		});
		/*自动播放*/
		if (op.auto) {
			setTimer();
			op.sw.off('mouseenter.switch mouseleave.switch').on({
				'mouseenter.switch': function () {
					clearTimer();
				},
				'mouseleave.switch': function () {
					setTimer();
				}
			});
		}
	};
	/**
	 * [执行切换函数]
	 * 可绑定函数 playBefore,playAfter
	 */
	XF.Switch.prototype._play = function (showpage, isprev, isnext) {
		var self = this, op = self.op, targetItem = null, targetPos = {}, k = 0;
		if ($(self).trigger('playBefore') !== false) {
			//确定实际切换点showpage
			if (showpage === null) {
				showpage = isprev ? op.showpage - op.switchNum : op.showpage + op.switchNum;
			} else {
				showpage = isNaN(showpage) ? 0 : showpage; // * op.switchNum;
				if (showpage == op.showpage) {
					return;
				}
			}
			//左右循环切换
			if(op.circle){
				showpage < 0 && (showpage = op.itemLen - op.clipNum);
				showpage > op.itemLen - op.clipNum && (showpage = 0);
			} else {
				showpage < 0 && (showpage = 0);
				showpage > op.itemLen - op.clipNum && (showpage = op.itemLen - op.clipNum);
				//添加删除边界禁用类名
				showpage == 0 ? op.prev.addClass(op.prevDisClass) : op.prev.removeClass(op.prevDisClass);
				showpage == op.itemLen - op.clipNum ? op.next.addClass(op.nextDisClass) : op.next.removeClass(op.nextDisClass);
			}

			//change img src
			for (; k < op.clipNum + op.switchNum; k++) {
				if (showpage + k >= op.itemLen) {
					break;
				}
				self._changeSrc(showpage + k);
			}
			//执行动画效果
			if (op.effect == 'slide') {
				targetPos[op.leftOrTop] = -op.widthOrHeight * showpage;
				op.con.stop().animate(targetPos, op.duration);
			} else if (op.effect == 'fade' || op.effect == 'none') {
				targetItem = op.item.eq(showpage);
				op.item.not(targetItem).stop().fadeOut(op.duration, function() {
                    $(this).css("visibility", "hidden");
                });
				targetItem.fadeIn(op.duration, function() {
                    $(this).css("visibility", "visible");
                });
			}
			/*添加切换导航当前类名*/
			op.pnav.removeClass(op.current);
			op.pnav.eq(Math.ceil(showpage / op.switchNum)).addClass(op.current);
			/**/
			op.showpage = showpage;
			$(self).trigger('playAfter');



		}
	};

    XF.Switch.prototype.lockMouse = function(lock){
        this.op.mouseLock = lock;
    }

	XF.Switch.prototype.isWebpSupport = function () {
        var self = this,
            isSupport = window.localStorage && window.localStorage.getItem("webpsupport"),
            isIE = navigator.userAgent && /MSIE/.test(navigator.userAgent);

        isSupport = isIE ? false : isSupport;
        if(null === isSupport && !isIE){
            var img = new Image();
            img.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
            if(img && 2 === img.width && 2 === img.height){
                isSupport = true;
            }
        }
        window.localStorage && window.localStorage.setItem("webpsupport",isSupport);
        self._isWebPSupport = "true" === isSupport;
    };

	/**
	 * [changeSrc 动态载入图片]
	 */
	XF.Switch.prototype._changeSrc = function (index) {
		var self = this, op = self.op, thisImg = op.item.eq(index).find('img'), i = 0;
		for (; i < thisImg.length; i++) {
			var delaySrc = thisImg.eq(i).data('src');
			if(delaySrc && self._isWebPSupport){
                delaySrc && (/pic1\.ajkimg\.com(.*)\.(jpg|png)/.test(delaySrc)) && !(delaySrc.match(/\?t=(\d)/i) > 0) && (delaySrc += "?t=5");
            }
			thisImg.eq(i).attr('src') || thisImg.eq(i).attr('src', delaySrc);
		}
	};
	/**
	 * [switchTo 切换到指定帧(每帧的item数目等于switchNum)]
	 */
	XF.Switch.prototype.switchTo = function (showpage) {
		this._play(showpage, false, false);
	};
	/**
	 * [prev 切换到上一帧]
	 */
	XF.Switch.prototype.prev = function () {
		this._play(null, true, false);
	};
	/**
	 * [next 切换到下一帧]
	 */
	XF.Switch.prototype.next = function () {
		this._play(null, false, true);
	};
})(jQuery);
;
(function ($) {
    function tab(hd, bd, mouseevent) {
        hd.each(function (index) {
            var thishd = $(this), thisbd = bd.eq(index);
            thishd.on(mouseevent, function () {            	
                bd.not(thisbd).hide();
                thisbd.show();
            });
        });
    }
    var itemMod = $('.info-item-mod'), itemHd = itemMod.find('.item-hd .area-item'), itemBd = itemMod.find('.item-bd .item');
    $(itemBd).first().show();
    tab(itemHd, itemBd, "mouseenter");

    // 调整下 UI 和交互
    if ($('#navs')) {
		var showIdx = 0;
		$('.nav-content').hide();
		$('#navs li').eq(showIdx).addClass('li-hover');
		$('.nav-content').eq(showIdx).show();
		$('.nav-content label').hide();
		$('#navs ~ .nav-content').addClass('region-ajk');
		$('#navs li').mouseover(function() {
			$(this).siblings().removeClass('li-hover');
			$(this).addClass('li-hover');
			showIdx = $(this).index();
			var select = $('.nav-content').eq(showIdx);
			$('.nav-content').hide();
			select.show();
		});
	}
})(jQuery);  
;
(function ($) {
	XF.nameSpace('XF.AlbumTab');
	//	大图小图组合切换
	XF.AlbumTab = function (ops) {
		var self = this;
		self.ops = $.extend({}, XF.AlbumTab._default, ops);
		self._init();
	};
	XF.AlbumTab._default = {
		swBigOp    : null,
		swSmallOp  : null,
		tabST      : '',
		tabIndex   : 0,
		tabCurClass: 'cur',
		autoHeight : true,
		imgSrc     : null,
		imgDes     : null
	};
	XF.AlbumTab.prototype._init = function () {
		var self = this, ops = self.ops;
		ops.ie6 = /MSIE 6/.test(navigator.userAgent);
		ops.swBig = new XF.Switch(ops.swBigOp);
		ops.swSmall = new XF.Switch(ops.swSmallOp);
		ops.initHeight = ops.swBig.op.clip.height();

	    this.eventHandler();
	};

    XF.AlbumTab.prototype.eventHandler = function (){
        var self = this,
            ops = self.ops,
            swBig = ops.swBig;

        if (ops.tabST) {
			ops.tab = $(ops.tabST);
			ops.tab.each(function (index) {
				$(this).on('click.album', function () {
					ops.tab.not($(this)).removeClass(ops.tabCurClass);
					$(this).addClass(ops.tabCurClass);
                    $(self).trigger('click.album', index);
					self.create(index);

				});
			});
			ops.tab.eq(ops.tabIndex).trigger('click.album');
		} else {
			self.create(0);
		} 

        swBig.op.con.on('click', '.item-video', function(){
            var id = $(this).data('id'),
                duration = $(this).data('duration');

            $(self).trigger('click.video', { vid: id, duration: duration }); 
        });
    }

	XF.AlbumTab.prototype.create = function (index) {
		var self = this, ops = self.ops;
		/*生成Html结构，生成switch对象*/
		var thisData = ops.imgSrc[index], i = 0, bigHtml = '', smallHtml = '',
            isVideo = thisData.type === 'video',
            videoHtml = isVideo ? '<i class="icon-video"></i>' : '',
            className = isVideo ? 'item item-video' : 'item',
            descFunc = ops.imgDes && thisData.image_des ? function (str) {
                return  '<span class="tit-bg"></span><div class="photo-des"><!-- -->' + str + '</div>';
            } : function () { return '' };

        self.isVideo = isVideo;
		for (; i < thisData.big.length; i++) {
            var imgId = thisData.image_id || [],
                imgDes = thisData.image_des || [];
			bigHtml += '<div class="' + className + '" data-id="' + imgId[i] + '" data-duration="' + (thisData.image_duration || [])[i] + '">' + videoHtml + '<img data-src="' + thisData.big[i] + '" />' + descFunc(imgDes[i]) + '</div>';
			smallHtml += '<div class="item"><a href="javascript:void(0);"><img data-src="' + thisData.small[i] + '" /></a></div>';
		}
		ops.swBig.op.con.html(bigHtml);
		ops.swSmall.op.con.html(smallHtml);
		ops.swBig = new XF.Switch(ops.swBigOp);
		ops.swSmall = new XF.Switch(ops.swSmallOp);

		/*加载图片,改变高度*/
		ops.autoHeight && self.changeHeight();
		/*加载图片描述时,改变描述背景高度*/
		ops.imgDes && self.changeDesHeight();
		$(ops.swBig).on('playAfter', function () {
			ops.autoHeight && self.changeHeight();
			ops.imgDes && self.changeDesHeight();
			/*大小图切换关联*/
			var bigSp = ops.swBig.op.showpage, smallSp = ops.swSmall.op.showpage, smallCn = ops.swSmall.op.clipNum;
			if (bigSp >= smallSp + smallCn) {
				ops.swSmall.switchTo(bigSp);
			} else if (bigSp < smallSp) {
				ops.swSmall.switchTo(bigSp);
			}
		});
		$(ops.swBig).on('playAfter playBefore', function (e) {
            $(self).trigger(e.type);
        });
	};
	XF.AlbumTab.prototype.changeHeight = function () {
		var self = this, ops = self.ops, thisImg = ops.swBig.op.item.eq(ops.swBig.op.showpage).find('img'),
			clip = ops.swBig.op.clip, clipWidth = clip.width(), prev = ops.swBig.op.prev, next = ops.swBig.op.next;
		var setTime = setInterval(function () {
			if (thisImg.height() > 50) {
				clearInterval(setTime);
				ops.ie6 && thisImg.width('auto') && thisImg.width() > clipWidth && thisImg.width(clipWidth);
				change(thisImg.height());
			}
		}, 200);

		function change(thisHeight) {
            var h = thisHeight > ops.initHeight ? thisImg.height() : ops.initHeight;
            clip.add(prev).add(next).height(h);
			$(window).trigger('resize.modal');
		}
	};
	XF.AlbumTab.prototype.changeDesHeight = function () {
		var self = this, ops = self.ops,
			thisDes = ops.swBig.op.item.eq(ops.swBig.op.showpage).find('.photo-des'),
			thisBg = ops.swBig.op.item.eq(ops.swBig.op.showpage).find('.tit-bg');
		var setTime = setInterval(function () {
			clearInterval(setTime);
			if(thisDes.height() > 0){
				thisBg.height(thisDes.height()+9);
			}			
		}, 200);
	};
})(jQuery);
APF.Namespace.register("Web.Component.Loupan");
(function ($, loupan) {
	loupan.FreeCall = function() {
		var btn_mfth = $('#j-btn-mfth,.j-btn-mfth'), btn_ljth = $('#j-btn-ljth,.j-btn-ljth'), btn_yyhd = $('#j-btn-yyhd,.j-btn-yyhd');
		var btn_mfth2 = $('#j-btn-mfth2,.j-btn-yyhd2'), btn_ljth2 = $('#j-btn-ljth2,.j-btn-yyhd2'), btn_yyhd2 = $('#j-btn-yyhd2,.j-btn-yyhd2');
		var btn_ljth_layer = $('#j-btn-ljth-layer,.j-btn-ljth-layer'), btn_lhyy_layer = $('#j-btn-ljyy-layer,.j-btn-ljyy-layer');

		var cookie_tel = APF.Utils.getCookie('xf_400_free');

		/*免费通话跟随浮层*/
		var fcLayer = $('#j-freecall').appendTo('body');
		var trgEle = $('#j-triggerlayer-b');
		if (!trgEle.length) {
			trgEle = $('#j-triggerlayer');
		}
		$(window).on('scroll.call', function () {
			checkLayer();
		});
		checkLayer();
		function checkLayer() {
			var scrTop = $(window).scrollTop(), trgTop = (trgEle.length > 0 ? trgEle.offset().top : 100);
			scrTop > trgTop ? fcLayer.show() : fcLayer.hide();
		}

		/* 按钮显示（免费电话，立即通话，预约回电） */
		var nowHours = new Date().getHours();
		if (!XF.Vars.showReserv) {
			if (cookie_tel) {
				btn_ljth.addClass('make-call2').add(btn_ljth2.addClass('make-call2')).show();
			} else {
				btn_mfth.addClass('make-freecall2').add(btn_mfth2.addClass('make-freecall2')).show();
			}
		} else {
			//预约电话
			btn_yyhd.addClass('order-callback2').add(btn_yyhd2.addClass('order-callback2')).show();
		}

	}
	/*修复fixed父元素不跟随滚动轴的问题*/
 	var timer = null;
 	$(window).on('load resize',function(){
 		if(!timer){
 			clearTimeout(timer);
 		}
 		timer = setTimeout(function(){
 			var window_width=$(window).width();
 			$("#intro").css("width",window_width < 1080 ? window_width : '');
 		},250)
 	});	
})(jQuery, Web.Component.Loupan);
;(function($){
    var titleA      = '立即通话';
    var titleB      = '预约回电';
    var errMsgA     = '手机号码不能为空';
    var errMsgB     = '手机号码格式错误';
    var tipMsgA     = '请输入手机号';
    var tipMsgB     = '请输入您的手机号码';
    var tipMsgC     = '选择您方便接听的时间';
    var freeUrl     = '/aifang/web/loupan/ajax/phoneconnect/';//立即通话（原免费通话）
    var reserveUrl  = '/aifang/web/loupan/ajax/phonereserve/';//预约回电
    var body        = $('body');
    var bdQrcode = $('#qrcode-call');  // 扫码拨号
    var bdOne       = $('#free-step-one');//通话步骤一
    var bdTwo       = $('#free-step-two');//通话步骤二
    var bdBack      = $('#free-callback');//预约电话
    var bdMax       = $('#free-repeat');//免费通话过多
    var bdResult    = $('#call-result');//预约结果
    var entrance    = $('#newcall-entrance');//入口
    var entInput    = entrance.find('.new-cellphone');//入口号码输入框
    var enConfirm   = entrance.find('#enConfirm');//入口通话按钮
    
    var cookie_tel  = APF.Utils.getCookie('xf_400_free');
    var base_domain = $('#NewCall_domain').val();//最上级域名

    // 扫码拨打
    var qrcodeCall = new XF.Modal({
      modalClass: 'modal-qrcode',
      title: '',
      bd: bdQrcode,
      width: '548',
      height: '258'
    });
    //步骤一
    var stepOne = new XF.Modal({
        modalClass: 'modal-custom',
        title     : titleA,
        bd        : bdOne,
        width     : '560',
        height    : '455'
    });
    //步骤二
    var stepTwo = new XF.Modal({
        modalClass: 'modal-custom',
        title     : titleA,
        bd        : bdTwo,
        width     : '560',
        height    : '440'
    });
    //拨打过多
    var callMax = new XF.Modal({
        modalClass: 'modal-custom',
        title     : titleA,
        bd        : bdMax,
        width     : '560',
        height    : '320'
    });
    //预约通话
    var callBK = new XF.Modal({
        modalClass: 'modal-custom',
        title     : titleB,
        bd        : bdBack,
        width     : '560'        
    });
    //预约结果
    var callRT = new XF.Modal({
        modalClass: 'modal-custom',
        title     : titleB,
        bd        : bdResult,
        width     : '560',
        height    : '400'
    });
    var xfCodeDom = {
        phone     : $('.new-call-v2 .c-phone'),
        imgCode   : $('.new-call-v2 .img-code-int'),
        smsCode   : $('.new-call-v2 .sms-code-int'),
        msgBox    : $('.new-call-v2 .msg-box'),
        msgText   : $('.new-call-v2 .msg-box span'),
        isShow    : $('.new-call-v2 .j-is-show'),
        isSmsShow : $('.new-call-v2 .j-sms-show'),
        refreshBtn: $('#free-step-one .refresh-btn'),
        verfiyBtn : $('#free-step-one .send-sms-btn'),
        backCallrefreshBtn :$('#free-callback .refresh-btn'),
        backCallverfiyBtn  :$('#free-callback .send-sms-btn')
    };
    var timeDelayStatus;
    var timeDelay;
    var checkList = [],
        _errConfig = {
            'phone'    : {'defaults':'请输入您的手机号码','empty':'手机号码不能为空！','format':'请正确输入手机号！'},
            'code'     : {'defaults':'请输入图片码','empty':'图片码不能为空','format':'图片码错误'},
            'smscode'  : {'defaults':'请输入短信验证码','empty':'短信验证不能为空','format':'短信验证码错误'}
        };
    // 请求拨号二维码
    function getQrcode() {
      var qrBox = $('.wchar-qr'),
        params = {
          'from':'loupan_view',
          'loupan_id': XF.Vars.loupanId
        };
      if(window.QrCodeImg) {
        imgUrl = window.QrCodeImg;
        $('#qrcode-call').find('img').attr('src', imgUrl);
      } else {
        $.ajax({
          url: __base_url + '/aifang/web/ajax/getQrCode/',
          type: 'GET',
          dataType: 'json',
          data: params,
          context: qrBox,
          success: function(data){
            if(data.status == true) {
              imgUrl = data.image_url;
              window.QrCodeImg = imgUrl;
              if(imgUrl){
                $('#qrcode-call').find('img').attr('src', imgUrl);
              }
            }
          },
          error:function() {
          }
        });
      }
    }
     // 清空数据
    function clearDataInput(){
        var phoneDa = $('.xf-verify-module').find('.c-phone');
        var verfiyCodeDa = $('.xf-verify-module').find('.img-code-int');
        var smsCodeDa = $('.xf-verify-module').find('.sms-code-int');
        var msgBoxDa = $('.xf-verify-module').find('.msg-box');
        phoneDa.removeClass('int-err');
        verfiyCodeDa.attr('placeholder',_errConfig.code.defaults);
        verfiyCodeDa.val('');
        verfiyCodeDa.removeClass('int-err');        
        smsCodeDa.attr('placeholder',_errConfig.smscode.defaults);
        smsCodeDa.val('');
        smsCodeDa.removeClass('int-err');
        msgBoxDa.hide();
     }  
    // 手机 图片验证码 短信验证码
    // 手机号码的验证(免费通话和预约回电通用验证)
    checkList['phone'] = function(){
        var dom = xfCodeDom.phone,
            val = $.trim(dom.val()),
            msgPhone = xfCodeDom.msgBox.eq(0),
            msg = xfCodeDom.msgText.eq(0);
            val = val == _errConfig['phone'].defaults ? '':val;
        if(val != '' && !XF.Validate.phoneMobile(val)){
            msgPhone.show();
            dom.addClass('int-err');
            msg.html(_errConfig['phone'].format);
            return false;
        }else if(val ==""){
            msgPhone.show();
            dom.addClass('int-err');
            msg.html(_errConfig['phone'].empty);
            return false;
        }else{
            cookie_tel = val;
            dom.removeClass('int-err');
            msgPhone.hide();
            return true;
        }
    }
    // 图片验证码(免费通话和预约回电通用验证)
    checkList['imgCode'] = function(){
       var  dom = xfCodeDom.imgCode,
            val = $.trim(dom.val()),
            msgCode = xfCodeDom.msgBox.eq(1),
            msg = xfCodeDom.msgText.eq(1);
            val = val == _errConfig['code'].defaults ? '':val;            
        if (val!='' && val.length!=4) {
            msgCode.show();
            dom.addClass('int-err');
            msg.html(_errConfig['code'].format);
            return false;
        } else if(val==''){
            msgCode.show();
            dom.addClass('int-err');
            msg.html(_errConfig['code'].empty);
            return false;
        }else {
            dom.removeClass('int-err');
            msgCode.hide();
            return true;
        }
    }
    // 短息验证码(免费通话和预约回电通用验证)
     checkList['smsCode'] = function(){
        var dom = xfCodeDom.smsCode,
            val = $.trim(dom.val()),  
            msgSms= xfCodeDom.msgBox.eq(2),
            msg = xfCodeDom.msgText.eq(2); 
            val = val == _errConfig['smscode'].defaults ? '':val;
            if(val != '' && !XF.Validate.smsCode(val)){
                msgSms.show();
                dom.addClass('int-err');
                msg.html(_errConfig['smscode'].format);
                return false;
            }else if(val ==""){
                msgSms.show();
                dom.addClass('int-err');
                msg.html(_errConfig['smscode'].empty);
                return false;
            }else{
                dom.removeClass('int-err');
                msgSms.hide();
                return true;
            }
     }
     // 图片验证码是否启用(免费通话和预约回电通用验证)
     checkList['isShowCode'] = function(){
        if(xfCodeDom.isShow.is(':visible')){
            return checkList['imgCode']();
        }else{
            return true;
        }
     }
     //短信验证码是否启用   
     checkList['isShowSmsCode'] = function(){
        if(xfCodeDom.isSmsShow.is(':visible')){
            return checkList['smsCode']();
        }else{
            return true;
        }
     }   
      //刷新图片验证函数 
     function refreshCodeImg(obj){
         var newStamp = $.now(), newSrc,
            codeImg  = obj.prev();
            newSrc = codeImg.attr('src').substr(0,codeImg.attr('src').length-13) + newStamp;
            codeImg.attr('src',newSrc);
     }
     // 发送短信验证函数
     function verfiyPhone(obj, inputVal,time) {
        var mobieData = {
            phone:inputVal,
            guid :XF.Vars.Guid,
            type :15
        };
        var reRefeshBtn;
        if(xfCodeDom.isShow.is(':visible')){
            mobieData.imagecode = $.trim(xfCodeDom.imgCode.val());
        }
        $.ajax({
            url: __base_url + '/vcode/mobilecode/',
            type: 'post',
            dataType: 'json',
            data: mobieData,
            success : function(data){
                    var msgPhone,
                        phoneText,
                        msgImg,
                        imgText;
                        msgPhone = xfCodeDom.msgBox.eq(0),
                        phoneText = xfCodeDom.msgText.eq(0),
                        msgImg = xfCodeDom.msgBox.eq(1),
                        imgText = xfCodeDom.msgText.eq(1);
                    if(data.rst > 0){
                        verfiyCountdown(obj, time);
                        msgPhone.hide();
                        msgImg.hide();
                    }else if(data.rst==-3){
                        xfCodeDom.isShow.show();
                        xfCodeDom.imgCode.addClass('int-err');
                        msgImg.show();
                        imgText.html(data.msg);
                    }else{
                        if(xfCodeDom.isShow.is(':visible')){
                            msgImg.show();
                            xfCodeDom.imgCode.addClass('int-err');
                            imgText.html(data.msg);
                        }else{
                            msgPhone.show();
                            msg.html(data.msg);
                        }
                    }
                }
        });       
    }
    // 倒计时函数
     function verfiyCountdown(obj, time) {
        if (time == 0) {
            obj.removeAttr('disabled');
            obj.removeClass('f-getcode-dis');
            obj.text('发送短信验证码');            
            time = time;
            timeDelayStatus = false;
            if(obj.hasClass('free-callback-send')){
               backCallgetverfiyCode();
            }else{
               getverfiyCode();
            }
        } else {
            obj.attr('disabled', 'disabled');
            obj.addClass('f-getcode-dis');
            obj.text(time + '秒后重新发送');
            if(obj.hasClass('free-callback-send')){
               obj.off('click.backxfsend');
           }else{
               obj.off('click.xfsend');
           }
            time--;
            timeDelay = setTimeout(function() {
                verfiyCountdown(obj, time);
            }, 1000);
            timeDelayStatus = true;
        }
    }
    //清空倒计时（免费通话和立即通话）
    function clearTimeDelayHandle(){
        if(timeDelayStatus){
            clearTimeout(timeDelay);
            xfCodeDom.verfiyBtn.removeAttr('disabled');
            xfCodeDom.verfiyBtn.removeClass('f-getcode-dis');
            xfCodeDom.verfiyBtn.text('发送短信验证码');
            getverfiyCode();
        }
    }
    //清空倒计时（预约回电）
    function clearTimeDelayHandleBackCall(){
        if(timeDelayStatus){
            clearTimeout(timeDelay);
            xfCodeDom.backCallverfiyBtn.removeAttr('disabled');
            xfCodeDom.backCallverfiyBtn.removeClass('f-getcode-dis');
            xfCodeDom.backCallverfiyBtn.text('发送短信验证码');
            backCallgetverfiyCode();
        }
    }

    // 刷新图片验证码（免费通话）
    xfCodeDom.refreshBtn.on('click.xfrefresh',function(){    
        refreshCodeImg($(this));
    });
    // 刷新图片验证码（预约回电）
    xfCodeDom.backCallrefreshBtn.on('click.backxfrefresh',function(){
        refreshCodeImg($(this));
    });
    // 发送短信验证码按钮(免费通话)
    function getverfiyCode(){
        xfCodeDom.verfiyBtn.on('click.xfsend',function(){
            var val = $.trim(xfCodeDom.phone.val());
            if(checkList['phone']() && checkList['isShowCode']()){
                verfiyPhone($(this),val,60);
            }
        });
    }
    getverfiyCode();
    // 发送短信验证码按钮(预约回电)
    function backCallgetverfiyCode(){
        xfCodeDom.backCallverfiyBtn.on('click.backxfsend',function(){
            xfCodeDom.phone = $('#free-callback .c-phone');
            xfCodeDom.imgCode = $('#free-callback .img-code-int');
            xfCodeDom.msgBox = $('#free-callback .msg-box');
            xfCodeDom.msgText = $('#free-callback .msg-box span');
            xfCodeDom.isShow = $('#free-callback .j-is-show');
            var val = $.trim(xfCodeDom.phone.val());
            if(checkList['phone']() && checkList['isShowCode']()){
                verfiyPhone($(this),val,60);
            }
        });
    }
    backCallgetverfiyCode();
    //调接口判断是否显示图片验证码
    function isImgValideCode(){
        $.post(__base_url + "/vcode/image/", {}, function (data) {
            if (data.status == 1) {//成功
                xfCodeDom.isShow.show();
                xfCodeDom.isSmsShow.show();
            }else{
                xfCodeDom.isShow.hide();
                xfCodeDom.isSmsShow.hide();
            }
        }, 'json');
    };
    //****************************** 
    /* 按钮显示（免费电话，立即通话，预约回电） */
    var nowHours = new Date().getHours();
//    if (nowHours >= 8 && nowHours < 19) {
    if (!XF.Vars.showReserv) {
        if(cookie_tel){
            entInput.val(cookie_tel);
            enConfirm.attr('class','make-call1').text('立即通话').css('visibility','visible');
        }else{
            if($('#licensedflag').val() == 0){
                enConfirm.attr('class','make-freecall1').text('致电售楼处').css('visibility','visible');
            }else{
                enConfirm.attr('class','make-freecall1').text('致电咨询').css('visibility','visible');
            }
            if(APF.Utils.getCookie('xf_register_phone')){
                entInput.val(APF.Utils.getCookie('xf_register_phone')); 
            }   
        }
    } else {
        if(cookie_tel){
            cookie_tel&&entInput&&entInput.val(cookie_tel);
            enConfirm.attr('class','order-callback1').text('预约回电').css('visibility','visible');
        }else{
            enConfirm.attr('class','order-callback1').text('预约回电').css('visibility','visible');
            if(APF.Utils.getCookie('xf_register_phone')){
                entInput.val(APF.Utils.getCookie('xf_register_phone'));
            }
        }
    }

    //手机号码校验
    function checkNum(phoneInput){
        var phoneNum = $.trim(phoneInput.val()),
            msgBox = phoneInput.parent().find('p.com-msg');
        if(phoneNum==''||phoneNum==tipMsgA||phoneNum==tipMsgB){
            phoneInput.addClass('errorlight');
            msgBox.show().find('em').text(errMsgA);
            return false;
        }else if(!XF.Validate.phoneMobile(phoneNum)){
            phoneInput.addClass('errorlight');
            msgBox.show().find('em').text(errMsgB);
            return false;
        }else{
            cookie_tel = phoneNum;
            phoneInput.removeClass('highlight errorlight');
            msgBox.hide();
            return true;
        }
    }

    //带输入框的立即通话&&带输入框的免费通话入口
    body.on({
        'click':function(){
            // var self = $(this), callType = self.text();
            // var refreshBtnFree = $('#free-step-one .refresh-btn');
            // stepOne.open();
            // xfCodeDom.isSmsShow.hide();//隐藏短信验证码
            // isImgValideCode(); 
            // refreshCodeImg(refreshBtnFree); 
            // clearDataInput(); 
            // clearTimeDelayHandle();// 清空倒计时
            getQrcode();
            qrcodeCall.open();
        }
    },'.make-call1,.make-freecall1');

    //立即通话无输入框入口
    body.on({
        'click':function(){
            var refreshBtnFree = $('#free-step-one .refresh-btn');
            stepTwo.open();
            xfCodeDom.isSmsShow.hide();//隐藏短信验证码
            isImgValideCode();
            refreshCodeImg(refreshBtnFree); 
            clearDataInput(); 
        }
    },'.make-call2');

    //免费通话无输入框入口
    body.on({
        'click':function(){
            getQrcode();
            qrcodeCall.open();
            // var refreshBtnFree = $('#free-step-one .refresh-btn');
            // if (!!XF.Vars.consultant_id) {//售罄盘改变文案
            //     bdOne.find(".tel-subtitle").text('安居客将会对您的号码加密，置业顾问无法查看您的号码。');
            // }
            // if(APF.Utils.getCookie('xf_register_phone')){
            //     bdOne.find('.c-phone').val(APF.Utils.getCookie('xf_register_phone')); 
            // }   
            // xfCodeDom.isSmsShow.hide();//隐藏短信验证码
            // isImgValideCode();
            // refreshCodeImg(refreshBtnFree); 
            // clearDataInput(); 
            // clearTimeDelayHandle();// 清空倒计时 
        }
        
    },'.make-freecall2');

    //步骤一通话
    body.on({
        'click':function(){
            var self = $(this);
            if(checkList['phone']() &&checkList['isShowCode']() && checkList['isShowSmsCode']()){
                var phoneVal = $.trim(xfCodeDom.phone.val()),
                    codeVal = $.trim(xfCodeDom.smsCode.val()),
                    cookie_tel = $.trim(xfCodeDom.phone.val()),
                    msgSms = xfCodeDom.msgBox.eq(2),
                    msg = xfCodeDom.msgText.eq(2);                   
                var mobileDate = {
                        phone:phoneVal,
                        type :15,
                        code :codeVal,
                        loupan_id:XF.Vars.loupanId
                    };
                $.post(__base_url + '/vcode/checkmobilecode/', mobileDate, function (data) {
                    if(data.rst >0){
                        msgSms.hide();
                        stepOne.close();
                        stepTwo.open();
                        xfCodeDom.isSmsShow.hide();
                    }else{
                        if(data.rst == -4){
                           xfCodeDom.isSmsShow.show();
                        }else{
                            msgSms.show();
                            xfCodeDom.smsCode.addClass('int-err');
                            msg.html(data.msg); 
                        }
                       
                    }
                }, "json");
                
            }
        }
    },'#free-step-one .do-call');

    //步骤二修改号码
    body.on({
        'click':function(){
            var box = $('.new-call-v2'), phoneNum = bdTwo.find('.new-cellphone').text();
            bdOne.find('.c-phone').val(cookie_tel);
            if (!!XF.Vars.consultant_id) {//售罄盘改变文案
                bdOne.find(".tel-subtitle").text('安居客将会对您的号码加密，置业顾问无法查看您的号码。');
            }
            stepTwo.close();
            stepOne.open();
            clearDataInput();//清空验证码
            clearTimeDelayHandle();// 清空倒计时
        }
    },'#free-step-two .change-cell');

    $(stepTwo).on('openAfter', function () {
        var mask_telnum = cookie_tel.substring(0,3)+'****'+cookie_tel.substring(7, cookie_tel.length);
        bdTwo.find('.new-cellphone').text(mask_telnum);
        var data = {phone:cookie_tel,loupan_id:XF.Vars.loupanId,ref:XF.Vars.ref};
        if (!!XF.Vars.consultant_id) {//售罄盘
            data = $.extend({}, data, {consultant_id: XF.Vars.consultant_id, loupan_id: XF.Vars.consultant_loupan_id});
        }
        $.post(freeUrl, data, function (data) {
            APF.Utils.setCookie('xf_400_free',cookie_tel,'','/',base_domain);
            if (data.status == 1) {
                bdMax.find('.result-tip-content span').text(!!XF.Vars.consultant_id?'您今天已经拨打本置业顾问太多次啦！':'您今天已经拨打本楼盘太多次啦！');
                stepTwo.close();
                callMax.open();
            }
            if (data.status == 2) {
                bdMax.find('.result-tip-content span').text('您今天已经拨打太多次啦！');
                stepTwo.close();
                callMax.open();
            }
            if (data.status == -1) {
                bdMax.find('.result-tip-content span').text('您好，系统繁忙，请稍后再试');
                stepTwo.close();
                callMax.open();
            }
        }, "json");
    });

    /**预约回电**/

    //预约回电按钮带输入框
    body.on({
        'click':function(){
            var refreshBtnBackCall = $('#free-callback .refresh-btn');
                bdBack.find('.c-phone').val(cookie_tel);
                callBK.open();
            xfCodeDom.isSmsShow.hide();//隐藏短信验证码
            xfCodeDom.isShow = $('#free-callback .j-is-show');
            isImgValideCode();
            refreshCodeImg(refreshBtnBackCall);
            clearDataInput();
            clearTimeDelayHandleBackCall(); //清空倒计时
        }
    },'.order-callback1');

    //预约回电按钮无输入框
    body.on({
        'click':function(){
            var phoneNum = $.trim(entInput.val());
            var refreshBtnBackCall = $('#free-callback .refresh-btn');
            cookie_tel&&bdBack.find('.c-phone').val(cookie_tel);
            if(XF.Validate.phoneMobile(phoneNum)){
                bdBack.find('.c-phone').val(phoneNum);
            }
            xfCodeDom.isSmsShow.hide();//隐藏短信验证码
            xfCodeDom.isShow = $('#free-callback .j-is-show');
            isImgValideCode();
            refreshCodeImg(refreshBtnBackCall);
            clearDataInput();
            clearTimeDelayHandleBackCall(); //清空倒计时
            callBK.open();
        }
        
    },'.order-callback2');

    //弹层点击
    body.on({
        'click':function(){
            $(this).find('table').removeClass('show');
        }
    },'#free-callback');

    //时间框
    body.on({
        'click':function(evt){
            evt.stopPropagation();
            $(this).toggleClass('highlight');
            $(this).next().toggleClass('show');
        }
    },'#free-callback .select-data');

    //时间表格交互
    body.on({
        'mouseenter':function(){
            var self = $(this), timeTable = self.parents('table');
            var thiscol = self.parent("tr").children().index(self) + 1;
            self.addClass('td-hover');
            timeTable.find("tr>:nth-child(" + thiscol + ")").addClass('row-light');
            self.parent("tr").children().addClass('row-light');
        },
        'mouseleave': function() {
            $(this).removeClass('td-hover');
            $(this).parents('table').find(".row-light").removeClass("row-light");
        },
        'click':function(evt){
            evt.stopPropagation();
            var self = $(this), timeTable = self.parents('table'), dataBox = bdBack.find('.select-data');
                thiscol = self.parent("tr").children().index(self);
            var week = new Date().getFullYear() + "-" + timeTable.find("thead th:eq(" + thiscol + ")").text();
            var time = self.parent("tr").find("th").text();
            dataBox.html(week + '&nbsp;<strong>' + time + '</strong>');
            dataBox.removeClass("errorlight highlight");
            timeTable.removeClass('show');
        }
    },'#free-callback td');
    
    //立即预约按钮
    body.on({
        'click':function(){
            var self = $(this), numInput = bdBack.find('.new-cellphone'),
                phoneNum = $.trim(xfCodeDom.phone.val()), dateBox = bdBack.find('.select-data'),
                showdate = $.trim(dateBox.text()), from = $('#ref_from').val() == 'anjuke' ? 'anjuke' : 'site';
            xfCodeDom.phone = $('#free-callback .c-phone');
            xfCodeDom.imgCode = $('#free-callback .img-code-int');
            xfCodeDom.smsCode = $('#free-callback .sms-code-int');
            xfCodeDom.msgBox = $('#free-callback .msg-box');
            xfCodeDom.msgText = $('#free-callback .msg-box span');
            xfCodeDom.isShow = $('#free-callback .j-is-show');
            var smsCodeVal = $.trim(xfCodeDom.smsCode.val());
            if(checkList['phone']() &&checkList['isShowCode']() && checkList['isShowSmsCode']()){
                if(showdate==tipMsgC){
                    dateBox.addClass('errorlight');
                    return;
                }
                dateBox.removeClass('errorlight');                
                var timetext = showdate.split("-");
                timetext[0] = parseInt(timetext[0], 10);
                timetext[1] = parseInt(timetext[1], 10);
                timetext[2] = parseInt(timetext[2], 10);
                timetext[3] = parseInt(timetext[3], 10);
                if (timetext[1] < 10) {
                    timetext[1] = "0" + timetext[1];
                }
                if (timetext[2] < 10) {
                    timetext[2] = "0" + timetext[2];
                }
                var reserve_day = timetext[0].toString() + timetext[1].toString() + timetext[2].toString();
                var reserve_range;
                if (timetext[3] == 12) {
                    reserve_range = 1;
                } else if (timetext[3] == 15) {
                    reserve_range = 2;
                } else {
                    reserve_range = 3;
                }
                $.post(reserveUrl, {phone: cookie_tel, loupan_id: XF.Vars.loupanId, reserve_day: reserve_day, reserve_range: reserve_range, from: from,code:smsCodeVal}, function (data) {
                    APF.Utils.setCookie('xf_400_free',cookie_tel,'','/',base_domain);                    
                    if (data.status == 1) {//预约成功
                        callRT.open();
                        callBK.close();
                        bdResult.find('span').text('恭喜您预约成功！');
                        xfCodeDom.msgBox.eq(2).hide();
                        xfCodeDom.smsCode.removeClass('int-err');
                        xfCodeDom.isSmsShow.hide();
                    } else if (data.status == -3) {//已经预约过
                        xfCodeDom.msgBox.eq(2).hide();
                        xfCodeDom.smsCode.removeClass('int-err');
                        callRT.open();
                        callBK.close();
                        bdResult.find('span').text('您已预约过该楼盘！');
                    }else if(data.status ==9374){
                        xfCodeDom.smsCode.addClass('int-err');
                        xfCodeDom.msgBox.eq(2).show();
                        xfCodeDom.msgText.eq(2).html(data.msg);
                    }else if(data.status ==-1){
                        xfCodeDom.msgBox.eq(2).show();
                        xfCodeDom.msgText.eq(2).html(data.msg);
                    }else if(data.status ==9375){
                        xfCodeDom.isSmsShow.show();
                    }
                }, "json"); 
            }
           
        }
    },'#free-callback #make-order');
    

    //发码
    body.on({
        'click':function(){
            $(this).parents('.newcall-entrance').length&&sendSoj('fc_mfth_planpage');
            $(this).parents('#j-freecall').length&&sendSoj('fc_mfth_top');
        }
    },'.make-call1,.make-call2,.make-freecall1,.make-freecall2,.order-callback1,.order-callback2');

    body.on({
        'click':function(){
            $(this).is('#do-call')?
            sendSoj('fc_mfth_page2'):
            sendSoj('fc_mfyy_page2');
        }
    },'#do-call,#make-order');

    function sendSoj(code){
        XF.Soj.send('{from:'+code+'}', XF.Soj.param);
        return true;
    }
})(jQuery);;(function($){

	XF.nameSpace('XF.Video');

    XF.Video = function(options){
        var video = $('.jp-video');
        this.op = $.extend({
            videoAjaxUrl: XF.Video.options.videoAjaxUrl,
            pageName: XF.pagename
        }, {
            videoPath : '',
            container: '#jp_container_' + video.data('id'),
            videoWin: '#jquery_jplayer_' + video.data('id'),
            supplied  : 'webmv, ogv, m4v',
            size      : {
                width: "100%",
                height: "600px"
            },
            useStateClassSkin: true,
            autoBlur: false,
            smoothPlayBar: true,
            keyEnabled: true,
            remainingDuration: true,
            toggleDuration: true
        }, options);
        this.dom = {
            videoBox      : $(this.op.container),
            allTime       : $(this.op.container).find('.jp-all-time'),
            videoWin      : $(this.op.videoWin),
            playBtn       : $(this.op.container).find('.jp-play'),
            stopBtn       : $(this.op.container).find('.jp-stop'),
            repeatBtn     : $(this.op.container).find('.jp-repeat'),
            toggleBtn     : $(this.op.container).find('[toggle]'),
            volumnMax     : $(this.op.container).find('.jp-volume-max'),
            volumnBar     : $(this.op.container).find('.jp-volume-bar'),
            stateDialog   : $(this.op.container).find('.jp-state-dialog'),
            networkDialog : $(this.op.container).find('.jp-networkError-dialog'),
            closeBtn      : $(this.op.container).find('.jp-btn-close'),
            reloadBtn     : $(this.op.container).find('.jp-btn-reload')
        },
        this.state = {
            waiting : undefined
        };
        this.resource_lock = false;
        this.init();
        this.acts();
    };

    XF.Video.prototype.init = function(){
        var self = this;
        self.op.size.height = 'calc(100% - 49px)';
        self.dom.videoWin.jPlayer({
            ready: function(){
                self.op.ready = true;
            },
            error: function(e){
                self.handleError(e);
            },
            supplied    : self.op.supplied,
            size        : self.op.size,
            preload           : 'none',
            useStateClassSkin : true,
            autoBlur          : false,
            smoothPlayBar     : true,
            keyEnabled        : true,
            remainingDuration : true,
            toggleDuration    : true,
            cssSelectorAncestor: self.op.cssSelectorAncestor ? self.op.cssSelectorAncestor : self.op.container
        });
    }

    XF.Video.prototype.acts = function(){
        var self = this;
        self.dom.volumnMax.click(function(e){
            $(this).addClass('active');
        });
        self.dom.repeatBtn.click(function(){
            $(this).toggleClass('active');
        });
        self.dom.volumnBar.click(function(){
            self.dom.volumnMax.removeClass('active');
        });
        //网速过慢
        self.dom.videoWin.on($.jPlayer.event.waiting, function(e){
            //self.dom.networkDialog.show();
        });
        self.dom.videoWin.on($.jPlayer.event.playing, function(e){
            self.dom.networkDialog.hide();
        });
        // self.dom.videoWin.on($.jPlayer.event.ended, function(e){
        //     var status = e.jPlayer.status;
        //     self._SendSoj('ended',status);
        // });
        self.dom.videoWin.on($.jPlayer.event.seeked, function(e){
            var status = e.jPlayer.status;
            self._SendSoj('seeked',status);
        });
        self.dom.videoWin.on($.jPlayer.event.play, function(e){
            var status = e.jPlayer.status;
            //禁用视频右键保存
            document.oncontextmenu=function (event) {
                var btnNum = event.button;
                if(btnNum == 2){
                    event.preventDefault();
                    event.returnValue = false;
                }
            }
            self._SendSoj('play',status);
        });
        //setting duration in GUI
        self.dom.videoWin.on($.jPlayer.event.durationchange , function(e){
            var status = e.jPlayer.status;
            self.dom.allTime.html('/'+$.jPlayer.convertTime( status.duration ))
        });
        self.dom.videoWin.on($.jPlayer.event.pause, function(e){
            var status = e.jPlayer.status;
            if (status.ended) {
                self._SendSoj('ended',status);
            }else{
                self._SendSoj('stop',status);
            }
        });
        self.dom.closeBtn.click(function(){
            self.dom.stateDialog.hide();
        });
        self.dom.reloadBtn.click(function(){
            window.location.reload();
        });
    }

    XF.Video.prototype.setVideo = function(vid, duration){
        var self = this;
        this.dom.allTime.text('/' + (duration || ''));
        self.dom.networkDialog.show();

        return $.when( $.ajax({ url: this.op.videoAjaxUrl + vid, type: 'get', dataType: 'json'}) ).done(function (res) {
            res.status == 1 && self.dom.videoWin.jPlayer("setMedia", { m4v: res.play_url.f30_url });
        });
    }

    XF.Video.prototype.show = function(flag){
        var self = this;
        this.flag = flag;
        flag ? self.dom.videoBox.show() : self.dom.videoBox.hide();
    }

    XF.Video.prototype.stop = function(){
        if (!this.flag) {
            return false;
        }
        this.show(false);
        this.dom.videoWin.jPlayer('pause');
    }

    XF.Video.prototype.replay = function(){
        this.dom.repeatBtn.trigger('click');
    }

    XF.Video.prototype.play = function(vid, duration,url){
        var self = this;
        self.op.vid = vid;
        this.show(true);
        // self._SendSoj('play');
        if(!url){
            vid && self.setVideo(vid, duration).done(function(){
                // 兼容ie8自动播放
                setTimeout(function() {
                    self.dom.networkDialog.hide();
                    self.dom.videoWin.jPlayer('play');
                }, 0);
            });
        }else{
            if(!self.resource_lock){
                self.dom.videoWin.jPlayer("setMedia", { m4v : url });
                self.resource_lock = true;
                self.dom.networkDialog.hide();
                setTimeout(function() {
                    self.dom.videoWin.jPlayer('play');
                }, 0);
            }

        }
    }

    XF.Video.prototype.handleError = function(event){
    }

    XF.Video.prototype._SendSoj = function(type,status){
        var vid = this.op.vid,
            pg = this.op.pageName || XF.pagename;
        // console.log(type,status);
        XF.Soj.send('{from:' + pg + '_video_' + type + ',video_id:' + vid + ',cur_time:'+status.currentTime+',duration:'+status.duration+'}', XF.Soj.param);
    }
})(jQuery);
;
(function ($) {

    XF.nameSpace('XF.loupan.photo.Image');
    XF.loupan.photo.Image = function(op){
	    //	弹出框部分
	    this.ops = {
            basicLink: $('.others-b').find('a'),
	        modalAlbumCon: $('#modal-album-con')
        }
        this.ops = $.extend(this.ops, op);
	    this.modalAlbumTab = new XF.Modal({
	        modalClass: 'modal-album',
	        con       : this.ops.modalAlbumCon,
	        width     : '970'
	    });
        this.init();
    }

    XF.loupan.photo.Image.prototype.init = function(){
        this.videoPlayer = new XF.Video({

            videoAjaxUrl: this.ops.videoAjaxUrl,
            size      : {
                width: '100%',
                height: '596px'
            },
            pageName: this.ops.pageName
        });
        this.eventHandler();
        this.AlbumLoopPoplayer();
    }

    XF.loupan.photo.Image.prototype.eventHandler = function(){
        var self = this,
            basicLink = this.ops.basicLink,
            AlbumTabPhoto = this.AlbumTabPhoto,
            modalAlbumTab = this.modalAlbumTab,
            modalAlbumCon = this.ops.modalAlbumCon;

        $(basicLink).each(function () {
           	$(this).on('click.album', function (e) {
           		if($(this).hasClass('qj-item')){
           			return;
           		}
	    		var image_id = $(this).attr('image_id'), obj = getIndex(image_id), index = obj.index, num = obj.num;

	    		if (!XF.Vars.imageAlbumData[num].big.length) {
	    			return;
	    		}
	    		if (!AlbumTabPhoto) {
	    			AlbumTabPhoto = new XF.AlbumTab({
	    				swBigOp    : {
	    					switchST: '#j-switch-album-b',
	    					conST   : '.swcon',
	    					pnavST  : '#j-switch-album-s .item',
	    					effect  : 'fade'
	    				},
	    				swSmallOp  : {
	    					switchST : '#j-switch-album-s',
	    					conST    : '.swcon',
	    					switchNum: 6,
	    					clipNum  : 7
	    				},
	    				tabST      : '.album-info-tab .tab-con a',
	    				tabIndex   : num,
	    				tabCurClass: 'cur',
	    				imgSrc     : XF.Vars.imageAlbumData,
	    				imgDes     : true,
                        videoH     : 566
	    			});
                    self.AlbumTabPhoto = AlbumTabPhoto;
                    $(AlbumTabPhoto).on('click.video', $.proxy(self.videoHandler, self) );
                    $(AlbumTabPhoto).on('playAfter playBefore click.album', function(){
                        self.AlbumTabPhoto.ops.swBig.op.clip.show();
                        self.videoPlayer.stop();
                    });
                }
	    		AlbumTabPhoto.ops.tab.eq(num).trigger('click.album');
	    		AlbumTabPhoto.ops.swBig.switchTo(index);
	    		self.setAlbumWidth();
	    		modalAlbumTab.open();
	    	});
	    });

        $(modalAlbumTab).on('closeAfter', function(){

            self.AlbumTabPhoto.ops.swBig.op.clip.hide();
            self.videoPlayer.stop();
        });

	    $(window).on('resize.album', function () {
	    	AlbumTabPhoto && self.setAlbumWidth();
	    });

        /*发送SOJ*/
	    basicLink.on('click.sendsoj', function () {
			var sojname = "{from:" + $(this).data('sojname') + "}";
			//wupc ----新加
			var parentEl = $(this).parents('.others-b');
			var action = $(parentEl).data('action') || '',
				imageType = $(parentEl).data('imagetype') || '';
			var sojData = {};
			if(action || imageType){
				sojData ={
					action: action,
					ep:{imagetype:imageType}
				}
			}
			var sojParam = $.extend({},sojData,XF.Soj.param);
	    	XF.Soj.send(sojname,sojParam);
	    });
	    $('#j-switch-album-s').on('click.sendsoj', '.item', function () {
	    	XF.Soj.send("{from:click_xiangcelist_bigpic_thoum}", XF.Soj.param);
	    });
	    $('#j-switch-album-b').on('click.sendsoj', '.prev,.next', function () {
	    	XF.Soj.send("{from:click_xiangcelist_bigpic_thoum}", XF.Soj.param);
	    });
	    modalAlbumCon.find('.album-info-tab .tab-con a').on('click.sendsoj', function () {
	    	XF.Soj.send("{from:click_xiangcelist_bigpic_tips}", XF.Soj.param);
	    });

	    // 设置相册弹出层循环结束
	    // 点击“装修图”
	    this.initPhoneNum = "",
	    this.closeBtnBinded = false;
	    $(".others-pic").on("click", "li", function() {
	    	self.initPhoneNum = self.initPhoneNum || $(".phone").html();
			self.closeBtnBinded || self.bindClose();
			// 兼容一下，防止除相册外其他地方引用，没用.on元素的报错
	    	if ( $(this).parent().hasClass("hxzxg-dwg-list") || ($(".on").html()&& $(".on").html().indexOf("装修图")!==-1) ) {
	    		self.changePhoneNum(true);
	    	}
	    });
	    $(".album-info-tab .tab-con a").on("click", function() {
	    	if( this.innerHTML.indexOf("装修图") !== -1 ) {
	    		self.changePhoneNum(true);
	    	} else {
	    		self.changePhoneNum(false);
	    	}
	    });

        /*通过图片id获取图片在相册中的位置*/
	    function getIndex(image_id){
	    	var obj = {index : 0, num : 0};
	    	var index , num = 0 ;
	    	for(var i = 0; i < XF.Vars.imageAlbumData.length; i++){
	    		if (XF.Vars.imageAlbumData[i] != null && typeof XF.Vars.imageAlbumData[i] != undefined ){
	    			var arr_image_id = XF.Vars.imageAlbumData[i].image_id;
	    			for (var j = 0; j < arr_image_id.length; j++) {
	    				if (arr_image_id[j] == image_id) {
	    					index = j;
	    					num = i;
	    					break;
	    				}
	    			}
	    		}
	    	}
	    	obj.index = index;
	    	obj.num  = num;
	    	return obj;
	    }

    }

    XF.loupan.photo.Image.prototype.videoHandler = function(e, data){
        this.AlbumTabPhoto.ops.swBig.op.clip.hide();
        this.videoPlayer.play(data.vid, data.duration);
    }

	/*设定相册宽度*/
    XF.loupan.photo.Image.prototype.setAlbumWidth = function(){
	    var modalAlbumCon = this.ops.modalAlbumCon,
            autoAlbum = modalAlbumCon.parents('.modal-album'),
            modalAlbumTab = this.modalAlbumTab,
            AlbumTabPhoto = this.AlbumTabPhoto,
	        albumWidth = $(window).width() >= 1250 ? 860 : 620;

	    if (albumWidth == 860) {
	    	autoAlbum.length ? autoAlbum.addClass('modal-album-lg') : (modalAlbumTab.op.modalClass = 'modal-album modal-album-lg');
	    	AlbumTabPhoto.ops.swSmall.op.clipNum = 7;
	    	AlbumTabPhoto.ops.swSmall.op.switchNum = 6;
	    } else {
	    	autoAlbum.removeClass('modal-album-lg');
	    	AlbumTabPhoto.ops.swSmall.op.clipNum = 5;
	    	AlbumTabPhoto.ops.swSmall.op.switchNum = 4;
	    }
	    AlbumTabPhoto.ops.autoHeight && AlbumTabPhoto.changeHeight();
	    /*窗口宽度变换时,改变描述背景高度*/
	    AlbumTabPhoto.ops.imgDes && AlbumTabPhoto.changeDesHeight();
    }

	// 设置相册弹出层循环
    XF.loupan.photo.Image.prototype.AlbumLoopPoplayer = function(){
		var index,
            self = this,
		    loopNext = $('#j-switch-album-b').find('.next'),
		    loopPrev = $('#j-switch-album-b').find('.prev'),
		    looptabCon =  $('.album-info-tab').find('.tab-con'),
		    loopTab = looptabCon.find('a'),
		    looptabLen = loopTab.length - 1;

		loopNext.on('click.loopNext',function(){
			var loopCurtab = looptabCon.find('.cur'),
			    index = loopTab.index(loopCurtab);
			if(loopNext.hasClass('next-dis')){

				setTimeout(function(){
					loopNext.removeClass('next-dis');
					//$("#j-switch-album-s").find(".item").eq(1).trigger('click.switch');
					loopCurtab.next().click();
					if( index == looptabLen ){
	                    loopTab.eq(0).click();
					}
				},100)

			}
		});

		loopPrev.on('click.loopPrev',function(){
			var loopCurtab = looptabCon.find('.cur'),
			    index = loopTab.index(loopCurtab);
			if(loopPrev.hasClass('prev-dis')){
				loopCurtab.prev().click();
				if(index == 0){
					loopTab.eq(looptabLen).click();
				}

			}
		});
	}

    XF.loupan.photo.Image.prototype.changePhoneNum = function(logo){
		if( logo ) {
			$(".phone strong").html("");
			$(".phone span").html("");
			$("#phone_num_image").html("400-681-6013<i class='hxzxg-logo'>红星装修公</i>");
		} else {
			$(".phone").html(this.initPhoneNum);
		}
	}

    XF.loupan.photo.Image.prototype.bindClose = function(){
        var self = this;
		$(".close").on("click", function() {
			self.hideHXZXGLogo();
			self.changePhoneNum(false);
		});
		this.closeBtnBinded = true;
	}

    XF.loupan.photo.Image.prototype.hideHXZXGLogo = function(){
		$(".hxzxg-logo").hide();
    }

})(jQuery);
;
(function ($) {
    XF.nameSpace('XF.loupan.DongtaiTimeline');
    XF.loupan.DongtaiTimeline = function (op) {
        this.ops = $.extend(this.ops, op);
        this.init();
    }
    XF.loupan.DongtaiTimeline.prototype = {
        init:function (){
            this.view_more();
            this.dealOfficialLastBlock();
        },
        view_more:function(){
            var obj = $('#all_hidden') || {};
            var h = 0,
                count = 0;
            obj.children('.moment-item-wrap').each(function(index, el) {
                if (count++ < 5) {
                    h += $(el).height();
                }
            });

            obj.css('height', h + 'px');
            var ser=$('#view_more');
            if(ser){
                ser.on('click', function(event) {
                    obj.css('height','auto');
                    ser.hide();
                });
            }

        },
        dealOfficialLastBlock:function(){

            var obj = $('.lp1')[0];
            if(!obj) return;
            var arr = obj.childNodes;
            var lastDom;
            for(var i =0 ,len =arr.length;i<len;i++){
                if(arr[i].nodeType == 1 && arr[i].className.indexOf('clickable')>= 0){
                    lastDom = arr[i];
                }
            }
            if(!lastDom){
                return;
            }
        },
    }
})(jQuery);