function get_Date(tt){
	var tmp='未定';
	if(typeof (tt)=='undefined'||tt=='' || tt==null){
		return tmp;
	}
	var arr=tt.split(' ');
	return time1=arr[0];
}

function initAlbumPhoto() {
    var showBImg={}, bimgSwiper, typeSwiper;;
    showBImg.html=function(){
        var shopBigScrollBox=$('.shopBigScrollBox');
        var scrollCon=$('.lp-bunner ul').clone(true);
        shopBigScrollBox.html('');
        scrollCon.appendTo(shopBigScrollBox);

    };
    showBImg.count=function(){
        var $li=$('.shopBigScrollBox .swiper-wrapper .swiper-slide-active');
        var classname=$('#JsClassName');
        var index=$('#JsIndex');
        var sum=$('#JsSum');
        var $type = $("li", "#classNames").filter("[data-index=" + $li.attr('data-class') + "]");
        $type.addClass('on').siblings().removeClass('on');
        classname.text($type.text());
        index.text($li.attr('data-index'));
        sum.text($li.attr('data-sum'));
        $("#totalIndex").text($li.data("totalindex"));
        typeSwiper.slideTo(+$type.index(), 500, true);
    };

    $(function() {
        var swiper = new Swiper('.lp-bunner',{
            preloadImages: false, lazyLoading: true, lazyLoadingOnTransitionStart: true,
            onTransitionEnd: function(swiper){
                $('.lp-index').text(swiper.activeIndex+1);
            },
            onInit: function(swiper){
                $('.lp-index').text(swiper.activeIndex+1);
                $('.lp-sum').text(swiper.imagesToLoad.length || swiper.imagesLoaded || $('img', '.lp-bunner').size());
            },
            onClick:function(swiper){
                $('.shopBigBox').show();
                if ( ! bimgSwiper) {
                    bimgSwiper = new Swiper('.shopBigScrollBox',{
                        preloadImages: false, lazyLoading: true, lazyLoadingOnTransitionStart: true,
                        initialSlide:swiper.activeIndex,
                        onTransitionEnd:function(/*swiper*/){
                            showBImg.count();
                        },
                        onInit:function(){
                            showBImg.count();
                        }
                    });
                }
            }
        });
        var liWidth = $('.showBigClass li').click(function(){
            $(this).addClass('on').siblings().removeClass('on');
            var albumType = $(this).attr('data-index');
            var $li = $(".shopBigBox .swiper-wrapper").find("[data-class=" + albumType +"]:first");
            bimgSwiper.slideTo(+$li.data("totalindex") - 1, 500, true);
        }).width();
        typeSwiper = new Swiper('.showBigClass',{
            width: liWidth ? liWidth : 52.5
        });
        showBImg.html();


    });
}

// 根据内容滚动固定 Tab
function initBoxScrollFixed() {
    var $head = $("body>.head"), boxConditions = [];
    $(".main .box.scrollFixed").each(function(ind, box) {
        var $box = $(box),
            $tab = $box.find(">.box-tit"),
            $lis, liConList = [];
        if ( ! $tab[0]) {
            $tab = $box.find(">.tab");
            if ( ! $tab[0]) return;
            // 这是一个 tab 注册其余事件
            $lis = $tab.find("ul>li");
            var $curTabLi = $lis.removeClass("active").filter(":first").addClass("active");
            $("#" + $curTabLi.attr("id") + "-con").show();

            $lis.click(function() {
                var conId = $(this).attr("id");
                if ( !! conId) {
                    $lis.removeClass("active");
                    $(this).addClass("active");
                    $("div.tab-con>*", $box).hide();

                    var $con = $("#" + conId + "-con").show();
                    $("html,body").stop(true).animate({
                        scrollTop: $con.offset().top - $tab.height() * 2
                    }, 500);
                }
            });
        }

        var criticalPoint = $box.offset().top - $head.height() + 14,
            condition = {
                $box: $box,
                $tab: $tab,
                criticalPoint: criticalPoint,
                minCriticalPoint: criticalPoint + $box.height() - $tab.height() * 4
            };
        if (criticalPoint <= 0) return;

        if (liConList && liConList.length > 0) {
            // 降序排序
            liConList = liConList.sort(function(a, b) {
                return a.criticalPoint < b.criticalPoint;
            });
            condition.callback = function() {
                $.each(liConList, function(ind, licon) {
                    if (window.scrollY >= licon.criticalPoint) {
                        $lis.removeClass("active");
                        licon.$li.addClass("active");
                        return false;
                    }
                });
            };
        }

        boxConditions.push(condition);
    });
    boxConditions = boxConditions.sort(function(a, b) {
        return a.criticalPoint < b.criticalPoint;
    });
    if (boxConditions.length > 0) {
        $(window).scroll(function() {
            var fixed = false;
            for (var i = 0; i < boxConditions.length; ++i) {
                var c = boxConditions[i];
                // 重新计算临近点
                c.criticalPoint = c.$box.offset().top - $head.height() + 14;
                c.minCriticalPoint = c.criticalPoint + c.$box.height() - c.$tab.height() * 4;
                if (!fixed && window.scrollY >= c.criticalPoint) {
                    if (window.scrollY >= c.minCriticalPoint) {
                        c.$tab.removeClass("fixed-top");
                    } else {
                        fixed = true;
                        c.$tab.addClass("fixed-top");
                        if (typeof c.callback === "function") {
                            c.callback.call(this);
                        }
                    }
                } else {
                    c.$tab.removeClass("fixed-top");
                }
            }
        });
    }
}

window.initAlbumPhoto = initAlbumPhoto;
window.initBoxScrollFixed = initBoxScrollFixed;


function get_li_item(index,index1,row,sum,img){

    return '<li class="swiper-slide" data-index="'+index+'" data-totalindex="'+index1+'" data-class="'+row+'" data-sum="'+sum+'">'
        +'<a>'
        +'<img class="swiper-lazy swiper-lazy-loaded" src="'+ServerHost+'/houseImg/'+img+'" alt="">'
        +'</a>'
        +'</li>';
}







$(document).ready(function(e){
    var id=getUrlParam("id");
    var _usertable = localStorage.getItem('usertable');
    if(_usertable === 'agents'){
    	var _level = localStorage.getItem('level');
    	if(_level == '4' || _level == '6'){
    		$('#caipan_link').css("display","block");
    	}
    }
    
    var _share = getUrlParam('share');
    if(_share == "1"){
    	var _fix_top = $(".public");
		_fix_top.show();
		$(".pbl_cha").click(function() {
			_fix_top.hide();
		});
	
		jumpEvent();//添加跳转app页面事件
    }
    


//*****************************yunfei 2016-10-26*******************************
//1.导入house_vrs表中对应id的vr链接
//当前为修改页面时通过houseid查询house_vrs表数据
     $.ajax({
        url:ServerHost+'/houseinfos/vr_url_houseid',//app注册
        data:{"id":id},
        type:"POST",
        dataType:"html",
        beforeSend:function(){},
        success:function(data1){
            // alert(data1);
          /*门店绑定楼盘*/
          if(data1=="no"){
             //无VR效果图隐藏
        	 $(".vr_kf").hide();
          }else{
           $("#vr_entry").show();
          $("#vr_house").append(data1);
          }
            },
            error:function(){alert("操作失败!");}
       });
//*****************************yunfei 2016-10-26*******************************






    $("#showcustomerlist").attr("href","customer.html?houseid="+id);
    $("#dajiangtanglink").attr("href","dajiangtang.html?id="+id);
    $("#fee_rule_link").attr("href","fee_rule.html?id="+id);

    //控制底部
    control_bottom_tab();

    $.ajax({
        url:ServerHost+"/houseinfos/getdetails",
        data:{"id":id},
        type:"POST",
        dataType:"text",
        beforeSend:function(){},
        success:function(responseText){
            var arr=responseText.split("||");
            var data1=eval("("+arr[0]+")");
            //账号类型
            var data3=eval("("+arr[2]+")");
            //最新动态标题
            var data4 = eval("("+arr[3]+")");
            //动态新闻id
            var data5 = eval("("+arr[4]+")");

            $("#title").html(data1.Houseinfo["title"]);
            $("#address").html(data1.Houseinfo["disc"]+"-"+data1.Houseinfo["address"]);
            $("#fee").html(data1.Houseinfo["fee"]+"万");
            $("#price").html(data1.Houseinfo["price"]);
            //判断该用户是门店、业务员还是市场部,如果是市场部那么就不显示
            if("3" == data3 || "4" == data3){
                //如果为门店,隐藏
            }else{
                if("0" == data1.Houseinfo['iscanreport']){
                   $("#applybuttonid").html("<a class='u_btn7' id='addapply'>报备客户</a>");
                   $("#addapply").attr("href","self-driving.html?id="+data1.Houseinfo["id"]);
                }
           }
            $("#housetelid").attr("href","tel:"+data1.Houseinfo["phone"]);

            //如果没有最新动态,那么就显示无
            if("" == data4){
                data4 = "暂无最新动态";
                $("#newsinfoid").attr("href","###");
            }else{
                $("#newsinfoid").attr("href","dynamicinfo_news.html?id="+data5+"&name="+data4);
            }

            $("#newsinfoid").html(data4);
            //卖点
            var sellingpoint='<h2 class="u_title3">楼盘卖点</h2>'
                +'<div class="u_des6 wordbox_lp">'+data1.Houseinfo["sellingpoint"]+'</div>';
            $("#sellingpoint").html(sellingpoint);

            //微楼书链接
            //$("#weilinks").attr("href",data1.Houseinfo["weilinks"]);
            $("#weilinks").attr("href","javascript:void(0)");
            if(data1.Houseinfo["weilinks"].length>0){
                $("#weilinks").attr("href","dajiangtang2.html?id="+id);
            }


            //案场电话
            $("#callhousephone").click(function(){
                window.location.href="tel://"+data1.Houseinfo["phone"];
            });


			var basicinfo='<li>'
				+'<p>开盘: </p>'
				+'<span>'+get_Date(data1.Houseinfo["opentime"])+'</span>'
				+'</li>';
			basicinfo+='<li>'
			+'<p>交房: </p>'
			+'<span>'+get_Date(data1.Houseinfo["committime"])+'</span>'
			+'</li>';
			basicinfo+='<li>'
			+'<p>产权: </p>'
			+'<span>'+data1.Houseinfo["prieod"]+'</span>'
			+'</li>';
			basicinfo+='<li>'
			+'<p>装修: </p>'
			+'<span>'+data1.Houseinfo["decorate"]+'</span>'
			+'</li>';
			basicinfo+='<li>'
			+'<p>类型: </p>'
			+'<span>'+data1.Houseinfo["type"]+'</span>'
			+'</li>';
			basicinfo+='<li>'
			+'<p>车位: </p>'
			+'<span>'+data1.Houseinfo["stops"]+'</span>'
			+'</li>';
			basicinfo+='<li>'
			+'<p>总户数: </p>'
			+'<span>'+data1.Houseinfo["totalhouse"]+'</span>'
			+'</li>';
			basicinfo+='<li>'
			+'<p>建筑面积: </p>'
			+'<span>'+data1.Houseinfo["area"]+'㎡</span>'
			+'</li>';
			basicinfo+='<li>'
			+'<p>开发商: </p>'
			+'<span>'+data1.Houseinfo["developer"]+'</span>'
			+'</li>';
			basicinfo+='<li>'
			+'<p>物业公司: </p>'
			+'<span>'+data1.Houseinfo["wuye"]+'</span>'
			+'</li>';
			$("#basicinfo").html(basicinfo);

			var data2=eval("("+arr[1]+")");

            var image_0="";
            var image_4_1="";

            var image_1="";//效果图
            var image_2="";//实景图
            var image_3="";//样板图
            var image_4="";//户型图
            var image_5="";//交通图
            var image_4_num=0;

            //每种图数量
            var sum_img_1=0;
            var sum_img_2=0;
            var sum_img_3=0;
            var sum_img_4=0;
            var sum_img_5=0;

            //index
            var index_item_1=0;
            var index_item_2=0;
            var index_item_3=0;
            var index_item_4=0;
            var index_item_5=0;
            var index_item_all=0;


            $.each(data2, function(i, item) {
                image_0+='<div class="swiper-slide">'
                    +'<img src="'+ServerHost+'/houseImg/'+item.Houseimg["imagename"]+'"/>'
                    +'</div>';
                index_item_all++;
                switch (parseInt(item.Houseimg["imgtype"])){
                    case 1:{
                        sum_img_1++;
                        index_item_1++;
                        image_1+=get_li_item(index_item_1,index_item_all,101,"sum_img_1",item.Houseimg["imagename"]);
                        break;
                    }
                    case 2:{
                        sum_img_2++;
                        index_item_2++;
                        image_2+=get_li_item(index_item_2,index_item_all,102,"sum_img_2",item.Houseimg["imagename"]);
                        break;
                    }
                    case 3:{
                        sum_img_3++;
                        index_item_3++;
                        image_3+=get_li_item(index_item_3,index_item_all,103,"sum_img_3",item.Houseimg["imagename"]);
                        break;
                        break;
                    }
                    case 4:{
                         image_4_1 += '<li class="m_ping1">'
                                + '<a href="imagebody.html?img_name='+item.Houseimg["imagename"] + '&name=' + item.Houseimg["img_title"] + '&address=1"><img src="'+ServerHost+'/houseImg/small_' + item.Houseimg["imagename"] + '" /></a>'
                                + '</li>';
						image_4_num++;
                        //tab
                        sum_img_4++;
                        image_4+=get_li_item(index_item_4,index_item_all,104,"sum_img_4",item.Houseimg["imagename"]);
                        break;

                        break;
                    }
                    case 5:{
                        sum_img_5++;
                        index_item_5++;
                        image_5+=get_li_item(index_item_5,index_item_all,105,"sum_img_5",item.Houseimg["imagename"]);
                        break;
                        break;
                    }
                }
            });
            image_1 = image_1.replace(new RegExp("sum_img_1",'gm'),sum_img_1);
            image_2 = image_2.replace(new RegExp("sum_img_2",'gm'),sum_img_2);
            image_3 = image_3.replace(new RegExp("sum_img_3",'gm'),sum_img_3);
            image_4 = image_4.replace(new RegExp("sum_img_4",'gm'),sum_img_4);
            image_5 = image_5.replace(new RegExp("sum_img_5",'gm'),sum_img_5);

            //正式加载，不成功
            $("#img_item_ul").html(image_1+image_2+image_3+image_4+image_5);
            initAlbumPhoto();
            initBoxScrollFixed();

            if(sum_img_1==0){
                $("#handle_img_1").hide();
            }
            if(sum_img_2==0){
                $("#handle_img_2").hide();
            }
            if(sum_img_3==0){
                $("#handle_img_3").hide();
            }
            if(sum_img_4==0){
                $("#handle_img_4").hide();
            }
            if(sum_img_5==0){
                $("#handle_img_5").hide();
            }



            //$("#image_4_1_title").html('住宅'+image_4_num+'个户型');
            $("#image_4_1").html(image_4_1);
            $("#allimgs").html(image_0);
            //设置大图展示总数
            $("#totalIndex").next().html($(".lp-sum").html());
           /* var mySwiper = new Swiper('.swiper-container',{
                pagination: '.pagination',
                loop:true,
                grabCursor: true,
                paginationClickable: true
            })*/

            //tab大图，样式待定
            //$("#allimgs1").html(image_1+image_2+image_3+image_4+image_5);
            /*var mySwiper1= new Swiper('.swiper-container2',{
                pagination: '.pagination2',
                loop:true,
                grabCursor: true,
                paginationClickable: true
            })*/

        },
        error:function(){}
    });
});

function canceldetail(){
	window.location.href="index.html";
}

//聊天初始化
function chat_init(){
	console.info(getUrlParam("id"));
	var house_id = getUrlParam("id");

	$.ajax({
        url: ServerHost + "/TmOpenIM/advisory_agent_company",
        type: "POST",
        dataType: "JSON",
        data: {
            "rand": Math.random(),
            "house_id": house_id,
            // "host": ServerHost,
            "version" : "1.0"
        },
        success: function(data) {
        	//console.info(data);
        	//return false;

        	if(data['code'] == '1'){
        		console.info('LOGIN SUCCESS');
        		localStorage.tm_chat_user_id = data['data']['tm_userid'];
        		localStorage.tm_chat_user_type = '1';//用户类型:1.门店人员,2.市场部人员,3.案场人员
        		localStorage.tm_chat_user_password = data['data']['tm_password'];
        		localStorage.tm_chat_tribe_id = data['data']['tribe_id'];
        		localStorage.tm_chat_appkey = data['data']['appkey'];

        		window.location.href = "chat_talk.html?house_id=" + house_id + '&isshowmsg=0';
        		return false;
        	}
        	console.info(data['msg']);
        	alert(data['msg']);
        },
        error: function(e) {
        	console.info('LOGIN ERROR');
        }
    });
}

//控制底部按钮
function control_bottom_tab(){
	$.ajax({
        url: ServerHost + "/TmOpenIM/judge_agent",
        type: "POST",
        dataType: "JSON",
        data: {
            "rand": Math.random(),
        },
        success: function(data) {
        	if(data['code'] == '1'){
        		var level = data['data']['level'];
        		if(level == '1' || level == '2'){
        			//经纪人显示咨询
                    $('.m_part3_w .consultLink').show();
                    $('.m_part3_w li').css("width","25%");
        		}else{
                    $('.m_part3_w .consultLink').hide();
                    $('.m_part3_w li').css("width","33.33%");
                }

        		return false;
        	}
        	console.info(data['msg']);
        },
        error: function(e) {
        	console.info('judge_agent ERROR');
        }
    });
}
