// vim: filetype=javascript
var GA_ACCOUNT_ID = 'UA-11480328-1';
var MAIN_DOMAIN = '99fang.com';
var link_state=1;

$(function(){
    var a = Math.floor(Math.random()*11);
    $("#antispama").val(a);
    $("#antispamb").val(Math.pow(a,3));
});

var SSL = {
    getParams: function(paramStr){
        var args = {};   
        var query = paramStr|| window.location.search.substring(1);
        var items = query.split("&");
        var len = items.length;
        for(var i=0;i<len;i++){   
            var item = items[i];
            var pos = item.indexOf('=');
            if(pos==-1){
                continue;
            }
            var argName = item.substring(0,pos);
            var argValue = item.substring(pos+1);
            args[argName] = unescape(argValue);
        }
        return args;
    }
};

$.fn.toggleButton = function(refObj){
    $.isArray(refObj) || (refObj = [refObj]);
    $(this).each(function(i){
        var curRef = refObj[i];
        if(!(curRef instanceof $)){
            if(typeof curRef == "undefined"){
                curRef = $($(this).attr("ref"));
            }
            else if (curRef.nodeType || typeof curRef == "String"){
                curRef = $(curRef);
            }
            else {
                throw "param should be dom node or css string"
            }
        }
        curRef.length && $(this).click(function (){
            curRef.toggle();
        });
    });
    return this;
};

function cookies_fun(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

//select
$(function(){
    $(".selectlist").bind("mouseover mouseout", function(event){
        $(this).find(".selectul").toggle();
        event.stopPropagation();
    });
    var $selectli = $(".selectul li");
    $selectli.bind("mouseover", function(){
        var $self = $(this);
        $self.siblings("li").removeClass("here");
        $self.addClass("here");
    });
    var $sels = $(".selectinner");
    $selectli.filter(".here").each(function(i){
        var text = $(this).text();
        var buxian = '不限';
        text = text.replace(/(^\s*)|(\s*$)/g, "");
        var $sel = $sels.eq(i);
        if(text!=buxian){
            $sel.empty();
            $sel.html(text);
        }else{
            $sel.html($sel.attr("title"));
        }
    });
});

function UpdateURL(url,name,value){
	var pos = url.indexOf("?");
	if (pos != -1)
	{
		var req = url.substr(pos+1);
		url = url.substr(0,pos+1)
		var items = req.split("&");
		var flag = 0
		for (var i=0; i<items.length; i++)
		{
			parts = items[i].split("=");
			if(parts[0] == name)
			{
				url += name + "=" + value;
				flag = 1;
			}
			else
			{
				url += items[i];
			}
			if (i<items.length-1)
				url += "&";
		}
		if (flag == 0)
		{
			url += "&" + name + "=" + value;
		}
	}
	else
	{
		url += "?" + name + "=" + value;
	}
	return url;
}

//suggestionjs功能函数
/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * Copyright notice and license must remain intact for legal use
 * jSuggest
 * Version: 1.0 (May 26, 2008)
 * Requires: jQuery 1.2.6+
 */
$.fn.jSuggest = function(options) {
    var jH = ".jSuggestHover";
    var jsH = "jSuggestHover";
    var iniVal = this.value;
    var textBox = this;
    var textVal = this.value;
    var jC = "#jSuggestContainer";
    var defaults = {
        minchar: 1,
        opacity: 1.0,
        zindex: 20000,
        delay: 0,
        loadingText: 'Loading...',
        autoChange: false,
        url: "",
        type: "GET",
        data: "",
        onSelect: function(){
            $(".search-button:visible").trigger("click");
        }
    };
    var opts = $.extend({}, defaults, options);

    $("body").append('<div id="jSuggestContainer"></div>');
    $(jC).hide();
    $(this).bind("keyup click", function(e){
        textBox = this;
        textVal = this.value;
        if (this.value.length >= opts.minchar && $.trim(this.value)!="Search Terms") {
            var offSet = $(this).offset();

            $(jC).css({
                position: "absolute",
                top: offSet.top + $(this).outerHeight() + "px",
                left: offSet.left,
                width: $(this).outerWidth()-2 + "px",
                opacity: opts.opacity,
                zIndex: opts.zindex
            }).show();

            // if escape key
            if (e.keyCode == 27 ) {
                $(jC).hide();
            }
            // if enter key
            else if (e.keyCode == 13 ) {
                if ($(jH).length == 1)
                    $(textBox).val($(jH).text());
                $(jC).hide();
                iniVal = textBox.value;
            }
            // if down arrow
            else if (e.keyCode == 40) {
                // if any suggestion is highlighted
                if ($(jH).length == 1) {
                    if (!$(jH).next().length == 0) {
                        $(jH).next().addClass(jsH);
                        $(".jSuggestHover:eq(0)").removeClass(jsH);
                        if (opts.autoChange)
                            $(textBox).val($(jH).text());
                    }
                }
                else {
                    $("#jSuggestContainer ul li:first-child").addClass(jsH);
                    if (opts.autoChange)
                        $(textBox).val($(jH).text());
                }
            }
            // if up arrow
            else if (e.keyCode == 38) {
                // if any suggestion is highlighted
                if ($(jH).length == 1 ) {
                    if (!$(jH).prev().length == 0) {
                        $(jH).prev().addClass(jsH);
                        $(".jSuggestHover:eq(1)").removeClass(jsH);
                        if (opts.autoChange)
                            $(textBox).val($(jH).text());
                    }
                    // if is first child
                    else {
                        $(jH).removeClass(jsH);
                        $(textBox).val(iniVal);
                    }
                }
            }
            // new query detected
            else if (textBox.value != iniVal){
                iniVal = textBox.value;
                if (opts.data == '')
                    opts.data = $(this).serialize();
                else
                    opts.data = "count=10&ch=Fang&callback=&city=" +
                        encodeURI($("#from").val()) +"&q=" + encodeURI($(this).val());
                    // optimize server performance by loading at intervals
                    setTimeout(function () {
                        $.ajax({
                            type: opts.type,
                            url: opts.url,
                            data: opts.data,
                            success: function(msg){
                                $(jC).find('ul').remove();
                                $(jC).append(msg);
                                $("#jSuggestContainer ul li").mouseover(function(){
                                    $(jH).removeClass(jsH);
                                    $(this).addClass(jsH);
                                    textVal = $(this).text();
                                    if (opts.autoChange)
                                        $(textBox).val($(jH).text());
                                }).click(function(){
                                    $(this).addClass(jsH);
                                    $(textBox).val(textVal);
                                    opts.onSelect.call(this, textVal);
                                });
                                $(".jSuggestLoading").hide();
                            }
                        });
                    }, opts.delay);
            }
        }
        // if text is too short do nothing and hide everything
        else {
            $(jH).removeClass(jsH);
            $(jC).hide();
        }
        // no bubbling, click is binded to textBox to prevent document bind from firing
        return false;
    });
    // why no use $(this).blur ?,because jSuggest box is hidden before click fires so this is the only way to do it
    // alternate way is to say that text blur will fire before$("#jSuggestContainer ul li") click.
    $(document).click(function(){
        $(jC).hide();
        iniVal = textBox.value;
    });
};

//执行suggestion功能js
$(function(){
	if($.fn.autocomplete){
		var lastXHR;
		$("#bus").autocomplete({
			source: function(request, response){
				if(lastXHR) lastXHR.abort();
				lastXHR = $.getJSON('/bus/suggestion/?callback=?',
					{'q': encodeURI($(this.element).val()), 'city': encodeURI($("#from").val())},
					function(data){
						response($.map(data, function(item){
							return {label: item.name, value: item.id}
						}));
					}
				);
				$('#bus_id').val("");
			},
			focus: function(event, ui){
				$(this).val(ui.item.label);
				return false;
			},
			select: function(event, ui){
				$('#bus_id').val(ui.item.value)
				$('#bus_search').trigger('click')
				$(this).val(ui.item.label);
				return false;
			}
		});
		$('#bus').keypress(function(e){ if((e.keyCode || e.which) == 13) $('#bus_search').trigger('click')})
		$('#bus_search').click(function(){
			if($('#bus_id').val()){
				location.href= '/'+ $('#city_code').val() + '/rb'+ $('#bus_id').val() + '/';
			} else {
				$.getJSON('/bus/suggestion/?callback=?',
					{'q': encodeURI($('#bus').val()), 'city': encodeURI($("#from").val())},
					function(data){
						if(data.length){
							location.href = '/' + $('#city_code').val() + '/rb' + data[0]['id'] + '/';
						} else {
							$("#bus").val('');
							alert('没有匹配的相关路线');
						}
					}
				)
			}
		});
	};
});

//用js实现超链接
function visit(href, target){
    target = target||"_self";
    if(navigator.appName.toLowerCase().search("microsoft") != -1){
        var bodyElem = document.getElementsByTagName("body")[0];
        var elem = document.createElement("a");
        elem.style.display = "none";
        elem.href = href;
        elem.target = target;
        bodyElem.appendChild(elem);
        elem.click();
        bodyElem.removeChild(elem);
    }else{
        if(target == "_self"){
            window.location.href = href;
        }else{
            window.open(href);
        }
    }
}
function visit_de(encoded_href, target){
    visit(translate_url(encoded_href), target);
}

//以指定方式(_self或_blank)访问指定链接，并以gaIdentifier进行ga统计
//对于_self方式的链接，为了让ga统计更准确，会有0.5秒延时
function visitLink(href, target, gaIdentifier){
    ga_statistics(gaIdentifier);
    if(!target || target == "_self"){
        setTimeout(function(){
            visit(href, target);
        }, 500);
    }else{
        visit(href, target);
    }
}

// save visited item to cookie
function visitItem(type, channel, title, href, target, gaIdentifier, open_link) {
    // save cookie
    var cookie_val = cookies_fun('recent_visited');
    if(channel == 'Rent') {
        title = '[租房]' + title;
    }
    else {
        title = '[二手房]' + title;
    }
    if(href.nodeType)
    {
        href = href.getAttribute("ref");
    }
    var  val = title + "::" + href;

    if(cookie_val === null){
        cookie_val = val;
    }
    else{
        var cookie_val_array = cookie_val.split('||');

        if(cookie_val.indexOf(val) < 0) {
            if(cookie_val_array.length > 2){
                var cookie_val_array = cookie_val.split('||');
                cookie_val_array.pop();
                cookie_val = cookie_val_array.join('||');
            }

            cookie_val = val + "||" + cookie_val;
        }
    }

    var expires_time = 360;
    var options = { expires: expires_time, path: '/', domain: MAIN_DOMAIN, secure: false};
    cookies_fun('recent_visited', cookie_val, options);

    // refresh gui
    show_recent_visited();

    // visitLink
    if(type == 'vhit'){
        if(open_link===false || open_link===0){
            ga_statistics(gaIdentifier);
        }else{
            visitLink(href, target, gaIdentifier);
        }
    }else{
        //vclick item
        visitLink(href, target, gaIdentifier);
    }
}

function show_recent_visited() {
    var html = '';
    var cookie_val = cookies_fun('recent_visited');
    var city_code = $('#city_code').val();
    var channel = $('#channel').val().toLowerCase();
    var page_type = $('#page_type').val().toLowerCase();

    if(cookie_val == null) {
        if(channel == 'rent'){
            var short_domain = "fang";
            var short_channel= "r";
        }else{
            var short_domain = "esf";
            var short_channel= "h";
        }
        $("#recent_visited").html('<div class="freshman"><a href="http://' +
            short_domain+'.' +MAIN_DOMAIN+'/'+city_code+'/'+short_channel+
        '/"><img src="/image/home_freshman_pic.jpg" /></a></div>');
        return;
    }

    var cookie_val_array = cookie_val.split('||');
    for (var i = 0; i < cookie_val_array.length; i++) {
        links = cookie_val_array[i].split('::');
        html += '<li><a'
        if(page_type == 'indexpage'){
            html += " onclick=\"_gaq.push(['_trackEvent', 'history', 'history']);\" ";
        }
        html += " href=\"javascript:visitLink('" + links[1] + "', '_blank', '');\" blank=\"_blank\">"
        + links[0] + '</a></li>';
    }
    $("#recent_visited").html(html);
}

H_C = {
    "history_key": 'history_condition',
    "last_key": 'last_condition',
    "row_splitor": "|||",
    "col_splitor1": ",",
    "col_splitor2": ">>",
    "max_num_of_history": 5,
    "expire_day": 360,
    "get_container" : function(){
        if(typeof this.__container == "undefined")
        {
            this.__container = $("#history_condition");
        }
        return this.__container;
    },
    "get_current_condition": function () {
        if(typeof this.__last_condition == "undefined")
        {
            var desc = [];
            var $container = $("#bigareabox .filter-container");

            //输入框关键字
            var path = window.location.pathname;
            var rxp = /\/[rh]\/q.*?\//;
            if(rxp.test(path))
            {
                var $form = $("#"+this.channel+"-form");
                var query = $.trim($(":text[name='q']", $form).val());
                desc.push({
                    text:query,
                    back_href:path.replace(rxp, "/")
                });
            }
            //所有非“不限”的条件链接
            var unit = this.unit;
            $container.find("div").filter(".content,.content-short,.smallarea,.selectlist")
            .each(function(i, section){
                var $sec = $(section);
                var $current_a = $sec.find("a.areanow, li.here");
                if($current_a.length){
                    //抛弃第一项：不限、全部、经纪人..
                    if($current_a.is(":first-child") || $current_a.prev(".rent-sort").length){
                        return true;
                    }else{
                        if($current_a.is("li")){
                            $current_a = $current_a.children("a");
                        }
                        var text = $.trim($current_a.text()).replace("m2", "平米");
                    }
                }else{
                    var $pu = $sec.find(":text[name='price_upper']");
                    //self defined price
                    if($pu.length){
                        var price_u = $pu.val();
                        var price_l = $sec.find(":text[name='price_lower']").val();
                        price_u = price_u=="0"? "": price_u;
                        price_l = price_l=="0"? "": price_l;
                        if(price_u && price_l){
                            var text = price_l + "-" + price_u + unit;
                        }else if(price_u){
                            var text = price_u + unit + "以下";
                        }else if(price_l){
                            var text = price_l + unit + "以上";
                        }else{
                            return true;
                        }
                    }else{
                        var $bus = $("#bus");
                        //self defined bus 
                        if($bus.length){
                            var text = $bus.attr("defaultValue");
                        }else{
                            return true;
                        }
                    }
                }
                var $back_a = $sec.find("a:first");
                desc.push({
                    text:text,
                    back_href:$back_a.attr("href")
                });
            });
            this.__last_condition = desc;
        }
        return this.__last_condition;
    },
    "get_format_current_condition": function () {
        var current_condition = this.get_current_condition();
        if(!current_condition || !current_condition.length){
            return false;
        }
        var desc = [];
        var col_sp1 = this.col_splitor1;
        var col_sp2 = this.col_splitor2;

        //所有条件链接
        $.each(current_condition, function(index, item){
            var text = $.trim(item.text);
            desc.push(text);
        });
        if(desc.length){
            return [desc.join(col_sp1), col_sp2, window.location.pathname].join("");
        }
    },
    "save_current_condition_to_last_cookie": function () {
        var condition_str = this.get_format_current_condition();
        condition_str && cookies_fun(this.last_key, condition_str, {
            "path":"/",
            "expires":this.expire_day
        });
    },
    "save_current_condition_to_history": function () {
        var condition_str = this.get_format_current_condition();
        if(condition_str){
            var cookie_history = cookies_fun(this.history_key);
            var history_array = cookie_history? cookie_history.split(this.row_splitor) : [];
            var len = history_array.length;
            var max = this.max_num_of_history;
            (len >= max) && history_array.splice(0, 1);
            history_array.push(condition_str);
            cookies_fun(this.history_key, history_array.join(this.row_splitor), {
                "path":"/",
                "expires":this.expire_day
            });
            this.show_saved_condition();
        }
    },
    "show_current_condition": function () {
        var current_condition = this.get_current_condition();
        if(!current_condition || !current_condition.length){
            return false;
        }
        var $container = this.get_container();
        var $condition_bar = $container.find(">.condition-bar");

        //所有条件链接
        $.each(current_condition, function(index, item){
            var $info_a = $("<a class='select-unit'>"+ item.text + "</a>");
            $info_a.attr("href", item.back_href);
            $condition_bar.append($info_a);
        });

        $container.find(".condition-tips").html('当前找房条件：');
        $container.find(".save-link").show();
        $container.show();
    },
    "show_last_condition": function (last_cookie) {
        var last_condition = last_cookie.split(this.col_splitor2); 
        var desc = last_condition[0].split(this.col_splitor1).join(" ");
        var href = last_condition[1];
        var $container = this.get_container();
        var $a = $container.find("a.history-condition");
        $a.html("[" + desc + "]");
        $a.attr("href", href);
        $container.find(".condition-tips").html('您上次的找房条件：');
        $container.show();
    },
    "show_saved_condition": function (history_cookie) {
        var row_sp = this.row_splitor;
        var col_sp1 = this.col_splitor1;
        var col_sp2 = this.col_splitor2;
        var history_key = this.history_key;
        var this_ = this;
        var history_cookie = history_cookie || cookies_fun(history_key);
        var history_conditions = history_cookie? history_cookie.split(row_sp): []; 
        var $condition_list = $("#condition-list");
        var $container = $condition_list.find(".condition-list");
        $container.empty();

        $.each(history_conditions, function(i, item){
            var item = item.split(col_sp2);

            var $info_a = $("<a></a>");
            var text = item[0].split(col_sp1).join(" + ");
            $info_a.html(text);
            $info_a.attr("href", item[1]);
            $info_a.click(function(){
                var href = $(this).attr("href");
                var flag = "?ga_stat=diy";
                if(href.indexOf(flag) == -1)
                {
                    $(this).attr("href", href + flag);
                } 
                return true;
            });

            var $close_div = $('<div class="close-btn"></div>');
            $close_div.click(function(){
                var $all_close = $container.find("div.close-btn");
                var index = $all_close.length -1 - $all_close.index(this);
                var cookie_history = cookies_fun(history_key);
                var history_array = cookie_history? cookie_history.split(row_sp) : [];
                history_array.splice(index, 1);

                cookies_fun(history_key, history_array.join(row_sp), {
                    "path":"/",
                    "expires":this.expire_day
                });
                this_.show_saved_condition();
            });

            var $tr = $("<tr></tr>");
            var $td1 =$("<td></td>").append($info_a);
            var $td2 =$("<td></td>").append($close_div);
            $tr.append($td1).append($td2);
            $container.prepend($tr);
        });

        $condition_list.find(".saved-number").html("已保存（"+ history_conditions.length + "）");
        $condition_list.show();
        this.get_container().show();
    },
    "is_current_empty": function () {
        var path = window.location.pathname;
        if(/^\/\w+\/$/.test(path)){
            var isEmpty = true;
        }
        //bus subway
        else if(/^\/\w+\/(r|h)(b|sw)\/$/.test(path)){
            var isEmpty = true;
        }else{
            var isEmpty = false;
        }
        return isEmpty;
    },
    "init_history_condition": function () {
        //only open for list channel
        this.channel = ($('#channel').val()||"").toLowerCase();
        var host = window.location.hostname;
        if(host.indexOf("esf.")>=0){
            this.unit = "万";
        }else if(host.indexOf("fang.")>=0){
            this.unit = "元";
        }else{
            return false;
        }

        //保存当前条件事件
        var this_ = this;
        this.get_container().find(".save-link").click(function(){
            var $self = $(this);
            this_.save_current_condition_to_history();
            $self.unbind("click");
            $self.html("当前条件已存");
        });

        var cookie_history = cookies_fun(this.history_key);

        //当前搜索条件空
        if(this.is_current_empty())
        {
            var cookie_last = cookies_fun(this.last_key);
            //有上次搜索条件
            if(cookie_last){
                this.show_last_condition(cookie_last);
                //有历史条件
                cookie_history && this.show_saved_condition(cookie_history);
            }else{
                this.get_container().parent(".rent-condition-line").hide();
            }
        }else{
            this.show_current_condition();
            this.save_current_condition_to_last_cookie();
            //有历史条件
            cookie_history && this.show_saved_condition(cookie_history);
        }
    }
}

function ga_statistics(gaStr){
    try{
        _gaq.push(['_trackPageview', gaStr]);//ga
    }catch(err){}
}

//agency gate js
$(function(){
    $("#agency-tool").hover(function(){
        $(this).find("p").css("text-decoration","underline");
    }, function(){
        $(this).find("p").css("text-decoration","none");
    });
})

//切换城市
$(function(){
    var $othercity = $(".othercity");
	var city_status = 0;
    $("#city_btn").toggleButton($othercity);
	$(".othercity,#city_btn").mouseover(function(){
		city_status = 1;
	}).mouseout(function(){
		city_status = 0;
	});
	$("body").click(function(){
		if(city_status != 1){
			$othercity.css({display:"none"});
		}
	})
    $othercity.find("a").click(function(){
        $("#the_city").text($(this).text() + "站");
        $othercity.css({display:"none"});
    });
    $othercity.find(".close").click(function(){
        $othercity.css({display:"none"});
    });
})

//用户反馈
function append_suggest(){
	$("#suggest-table-container").html('<tr><td>问题分类：</td><td><select name="suggtitle" id="suggtitle"><option value="产品建议">产品建议</option><option value="电话号码盗用">电话号码盗用</option><option value="错判中介">错判中介</option><option value="虚假信息">虚假信息</option><option value="其他问题">其他问题</option></select></td></tr>' + '<tr><td>反馈内容：</td><td><textarea name="suggcontent" id="suggcontent" cols="" rows="5">' + default_info + '</textarea></td></tr>' + '<tr><td>您的姓名：</td><td><input name="suggname" id="suggname" class="input" type="text" value="' + default_name + '"/></td></tr>' + '<tr><td>电子邮箱：</td><td><input name="suggcontact" id="suggcontact" value="' + default_contact + '" class="input" type="text" /></td></tr>' + '<tr><td>手机号码：</td><td><input name="suggtel" id="suggtel" value="' + default_tel + '" class="input" type="text" /></td></tr>' + '<tr><td>&nbsp;</td><td><input name="subsuggest" id="subsuggest" value="提交" type="button" /> <a href="/static/qa_service.html" target="_blank">常见问题解答</a></td></tr>')
	}

function append_intro(city, channel){
    var channel_name = "";
    if(channel.toLowerCase() == "rent"){
        channel_name = "租房";
    }else{
        channel_name = "二手房";
    }
    var text = "九九房搜索了58同城房产、搜房网、易居网、个人房源网、焦点房地产网、新浪房产网上所有的"+channel_name+"信息，经过人工精心测试和程序的筛选，给您提供了较真实的个人房源，准确率为80%以上，我们这里也有网上最全的中介"+channel_name+"信息。欢迎您向我们九九房"+city+channel_name+"网提供帮助和建议。";
    $("#intro").append(text);
}

function test_user_win(channel, city_code){
    if(channel.toLowerCase() != 'house'){
        return;
    }
    var ratio = 10;
    if(city_code == "bj"){
        ratio = 50;
    }
    var url = "http://www.99fang.com/static/user_test.html";
    //get cookie
    var is_opened = cookies_fun('open_win');
    if(is_opened == 'true' || is_opened == 'false_2'){
        return;
    }
    var expires_time = 14;
    var options = { expires: expires_time, path: '/', domain: MAIN_DOMAIN, secure: false};
    random_val = Math.round((Math.random()) * 100);
    if(random_val > ratio){
        cookies_fun('open_win', 'false_2', options);
        return;
    }
    cookies_fun('open_win', 'true', options);
    window.open(url,'', 'menubar=yes,status=yes,toolbar=yes,resizable=yes,width=1000,height=600,scrollbars=yes');
}

function translate_url(url){
    return url.replace(/[_\/]/g, function(m){
        if (m=="/"){
            return "_";
        }else if(m=="_"){
            return "/";
        }else{
            return m;
        }
    });
}

$(function(){
	//底部seo样式
	$("#bottom-seo-recommend").css("width",$("#bottom-seo-recommend span").width());
	$("#bottom-seo-city").css("width",$("#bottom-seo-city span").width());

	//用户调查浮动层 js
	$("#research-win").find(".close-btn").click(function(){
		$("#research-win").css("display","none");
	});

    $("span[data-src]").each(function(){
        var $self = $(this);
        var src = $self.attr("data-src");
        $self.attr("data-src", translate_url(src));
        var html = $self.clone().wrap('<div></div>').parent().html();
        html = html.replace(/span/ig, "a");
        html = html.replace(/data-src/ig, "href");
        $self.replaceWith(html);
    });

    //显示历史搜索条件
    H_C.init_history_condition();

	//搜索页seo信息替换 js
    var seo_str = "";
    var $seo_slogan = $(".seo-slogan");
    if($seo_slogan.attr('valfromid') != 'qq' ){
        seo_str = "九九房搜索引擎--";
    }
    seo_str += "过去<span>&nbsp;1&nbsp;</span>分钟为您从<span>&nbsp;"+$seo_slogan.attr('valweb')+"&nbsp;</span>家网站发现<span>&nbsp;"+$seo_slogan.attr('valcount')+"&nbsp;</span>条"+$seo_slogan.attr('valcity')+"信息";
	$seo_slogan.html(seo_str);
	
	$(".seo-time").each(function(){
		$(this).text($(this).attr('rel'));
    });
	
	//聚合页信息条数替换 js
	var info_total_num = $("input[name='info-total-num']").val();
	var gather_total_num = $("input[name='gather-total-num']").val();
	$("#gather-info-line").text("发现" + info_total_num + "，已聚合为" + gather_total_num);
	$("#search-info-num").text("共发现" + info_total_num + "条信息");	
	
    var $gather_link_arr = $(".gather-info-link");
    $gather_link_arr.each(function(i, element){
        var $elm = $(element);
        $elm.html($elm.attr('rel')+"条相似信息");
    });
	
	$(".more-gather-info a").text("更多相似信息>>");
    
	//=======================================
    $(".gather-list").find(".gather-item").bind("mouseover mouseout", function(){
        $(this).toggleClass("hottd");
    });
    //详情按钮点击显示效果
    var $listtab = $(".listtab");
    var $list_items = $listtab.find("blockquote");
    $list_items.bind("mouseover mouseout", function(){
        $(this).toggleClass("blockquote-hover");
    }).bind("click", function(){
        $(this).css("color", "#551A8B");
    });
    $listtab.find(".open-link").click(function(){
        if(link_state!=0){
            var type = $(this).find("input:hidden[name='item_click']").val();
            var channel = $(this).find("input:hidden[name='item_channel']").val();
            var title = $(this).find("input:hidden[name='item_title']").val();
            var href = $(this).find("input:hidden[name='item_url']").val();
            var target = $(this).find("input:hidden[name='item_target']").val();
            var gaIdentifier = $(this).find("input:hidden[name='item_ga_id']").val();
            visitItem(type, channel, title, href, target, gaIdentifier,1);
            $(this).find("dt a").css("color","#551A8B");
            $(this).find(".info-title a").css("color","#551A8B");
        }
    })
    $listtab.find(".extend-link ul").click(function(){
        if(link_state!=0){
            if($(this).parent().find(".depand-detail-box").css("display")=="none"){
                var channel = $("input:hidden[name='item_channel']").eq(0).val();
                if(channel == 'House'){
                    channel = 'house';
                }else{
                    channel = 'rent';
                }
                var page_view = "/vhit/searchpage?extend=true&channel="+channel;
                var traffic_mode = $("#traffic_mode").val();
                if(traffic_mode){
                    page_view += "&type="+traffic_mode;
                }
                $(this).find(".detail-open-btn").addClass("detail-close-btn");
                $(this).siblings(".depand-detail-box").css("display","block");
                $(this).parent().css("background","#fff");
                ga_statistics(page_view);
            }else if($(this).parent().find(".depand-detail-box").css("display")=="block"){
                $(this).find(".detail-open-btn").removeClass("detail-close-btn");
                $(this).siblings(".depand-detail-box").css("display","none");
                $(this).parent().css("background","");
            }
        }
    })

    $listtab.find(".search-item blockquote").hover(function(){
        link_state=0;
    }, function(){
        link_state=1;
    });

    //对我爱我家的url添加400电话
    var channel = $('#channel').val();
    var idArray = [];
    var $5i5jArr = $list_items.filter("[marked_id]");
    $5i5jArr.each(function(){
        idArray.push($(this).attr("marked_id"));
    });
    if(idArray.length){
        $.getJSON("http://www.99fang.com/service/getcpc.js?jsoncallback=?", {
            "idArray": idArray.toString(),
            "channel": channel,
            "customer": "5i5j" 
        }, function(data){
            var masterNumber = data.master_number;
            var extNumberArray = data.ext_number_list;
            $.each(extNumberArray, function(i, value) {
                var extNumber = value.ext_number;
                var phoneNumber = value.phone_number;
                if(masterNumber && extNumber){
                    var $cur_elmt = $5i5jArr.eq(i);
                    var url = $cur_elmt.attr("ref");
                    var separator = get_sep(url);
                    var url400 = [url, separator, "master_number=", masterNumber,
                    "&ext_number=", extNumber, "&phone_number=", phoneNumber];
                    $cur_elmt.attr("ref", url400.join(""));
                }
            });
        });
    }
});

function get_sep(url){
    return url.indexOf("?")==-1 ? "?" : "&";
}

$(function(){
    $('a[ga_stat]').each(function(){
        var jthis = $(this);
        var href = jthis.attr('href');
        var separator = get_sep(href);
        jthis.attr('href', href + separator + 'ga_stat=' + jthis.attr('ga_stat'));
    });
});


