//TAB页签
function setTab(name,cursel,n){
	for(i=1;i<=n;i++)
	{
		var menu=document.getElementById(name+i);
		var con=document.getElementById("con_"+name+"_"+i);
		menu.className=i==cursel?"tab_active":"tab_normal";
		con.style.display=i==cursel?"block":"none";
	}
}

//下拉搜索框
$(function(){
		   
	$("span.btn")
	.hover(
	  function () {
		$(this).addClass("hover");
		$(this).prev(".txt").css({"font-weight":"700"});
	  },
	  function () {
		$(this).removeClass("hover");
		$(this).prev(".txt").css({"font-weight":"400"});
	  }) 
	.click(function(event){
		$(".super_select").fadeOut(200);
		$(this).next(".super_select").show();
	});
	
	$(".super_select dd a").click(function(event){
		var selected = $(this).text()
		$(this).parents(".super_select").fadeOut(200);
		$(this).parents(".super_select").siblings(".txt").attr({value: selected});
		return false;
	});

	$(document).mouseup(function(event){
		$(".super_select").fadeOut(200);
	});

 }); 
//选择城市
$(function(){
		   
	$(".city a")
	.click(function(event){
		$(".area").fadeOut(200);
		$(".area").show();
	});
	
	$(".area a").click(function(event){
		var city = $(this).text()
		$(this).parents(".area").fadeOut(200);
		$(".city strong").text(city);
		var cityCode=$(this).attr('code');
		changeCity(cityCode);
		changeCityClass(cityCode);
		return true;
	});

	$(document).mouseup(function(event){
		$(".area").fadeOut(200);
	});

 }); 

//注册表单
$(function(){
		   
	$("#register .txt")
	.focus(function(event){
		$(this).css({"background":"#edf8fe","border":"1px solid #97c3de"})
		$(this).next("div").show();
	})
	.blur(function(event){
		$(this).css({"background":"#FFF","border":"1px solid #C4E4F7"})
		$(this).next(".note").fadeOut(200);
	});
	

 }); 

//列表鼠标经过效果
$(function(){
	$(".table_con tr").hover(
		function () {
		$(this).addClass("hover");
	},
		function () {
		$(this).removeClass("hover");
	}
	); 
 }); 

  //家居秀横向滚动
$(function(){

	var $num= $("#scrollcom ul li").length;//获取图片个数
	$('#scrollcom ul').width(115*$num);//计算ul总宽度

	var $scrollcom = $('#scrollcom');//获取宽度
	$('.show_scroll .left a').click(function(){ //向左按钮绑定单击事件
	   if(!$scrollcom.is(":animated")){//判断是否处于动画
		$scrollcom.animate({ scrollLeft  : "-=345" } , 600);//每次滚动3个图片
		return false;
		}
	})
	$('.show_scroll .right a').click(function(){//向右按钮绑定单击事件
	   if(!$scrollcom.is(":animated")){
		$scrollcom.animate({ scrollLeft  : "+=345" } , 600);
		return false;
		}
	});
	
	$("#scrollcom img").hover(
		function () {
		$(this).addClass("hover");
	},
		function () {
		$(this).removeClass("hover");
	}
	); 
	
});
//家居秀按钮定位,图片大小限制
$(function(){
	var $h=$(".roomphoto_show").height();
	$(".roomphoto_show .left,.roomphoto_show .right").css({"top":$h/2-27});
	var $w=$(".roomphoto_show img").width();
	if($w>700){
		$(".roomphoto_show img").width(700)
		}
 });

//快照页面左右列高相等
$(function(){

	var div_h =$(".snapshot_l").height();
	$(".snapshot_r .con_c").height(div_h-28);
 });

//弹窗
$(function(){
	var $form_h=$(".pop_up form").height();//ie6下遮罩select bug,增加iframe
	$(".pop_up iframe").height($form_h);

	
	setInterval(function(){
	  $(".pop_up").each(function(){
		  $(this).css("top",$(window).scrollTop()+400);
	  });
	}, 100);

 });


function getOs()  
{  
   var OsObject = "";  
   if(navigator.userAgent.indexOf("MSIE")>0) {  
        return "MSIE";       //IE浏览器
   }
   if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){  
        return "Firefox";     //Firefox浏览器
   }
   if(isSafari=navigator.userAgent.indexOf("Safari")>0) {  
        return "Safari";      //Safan浏览器
   }
   if(isCamino=navigator.userAgent.indexOf("Camino")>0){  
        return "Camino";   //Camino浏览器
   }
   if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){  
        return "Gecko";    //Gecko浏览器
   }
} 

var xmlHttp; 
var data=null;
function changeCity(cityCode, callBackFunc)
{
	var os_type = getOs();
    if(window.ActiveXObject) {
      xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
    } else if(window.XMLHttpRequest) {
      xmlHttp=new XMLHttpRequest;
    }
    request="/index.php?action=ajax|GetDistrict&city="+cityCode;//window.open(request);

	if(callBackFunc!=null)
	{
		 xmlHttp.onreadystatechange=eval(callBackFunc+"()");
	}
	else
	{
		xmlHttp.onreadystatechange=(os_type!="Firefox")?(changeCityOK):(changeCityOK());
	}
    xmlHttp.open("GET", request, false);
    xmlHttp.setRequestHeader("Cache-Control","no-cache");
    xmlHttp.send(null); 

	if(callBackFunc!=null)
	{
		 xmlHttp.onreadystatechange=eval(callBackFunc+"()");
	}
	else
	{
		xmlHttp.onreadystatechange=(os_type!="Firefox")?(changeCityOK):(changeCityOK());
	}

}

function changeCityOK() {
    if(xmlHttp.readyState==4) {
      if(xmlHttp.status==200) {
        var dataJson=xmlHttp.responseText;
		if (dataJson == '')
		{
			data = '';
		}
		else 
		{
			data=eval("("+dataJson+")");
		}
		//修改区域内容
		$("dl.super_select.ss1 > dd").each(function(){
			var onclick_attr = $(this).find('a').attr('onclick');
			onclick_attr = String(onclick_attr);
			var id_type = '';
			if (onclick_attr.indexOf('newhouse_area') > 0) {
				id_type = 'newhouse_area';
			}
			else if (onclick_attr.indexOf('ershou_area') > 0)
			{
				id_type = 'ershou_area';
			}
			else if (onclick_attr.indexOf('rent_area') > 0)
			{
				id_type = 'rent_area';
			}
			var innerhtml = "<a href=\"javascript:void(0);\" value='' type=\"area\" onclick=\"selectErshouCondition(this.value, document.getElementById('"+id_type+"'));\">不限</a>";
			
			for(index in data['district'])
			{	
				innerhtml += "<a href=\"javascript:void(0);\" value='"+index+"' type=\"area\" onclick=\"selectErshouCondition("+index+", document.getElementById('"+id_type+"'));\">"+data['district'][index][0]+"</a>";
			}
			$(this).html(innerhtml);
		})
		changeDistrictInput();
		
		districtSelect=document.getElementById('district');
		changeRefresh=document.getElementById('change_refresh');
		if(typeof(districtSelect)!="undefined" && districtSelect!=null)
		{
			districtSelect.innerHTML="";
		    for(index in data['district']){
			    var oneOption=document.createElement("option");
                oneOption.text=data['district'][index][0];
                oneOption.value=String(index);//alert(String(defaultDistrict)==oneOption.value);
			    districtSelect.options.add(oneOption);
			    if(typeof(defaultDistrict)!="undefined" && defaultDistrict!=null && String(defaultDistrict)==oneOption.value){oneOption.selected=true;}
		    }
			if(typeof(defaultDistrict)!="undefined" && defaultDistrict!=null)
			{
				changeArea(data['allarea'][defaultDistrict]);
			}
			else
			{
				changeArea(data['area']);
			}		
			$('#district').bind('change', modifyArea);
		}
		else if(typeof(changeRefresh)!="undefined" && changeRefresh!=null)
		{
			window.location.reload();
		}
		
      }
    }
}

function modifyArea()
{
	var areaid = this.value;
	if(data!=null)
	{
		for(index in data['allarea'])
		{
		    if (index == areaid)
		    {
				changeArea(data['allarea'][index]);
		    }
		}
	}
}

function changeArea(areas)
{
	var areaDiv='';
	if(areas!=null)
	{
		for(index in areas)
		{
		    if(typeof(defaultArea)!="undefined" && defaultArea!=null && (","+defaultArea+",").indexOf(","+index+",")!=-1)var checked="checked";else var checked="";
			areaDiv+="<label><input name='servicearea[]' type='checkbox' value='"+index+"' "+checked+"/>"+areas[index][0]+"</label>";
		}
		document.getElementById("area").innerHTML=areaDiv;
	}
	if (typeof(areas) == "undefined" || areas == '')
	{
		document.getElementById("area").innerHTML='';
	}
}
/*
function changeArea()
{
	var areaDiv='';
	if(data!=null)
	{
		for(index in data['area'])
		{
		    if(typeof(defaultArea)!="undefined" && defaultDistrict!=null && (","+defaultArea+",").indexOf(","+index+",")!=-1)var checked="checked";else var checked="";
			areaDiv+="<label><input name='servicearea[]' type='checkbox' value='"+index+"' "+checked+"/>"+data['area'][index]+"</label>";
		}
		document.getElementById("area").innerHTML=areaDiv;
	}
}*/
function changeAuthImg(imgID)
{
	document.getElementById(imgID).src="class/action/vimg.php?ran="+Math.random();	
}

function SetHome(obj,vrl){ 
        try{ 
                obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl); 
        } 
        catch(e){ 
                if(window.netscape) { 
                        try { 
                                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
                        } 
                        catch (e) { 
                                alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将 [signed.applets.codebase_principal_support]的值设置为'true',双击即可。"); 
                        } 
                        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); 
                        prefs.setCharPref('browser.startup.homepage',vrl); 
                 } 
        } 
} 



	//obj	所有要添加mousedown事件的对象,jquery对象
	//tag	列表的标签如li,tr
	//向后台抛送用户点击日志
	function addmousedownevent(obj,tag){
			obj.mousedown(function(){
			t=$("#type").val();
			if(typeof($("#tradetype").val())!='undefined')
			t+=$("#tradetype").val();
			k=$("#keyword1").val();
			p=$.trim($("div.pages a.current").eq(0).text());
			u=$(this).parents(tag).find('a').eq(0).attr("href");
			reg=/index\.php\?/;
			is=(reg.exec($(this).attr('href')))?1:0;
			n=(t!='sjiaju')?$.trim($("div.title p.fr span").eq(0).text()):$.trim($("div.breadcrumbs2 p strong").eq(0).text());
			n=n?n*1:0;
			o=$(this).parents(tag).eq(0);
			po=(o.parent().find(tag).index(o))*1+1;
			//将最近浏览记录写入cookie
			viewurl=is?$(this).attr('href'):u;
			price=$(".price").eq(po-1).attr("title");
			percookie=$.trim($(this).parents(tag).find('h2').eq(0).text())+'|||'+viewurl+'|||'+price;
			var currentview=getCookie('currentview');
			if(typeof(currentview)=='string' && currentview.length>1)
			{
				currentview=percookie+'---'+currentview;
				currentview=currentview.substring(0,1000);
			}
			else
				currentview=percookie;
			
			setCookie('currentview',currentview,4320);
			sel=$('a.selected');
			filter='';
			for(i=0;i<sel.size();i++)
			{
				filter+="&"+sel.eq(i).attr('rel');
				filter+='='+sel.eq(i).text();
			}
			filter=encodeURIComponent(filter.substring(1));
			$.ajax({
				type	:'post',
				url	:'/static/static_log.php',
				data	:'type='+t+'&keyword='+encodeURIComponent(k)+'&page='+p+'&url='+encodeURIComponent(u)+'&isqshow='+is+'&restot='+n+'&pos='+po+'&filter='+filter
			})
		});
	}
	
	function logInfo(url,total,pos,key,type,tradetype,page,kz,filter,id)
	{
			t=type+tradetype;
			k=encodeURIComponent(key);
			p=page?page:0;
			is=kz;
			n=total?total:0;
			po=pos;
			u=encodeURIComponent(url);
			filter=encodeURIComponent(filter);
			$.ajax({
				type	:'post',
				url	:'/static/static_log.php',
				data	:'type='+t+'&keyword='+k+'&page='+p+'&url='+u+'&isqshow='+is+'&restot='+n+'&pos='+po+'&filter='+filter+'&id='+id,
				success: function(msg){ }
			})
	}
	///想后台抛送查询日志
	function sendsearchlog()
	{
		t=$("#type").val();
		if(typeof($("#tradetype").val())!='undefined')
		t+=$("#tradetype").val();
		k=$("#keyword1").val();
		n=(t!='sjiaju')?$.trim($("div.title p.fr span").eq(0).text()):$.trim($("div.breadcrumbs2 p strong").eq(0).text());
		p=0;is=0;po=0;u=0;
		c=$("#this_city").text();
		if(k=='' || n<1)return;
		$.ajax({
			type	:'post',
			url	:'/static/static_log.php',
			data	:'type='+t+'&keyword='+k+'&page='+p+'&url='+u+'&isqshow='+is+'&restot='+n+'&pos='+po+"&city="+c
		});
	}

function filter_str(str)
{	
	if(typeof(str)=='undefined' || str.length<=0)return '';
	interval=typeof(arguments[1])!='undefined'?arguments[1]:' ';
//	str=DBC2SBC(str)
	return str.replace(/[^\u4E00-\u9FA5a-zA-Z0-9]/g,interval)
}
//*　参数说明:
//* str:要转换的字符串
//* flag:标记，为０时半转全，为非０时全转半 默认是1
//* 返回值类型：字符串
function DBC2SBC(str) {
var i;
var result='';
flag=typeof(arguments[1])!='undefined'?arguments[1]:1;
if (str.length<=0) {return false;}
for(i=0;i<str.length;i++)
{ 
str1=str.charCodeAt(i);
reg=/[^\u4E00-\u9FA5]/;
if(str1<125&&!flag&&reg.exec(str1))
result+=String.fromCharCode(str.charCodeAt(i)+65248);
else if(str1>125 && flag && reg.exec(str1))
result+=String.fromCharCode(str.charCodeAt(i)-65248);
else
result+=String.fromCharCode(str.charCodeAt(i));
}
return result;
}

function changeCityClass(cityCode)
{
	$(".area a").each(function(){
		$(this).removeClass();
		if($(this).attr('code') == cityCode)
		{
			$(this).addClass('red');
		}
	})
}

function changeDistrictInput()
{
	$(".super_select dd a").click(function(event){
		var selected = $(this).text()
		$(this).parents(".super_select").fadeOut(200);
		$(this).parents(".super_select").siblings(".txt").attr({value: selected});
		/*
		var type=$(this).attr("type");
		var value=$(this).attr("value");
		if(type=="area")
		{		  
		    $("#area").val(value);
		}
		if(type=="price")
		{
			$("#price").val(value);
		}
		if(type=="roommodel")
		{
			$("#roommodel").val(value);
		}*/
		return false;
	});
}

$(function(){
	document.onkeyup = function(event){
		event = event?event:window.event;
		if (event.keyCode == 13)
		{
			var activeElemId = document.activeElement.id;
			if (activeElemId == 'pageNumber')
			{
				var page = $('#pageNumber').val();
				changePage(page);
			};
			
		}
	};
});

function changePage(page)
{
	page = parseInt(page);
	if (page.length <= 0)
	{
		alert("页码不能为空！");
		$('#pageNumber').blur();
		return false;
	}
	var reg = /^[0-9]+$/;
	if (!reg.test(page))
	{
		alert('请输入整数！');
		$('#pageNumber').blur();
		return false;
	}
	var maxpage = $('#totalPage').val();
	maxpage = parseInt(maxpage);

	if (page < 1 || page > maxpage)
	{
		alert('输入的页码应该在1到'+maxpage+"之间！");
		$('#pageNumber').blur();
		return false;
	}
	var pageUrl = $('#pageUrl').val();
	if (pageUrl.indexOf('page=') < 0)
	{
		pageUrl += '&page='+page;
	}
	else
	{
		reg = /(page=[^&]+)/;
		pageUrl = pageUrl.replace(reg, "page="+page);
	}
	window.location = pageUrl;
}

//页面跳转的js函数
function gopage(total,num)
{
	url=document.getElementById('currenturl').value;
	page=document.getElementById('gopage').value;
	page=isNaN(parseInt(page))?0:parseInt(page);
	page=Math.round(page);
	if(page*num>total )
	{
		page=Math.ceil(total/num);
	}
	else if(page<1)
	{
		page=1;
	}
	window.location.href=url+"&page="+page;

}


//写cookies函数 
function setCookie(name,value,period)//3个参数，一个是cookie的名子，一个是值,一个是有效期单位分钟
{
    var period = period; 
    var exp  = new Date();    //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + period*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)//取cookies函数     
{
    var arr = document.cookie.match(new  RegExp("(^| )"+name+"=([^;]*)(;|$)"));
     if(arr != null) return unescape(arr[2]); return null;
}
function delCookie(name)//删除cookie
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

//显示最近浏览记录
function show_currentview(obj,n)//obj jquery对象,n最多显示条数
{

	var currentview=getCookie('currentview');
	
	if(typeof(currentview)=='string' && currentview.length>1)
	{
		var html="";
		if(currentview.indexOf('---')>1)
		{
			var currentviews=currentview.split('---');
			for(var i=0;i<n;i++)
			{
				if(typeof(currentviews[i])!='undefined' && currentviews[i].indexOf('|||')>1)
				{
					 precord=currentviews[i].split('|||');
					html+='<li><a href="'+precord[1]+'" target="_blank" title="'+precord[0]+'">'+precord[0].substring(0,8)+' -- <span class="orange">'+precord[2]+'</span>'+'</a></li>';
				}
			}
		}
		else if(currentview.indexOf('|||')>1)
		{
			 var precord=currentview.split('|||');
			html+='<li><a href="'+precord[1]+'" target="_blank" title="'+precord[0]+'">'+precord[0].substring(0,8)+' -- <span class="orange">'+precord[2]+'</span>'+'</a></li>';
		}
		else
		{
			html="<li>没有最近浏览记录!</li>";
		}
	}
	else
	{
		html="<li>没有最近浏览记录!</li>";
	}
	obj.html(html);
}

//添加到收藏夹
function addBookmark() {
title='fangdudu搜索';
url='http://www.fangdudu.com/';
var browser=getOs();
if (browser=='Firefox') { 
window.sidebar.addPanel(title, url,""); 
} else if( browser=='MSIE' ) {
	try{
		window.external.AddFavorite(url, title);
	}
	catch(e)
	{
		alert("添加失败,劳您手动添加!");
	}
} else if( window.opera && window.print ) {
return true;
}
}

//提交表单
function submit_check(key,form)
{
	key=document.getElementById(key);
	theform=document.getElementById(form);
	key.value=$.trim(key.value);
//	if(key.value.length>0)
//		key.value=filter_str(key.value);
	if(form=='sub_ershou' || form=='sub_house' || form=='sub_rent' || form=='sub_show' || form=='sub_jiaju')
	{
		if(key.value=='请输入搜索条件')key.value='';		
		theform.submit();
		return;
	}
	if(form=='sub_web' && (key.value==''|| key.value=='请输入搜索条件'))
		window.location.href="/index.php";
	if(key.value!='请输入搜索条件' && key.value.length>0)
	{
		theform.submit();
	}

}

//首页绑定值
function selectErshouCondition(val,obj,o){
	obj.value=val;
	t=typeof(arguments[2])=="undefined"?null:arguments[2];
	if(t==null)
		return 0;
	var pli=$(t).parents("li").eq(0);
	if(pli!=null && typeof(pli)!="undefined")
		pli.find("span").eq(0).text($(t).text());
	}

//绑定搜索全部
function bind_checkbox(bind_checkbox,target)
{
	if(bind_checkbox.checked==1)
		target.value=true;
	else if(bind_checkbox.checked==0)
		target.value=false;
}

//过滤输入框指定非Int字符
function filter_int(obj,event)
{
	event = event?event:window.event;
	if(event.keyCode==13 && parseInt(obj.value)>0)
	{
	$(obj).next('.pagebtn2').click();
	}
		
	obj.value=obj.value.replace(/[^\d]/,'');
}

function autoSubmit(event, object)
{
	event = event?event:window.event;
	if(event.keyCode==13)// && oInputField.value!='')
	{
//		oInputField.value=filter_str(oInputField.value);
		object.submit();
	}
}

//搜索感受弹窗
$(function(){
	//屏幕跟随
	setInterval(function(){
	  $(".msg_btn").each(function(){
		  $(this).css("top",$(window).scrollTop()+100);
	  });
	}, 100);
	
	
	//屏幕跟随
	setInterval(function(){
	  $(".msg_popup").each(function(){
		  $(this).css("top",$(window).scrollTop()+300);
	  });
	}, 100);
	
	
	
//	$(".msg_btn").toggle(
//		function () {
//				if(!$(".msg_popup").is(":animated")){
//					$(".msg_popup").animate({height:391,width:491,left:'50%'}, { duration:400 });
//				return false;
//				}
//			},
//		function () {
//				if(!$(".msg_popup").is(":animated")){
//					$(".msg_popup").animate({height:0,width:0,left:0}, { duration:400 });
//				return false;
//				}
//			}
//	); 

	//关闭弹窗
	$(".msg_popup .close").click(function(event){
		if(!$(".msg_popup").is(":animated")){
			$(".msg_popup").animate({height:0,width:0,left:0}, { duration:400 });
		return false;
		}
	});
	//点开弹窗
	$(".msg_btn").click(function () {
			if(!$(".msg_popup").is(":animated") & ($(".msg_popup").height()==0)  ){
				$(".msg_popup").animate({height:500,width:491,left:'50%'}, { duration:400 });
				return false;
			}
			else if(!$(".msg_popup").is(":animated") & ($(".msg_popup").height()==500)  ){
				$(".msg_popup").animate({height:0,width:0,left:0}, { duration:400 });
				return false;
			}
	}); 
	//关闭alert弹窗
	$(".popup3 .close").click(function(event){
		if(!$(".popup3").is(":animated")){
			$(".popup3").fadeOut(400);
		return false;
		}
	});

	
 });



 function reset(obj)
 {
	 var w=isNaN(parseInt(obj.width))?0:parseInt(obj.width);
	 var h=isNaN(parseInt(obj.height))?0:parseInt(obj.height);

	if(w>500)obj.wirth='500px';
	if(h>350)obj.height='350px';

 }



 //更多条件
$(function(){
	$("#s_cen").toggle(
		function () {
		$("#s_mores").addClass("show");
		$("#s_cen").addClass("s_cen2");
	},
		function(){
		$("#s_mores").removeClass("show");
		$("#s_cen").removeClass("s_cen2");
	}
	); 
 }); 
