fontEndEasy / socket.io

0 stars 0 forks source link

javascript components.v01 #1

Open fontEndEasy opened 8 years ago

fontEndEasy commented 8 years ago
/**
 * @注释标准:
 * @description 功能描述
 * @param {String} name 需要获取的参数如type
 * @param {String} url 缺省:window.location.href
 * @author authorName
 * @return {String}
 * @example
*/
DDS={};//最大一层的命名空间

//喜欢相关js
DDS.ILike={};
DDS.Tools = {};
DDS.ILike.config={//配置
    like_button:'.ilike',//喜欢按钮的样式名称
    iliked_class:'iliked',//喜欢过的变成灰色
    like_count:'.like-num',//被喜欢的数目
    like_text:'.like-text',//被喜欢的数目
    like_url:'/article/ilike',//
    Msg:{
        likeOk:'已点亮',//'ok,喜欢啦!',
        repeatLike:'点亮过了'//'亲你已经喜欢过了哦!'
    }
};
DDS.ILike.Init=function(){//进行相关的初始化操作
    //给按钮绑定事件
    $(DDS.ILike.config.like_button).on("click", function() {
        var share_id=$(this).attr('share_id');
        DDS.ILike.DoLike(share_id);
    });   
};
DDS.ILike.DoLike=function(share_id){

    /**
     * 1.判断用户是否登录了 未登录直接弹出登录窗口
     * 2.登录成功的 调用添加喜欢的方法
     */
    var callback=escape("DDS.ILike.RealDoLike('"+share_id+"')")
    checkIsLogin(callback);
};
DDS.ILike.RealDoLike=function(share_id){

    if ( window.noUserName ) {
        showAddName();
        return false;
    }

    var obj=$(".ilike[share_id='"+share_id+"']");
    var type = obj.attr("data-type");
    DDS.ILike.config.like_url = type == "group" ? "/article/ilike" : DDS.ILike.config.like_url;
    $.ajax({
        url:DDS.ILike.config.like_url,
        type:'get',
        data:{'share_id':share_id},
        success:function(d){
            if(d.task){
                alert('您的点亮已经获得1点成长值');
            }
            switch(d.code){
                case 'likeOk':
                    obj.removeClass(DDS.ILike.config.like_button.replace('.',''));      
                    obj.addClass(DDS.ILike.config.iliked_class);
                    obj.children(DDS.ILike.config.like_text).text(DDS.ILike.config.Msg[d.code]);
                    obj.children(DDS.ILike.config.like_count).text(parseInt(obj.children(DDS.ILike.config.like_count).text())+1);               
                    break;
                case 'repeatLike':
                    obj.removeClass(DDS.ILike.config.like_button.replace('.',''));
                    obj.addClass(DDS.ILike.config.iliked_class);
                    obj.children(DDS.ILike.config.like_text).text(DDS.ILike.config.Msg[d.code]);              
                    break;
                default:
                    alert(d.msg);
                    break;
            }
        },
        dataType:'jsonp',
        jsonp:'jsonp',
        jsonpCallback:'jsonp'
    })        
};

//店铺收藏相关js
DDS.CollectShop={};
DDS.CollectShop.config={
    icollect:'.icollect',//收藏店铺按钮
    lcollection_url:'/fav/collectshop',//request url
    Msg:{
        collectionOk:'已收藏',//'ok,喜欢啦!',
        repeatCollection:'收藏过了'//'亲你已经喜欢过了哦!'
    }
};//配置
DDS.CollectShop.Init=function(){//进行相关的初始化操作
    //给按钮绑定事件
    $(DDS.CollectShop.config.icollect).live({
        click: function() {
            var shop_id=$(this).attr('shop_id');
            DDS.CollectShop.DoCollect(shop_id);
        }
    });   
};
DDS.CollectShop.DoCollect=function(shop_id){

    /**
     * 1.判断用户是否登录了 未登录直接弹出登录窗口
     * 2.登录成功的 添加收藏
     */
    var callback=escape("DDS.CollectShop.RealDoCollect('"+shop_id+"')");
    checkIsLogin(callback)
};
DDS.CollectShop.RealDoCollect=function(shop_id){

    /**
     * 1.判断用户是否登录了 未登录直接弹出登录窗口
     * 2.登录成功的 添加收藏
     */
    if(checkIsLogin()){//表示登录成功了        
        $.get(DDS.CollectShop.config.lcollection_url, {
            shop_id:shop_id
        }, function(d){
            switch(d.code){
                case 'collectionOk':
                case 'repeatCollection':
                    alert(d.msg);              
                    break;
                default:
                    alert(d.msg);
                    break;
            }
        }, 'json');
    }    
};

//瀑布流
DDS.Waterfall={};
DDS.Waterfall.config={
    subPage:0,//当前页面分步加载的子页面序号 默认是0
    is_end:false,//表示是否还可以继续从后台加载数据
    is_can_load:true,//防止一个ajax没有加载完另外一个又开始加载了
    ajaxUrl:'/share/ajax',//request url
    pagingContainer:'.share_page',//承载分页的容器
    shareColContainer:'.share_col',//承载列的容器
    loadingPic:'http://static.dotdotbuy.com/images/loading_32_32.gif?t=20130125',//loading图片
    loadingDiv:'.loadingDiv',//
    mainDiv:'.share_col_list',
    listPicContainer:'.share_logo'
};
DDS.Waterfall.get_subpage=function(sub_page,DOTDOTPROFILE,type){//取得某个子页的数据
    DDS.Waterfall.config.is_can_load=false;
    var loading_html='<div class="clear '+DDS.Waterfall.config.loadingDiv.replace('.','')+'"><img src="'+DDS.Waterfall.config.loadingPic+'"/></div>';
    $(DDS.Waterfall.config.mainDiv).append(loading_html);
    $.ajax({
        url : DDS.Waterfall.config.ajaxUrl,
        type : 'post',
        data : {
            list_ids:DOTDOTPROFILE.list_ids,
            page:sub_page
        },
        dataType : 'json',
        //timeout : 1000,
        error : function() {
            $(DDS.Waterfall.config.loadingDiv).remove();
            DDS.Waterfall.config.is_can_load=true;
        },
        success : function(d) {
            $(DDS.Waterfall.config.loadingDiv).remove();
            DDS.Waterfall.config.is_can_load=true;
            DDS.Waterfall.config.is_end=d.is_end;//确定是否是最后一个子页
            if(DDS.Waterfall.config.is_end){//显示分页
                $(DDS.Waterfall.config.pagingContainer).html(DOTDOTPROFILE.page_links);
            }
            DDS.Waterfall.append_data(d.goods_list,type);
            DDS.Tips.UserTips($('.share_userface img'));
        }
    });

}
DDS.Waterfall.get_one_goods_html=function(json,type){//根据返回结果 构造数据
    var content='';         
    var price=json['g_price'];
    if(price.toString().indexOf('.')!==-1){//表示是个小数
        price=price.toFixed(2);
    }

    var host=window.location.host;

    host=host.split('.');
    if (type=='new') {
    content+='<div class="iwf">';
    content+='  <div class="img share_logo">';
    content+='    <a href="/book/'+json['id']+'" class="img" target="_blank">';
    content+='    <img src="http://static.'+host[1]+'.com/images/grey.gif"  data-original="'+json['main_pic_src']+'"  title="'+json['goods_name']+'" />';
    content+='  </a>';
    content+='  </div>';
    content+='  <div class="pd">';
    content+='      <p class="title">';
    content+='        <a href="/book/'+json['id']+'" target="_blank" class="no_icons">'+json['icon_code'] + '&nbsp;' + json['goods_name']+'</a>';
    content+='      </p>';
    content+='      <div class="goods_info">';
    content+='        <b class="price_info">';
    content+='        <i>¥</i>'+price+'</b>';
    content+='      </div>';
    content+='      <div class="goods_fav">';
    content+='          <a class="fav_num fr" share_id="'+json['id']+'" href="###"><i class="icon icon-fav"></i><span class="like-num">'+json['liked']+'</span></a>';
    content+='          <a class="comment_num" href="/book/'+json['id']+'" target="_blank"><i class="icon icon-comment"></i><u>'+json['commentnum']+'</u></a>';
    content+='      </div>';
    content+='  </div>';
    content+='</div>';
    } else {
        content+='<div class="share_show">';
        content+='<div class="share_logo"><a style="height:235px;overflow:visible;" href="/book/'+json['id']+'" target="_blank"><img height="235" src="http://static.'+host[1]+'.com/images/grey.gif" data-original="'+json['main_pic_src']+'" title="'+json['goods_name']+'"/></a>';
        content+='<p class="price"><span>¥'+price+'</span></p></div>';        
        content+='<div class="share_like"><li class="fl like"><p share_id="'+json['id']+'" class="ilike"><span class="like-text">喜欢</span>(<span class="like-num">'+json['liked']+'</span>)</p></li><li class="fr comment"><a href="/book/'+json['id']+'" target="_blank">评论(<u>'+json['commentnum']+'</u>)</a></li></div>';
        content+='<div class="share_title">'+json['goods_name']+'</div>';
        content+='<div class="share_user">';
        for(x in json['event_list']){
            var avatar=json['event_list'][x]['avatar'];
            if(avatar.indexOf('http://')===-1){
                avatar='http://static.'+host[1]+'.com/'+avatar;
            }
            content+='<ul><li class="share_userface"><a href="#nogo" target="_blank"><img rel="show_tips" user_id="'+json['event_list'][x]['user_id']+'" src="'+avatar+'"/></a></li><li class="share_userinfo"><span class="fr dgrey_font">'+json['event_list'][x]['location']+'</span><a href="#">'+json['event_list'][x]['user_name']+'</a><p>'+json['event_list'][x]['content']+'</p></li></ul>';
        }
        content+='</div>';
        content+='<div class="share_go"></div>';
    }

    content+='</div>';

    return content;                
}            
DDS.Waterfall.append_data=function(data,type){//根据构造好的数据 添加数据到div
    var obj=$(DDS.Waterfall.config.shareColContainer);                
    var i=0;
    for(x in data){
        var content= DDS.Waterfall.get_one_goods_html(data[x], type);
        //var j=i%4;//j表示是第几列
        //obj.eq(j).append(content);
        obj.append(content);
        //i++;
    }
    $(DDS.Waterfall.config.listPicContainer+" img").lazyload({ 
        effect : "fadeIn" ,
        threshold : 200,
        failure_limit : 10
    });
}
DDS.Waterfall.Init=function(type){
    $(window).scroll( function() {
        var obj=$(this);
        var scrollTop =parseInt(obj.scrollTop());
        var windowHeight=parseInt(obj.height());//窗口的高度
        var bodyHeight=parseInt($('body').height());//body的高度

        if((bodyHeight-windowHeight-scrollTop)<((bodyHeight-windowHeight)/6)){
            if(!DDS.Waterfall.config.is_end&&DDS.Waterfall.config.is_can_load){//表示没有结束的话而且没有其他的ajax在加载
                DDS.Waterfall.get_subpage(DDS.Waterfall.config.subPage+1,DOTDOTPROFILE, type);
                DDS.Waterfall.config.subPage++;
            }
        }
    });
}

//图片相关的
DDS.Thumb={}
DDS.Thumb.LoadPic={}
DDS.Thumb.BookThumbList=function(config){//显示图片列表
    $(config.targetElement).mouseover(function(){
        var mainPicUrl=$(this).attr(config.mainPic);
        var PicCover_Loading = $('#J_PicCover_Loading');
        if(config.PicCover_Loading){
            PicCover_Loading = $(PicCover_Loading);
        }
        if(DDS.Thumb.LoadPic[mainPicUrl]){

        }else{
            if(PicCover_Loading.length>0){
                PicCover_Loading.show();
            }else{
                $(config.mainPicContainer).attr('src','http://static.dotdotbuy.com/images/loading_32_32_320.gif');
            }
        }
        var   imgObj   =   new   Image(); 
        imgObj.src   =   mainPicUrl;
        imgObj.onload   =   function(){
            if(DDS.Thumb.LoadPic[mainPicUrl]){

            }else{
                if(PicCover_Loading.length>0){
                    PicCover_Loading.hide();
                }
                DDS.Thumb.LoadPic[mainPicUrl] = 1;
            }
            $(config.mainPicContainer).attr('src',imgObj.src).css({
                "margin-top":0
            });
        }

    });
}

var checkSiteHost=function(){
    var bbs_site = [
        'bbs.daigou.com',
        'bbs.dotdotbuy.com',
        'http://www.daigou.com',
        'http://www.dotdotbuy.com'
    ];
    var url_site = '';
    (bbs_site[0].indexOf(document.domain) == 0) ? url_site = bbs_site[2] : url_site = '';
    if(url_site == ''){
        (bbs_site[1].indexOf(document.domain) == 0) ? url_site = bbs_site[3] : url_site = '';
    }
    return url_site;
};

//tips相关的
DDS.Tips={}
DDS.Tips.config={
    user_info_ajax_url: checkSiteHost()+'/card/user/',
    user_tips_id:'#user_card',
    user_infos:{},//存储以及读取过了的用户信息
    i:null,
    j:null,
    show_tips_delay:300,//毫秒
    remove_tips_delay:500//毫秒
}
DDS.Tips.UserTips=function(target){  
    $("body").on("mouseenter", target, function(){
        tmp_obj=$(this);
        this.usercardEvent||    
        (tmp_obj.unbind(),
            this.usercardEvent=!0,
            DDS.Tips.config.j = setTimeout(function() {
                DDS.Tips.DoTips(tmp_obj);
            },
            DDS.Tips.config.show_tips_delay),
            tmp_obj.hover(function() {                
                clearTimeout(DDS.Tips.config.i);
                DDS.Tips.config.j = setTimeout(function() {
                    DDS.Tips.DoTips(tmp_obj);
                },
                DDS.Tips.config.show_tips_delay)
            },
            function() {
                clearTimeout(DDS.Tips.config.j);
                DDS.Tips.config.i = setTimeout(function() {
                    $(DDS.Tips.config.user_tips_id).remove()
                },
                DDS.Tips.config.remove_tips_delay)
            }))
    })

}

DDS.Tips.DoTips=function(obj){
    var user_id=obj.attr('user_id');
    var user_info='';
    if(DDS.Tips.config.user_infos[user_id]){
        user_info=DDS.Tips.config.user_infos[user_id];
        DDS.Tips.JCardHover(user_info,obj);
    }else{
        $.ajax({
            url: DDS.Tips.config.user_info_ajax_url,
            cache: false,
            data:{user_id:user_id},
            type:'GET',
            dataType:'jsonp',
            jsonp:'jsonp',
            success: function(d){
                if(d.code=='sucess'){
                    user_info=d.card;
                    DDS.Tips.config.user_infos[user_id]=user_info;
                    DDS.Tips.JCardHover(user_info,obj);
                }
            }
        });
    }
}
DDS.Tips.get_content=function(user_info){
    var host=window.location.host;    
    host=host.split('.');
    var content='';
    var avatar=user_info['avatar'];
    if(avatar.slice(0,3)!='http'){
        avatar='http://static.'+host[1]+'.com/'+avatar;
    }

    content+='<div class="user_tips" id="'+DDS.Tips.config.user_tips_id.replace('#','')+'">';
    content+='<dl>';
    content+='<table width="100%">';
    content+='<tr>';
    content+='<td class="user_img"><img src="'+avatar+'" /></td>';
    content+='<td valign="top"><h3 class="black_font">'+user_info['user_name']+'</h3>现居 '+user_info['reg_location']+'</td>';
    content+='</tr>';
    content+='</table>';
    // content+='<dt><!--<a href="#" class="input_send input_send12 fr">发送消息</a>--><span class="dotdotbuy_topservericon"><a href="/dotbuyservice" target="_blank" class="dotbuyservice"></a><a href="/diybuyservice" target="_blank" class="diybuyservice"></a></span></dt>';
    content+='</dl>';
    content+='</div>';
    return content;
}
DDS.Tips.show_tip=function(user_info,obj){
    var content=DDS.Tips.get_content(user_info);    
    $('body').append(content);

    var top=$(obj).offset().top + 20; 
    var left=$(obj).offset().left;
    $(DDS.Tips.config.user_tips_id).css({
        'top':top,
        'left':left
    }) 
}
DDS.Tips.JCardHover=function(user_info,obj){
    $(DDS.Tips.config.user_tips_id).length && $(DDS.Tips.config.user_tips_id).remove();
    clearTimeout(DDS.Tips.config.i);    
    DDS.Tips.show_tip(user_info,obj);
    $(DDS.Tips.config.user_tips_id).unbind();
    $(DDS.Tips.config.user_tips_id).hover(
        function() {
            clearTimeout(DDS.Tips.config.i)
        },
        function() {
            DDS.Tips.config.i = setTimeout(function() {
                $(DDS.Tips.config.user_tips_id).remove()
            },
            DDS.Tips.config.remove_tips_delay)
        })
}

//返回顶部
DDS.Returntotop=function(target){
    var obj=$(target);
    $(window).scroll(function(){
        i(obj)
    })
    var i=function(b){
        setTimeout(function(){
            $(window).scrollTop()==0?b.addClass("hide"):b.removeClass("hide");
        },200)
    }
    obj.on("click",function(){
        $("html, body").animate({
            scrollTop:0
        },500)
    })
}

//分享宝贝
DDS.Share={}
DDS.Share.config={
    sharegoods:'.share_goods',//发布宝贝的按钮
    sharegoodsC:'#ShareGoodsD',//链接粘贴框
    textTip:'.text-tip',//文字提示
    pubDiv:'#GoodsPub',
    sucessDiv:'#PubSuccess',
    ajax_url:'/api/findgoods',
    pubgoods_url:'/share/pubgoods'

}

DDS.Share.Init=function(){//初始化操作
    $(DDS.Share.config.sharegoods).click(function(){
        var callback=escape("$(\'"+DDS.Share.config.sharegoodsC+"\').toggle()");
        checkIsLogin(callback);        
    })
    $(".share_pubclosebtn").click(function(){
        $(DDS.Share.config.sharegoodsC).hide();
    })
}
DDS.Share.ShowGoods=function(){//显示抓取的商品信息给用户操作
    var url=$(DDS.Share.config.sharegoodsC+" input[name='url']").val();
    $(DDS.Share.config.sharegoodsC+" "+DDS.Share.config.textTip).html('<img src="http://static.dotdotbuy.com/images/loading.gif" align="absmiddle"> 宝贝信息抓取中...').css({
        color:'#7A7A7A'
    });
    $.post(DDS.Share.config.ajax_url, {
        url:url
    }, function(d){        
        if(d.code=='sucess'){
            $(DDS.Share.config.sharegoodsC+" "+DDS.Share.config.textTip).html('');
            $(DDS.Share.config.sharegoodsC+" input[name='url']").val('');
            $(DDS.Share.config.sharegoodsC).hide();
            var content=DDS.Share.makeHtml(d.product);
            var title='';

            $(DDS.Share.config.pubDiv).remove();
            $("body").append("<div id='"+DDS.Share.config.pubDiv.replace('#','')+"'>"+content+"</div>");
            if(d.product.shared==true){
                title="发布宝贝";
            }else{
                title='发布宝贝';
            }
            $(DDS.Share.config.pubDiv).dialog({
                title:title,
                width:600,
                modal:true,
                draggable:false,
                resizable: false
            });
        }else{//text-tip
            $(DDS.Share.config.sharegoodsC+" "+DDS.Share.config.textTip).css({
                color:'red'
            }).html(d.msg);
        }

    }, 'json');
    return false;
}
DDS.Share.makeHtml=function(json){//分享商品
    var content='';
    if(json['shared']==true){
        //分享过了就评论

        content+='<form id="GoodsPubForm"action=""method="POST">';
        content+='<input type="hidden" name="share_id" value="'+json['share_id']+'" />';
        content+='<table class="table_edit" width="100%">';
        content+='<tbody>';
        content+='<tr><th>宝贝名称:</th><td class="font14" style="padding-top:5px"><a title="'+json['title']+'"target="_blank"href="/book/'+json['share_id']+'">'+json['title']+'</a></td></tr>';
        content+='<tr><th>宝贝图片:</th><td class="share_piclist" style="padding-bottom:0px"><a title="'+json['title']+'"target="_blank"href="/book/'+json['share_id']+'"><li><img alt="'+json['title']+'"src="'+json['pic_url'].replace('60x60.','90x90.')+'" ></li></a></td></tr>';
        content+='<tr><th>评论一下:</th><td><textarea placeholder="喜欢它什么呢?" name="comment"id="desc"cols="61"rows="5"onfocus="this.style.color=\'#000\'"onblur="this.style.color=\'#999\'"style="color:#999;"></textarea></td></tr>';
        content+='<tr><th></th><td style="vertical-align:middle">';
        content+='<input type="button" onclick="DDS.Share.Dopub(\'save\')"  name="btn_send"value="发布"class="input_send">';
        content+=' <input type="checkbox" name="tomyfav"id="checkbox"/>加入我喜欢的宝贝</td></tr>';
        content+='</tbody></table></form>'; 

    }else{//没分享过就分享
        content+='<form id="GoodsPubForm"action=""method="POST">';
        content+='<input type="hidden" name="goods_code" value="'+json['goods_code']+'" />';
        content+='<table class="table_edit" width="100%">';
        content+='<tbody>';
        content+='<tr><th>宝贝名称:</th><td><input value="'+json['title']+'" type="text"name="title"id="title"class="input_border"size="60" disabled="disabled"></td></tr>';
        content+='<tr><th>评论一下:</th><td><textarea placeholder="喜欢它什么呢?" name="comment"id="desc"cols="61"rows="5"onfocus="this.style.color=\'#000\'"onblur="this.style.color=\'#999\'"style="color:#999;"></textarea></td></tr>';
        content+='<tr><th>宝贝图片:</th><td class="share_piclist"><ul>';
        for(x in json['item_imgs']){
            content+='<li><img src="'+json['item_imgs'][x]+'_90x90.jpg" alt=""></li>';
        }
        content+='</ul></td></tr>';
        content+='<tr><th></th><td style="vertical-align:middle">';
        content+='<input type="button" onclick="DDS.Share.Dopub(\'pub\')"  name="btn_send"value="发布"class="input_send">';
        content+=' <input type="checkbox" name="tomyfav"id="checkbox"/>加入我喜欢的宝贝</td></tr>';
        content+='</tbody></table></form>';      
    }
    return content;
}

DDS.Share.SucessPage=function(share_id){
    $(DDS.Share.config.pubDiv).remove();
    var content=''; 
    content+='<div class="send_style">';   
    content+='<table align="center" style="margin:30px auto 50px auto;">';
    content+='<tbody><tr>';
    content+='<th><h1 class="icon_ok"></h1></th>';
    content+='<td><h2 class="msg_ok">宝贝已分享成功!</h2>';
    content+='<p>接下来您还可以<br><a href="/book/'+share_id+'">查看我的分享</a>&nbsp;&nbsp;<a class="buy_continue" onclick="$(\''+DDS.Share.config.sharegoodsC+'\').show();$(\''+DDS.Share.config.sucessDiv+'\').remove();" href="#nogo">继续分享</a></p></td>';
    content+='</tr>';
    content+='</tbody>';
    content+='</table>';
    content+='</div>';

    $(DDS.Share.config.sucessDiv).remove();
    $("body").append("<div id='"+DDS.Share.config.sucessDiv.replace('#','')+"'>"+content+"</div>");

    $(DDS.Share.config.sucessDiv).dialog({
        title:'',
        width:400,
        modal:true,
        draggable:false,
        resizable: false
    });
}
DDS.Share.Dopub=function(){
    $.post(DDS.Share.config.pubgoods_url, $(DDS.Share.config.pubDiv+" form").serialize(), function(d){
        if(d.code=='sucess'){
            DDS.Share.SucessPage(d.share_id);   
        }else{
            alert(d.msg);     
        }
    }, 'json');
}

//分享评论相关代码
DDS.Comment={};
DDS.Comment.config={
    pubcommentbtn:'.pubcomment',//发布按钮
    formId:'#scomment_form',//提交评论的form
    commentUrl:'/book/addcomment',//评论提交的地址
    commentListUrl:'/book/listcomments',//请求评论列表的url
    commentDiv:'#share_comment_list_div',//显示评论的div
    paginationDiv:'#share_comment_pagination_div',//显示分页的div
    isShowPagination:0,//
    pageNum:0
}
DDS.Comment.Init=function(share_id){
    $(DDS.Comment.config.pubcommentbtn).click(function(){
        DDS.Comment.Addcomment(DDS.Comment.config.formId);
    });
    if(DDS.Comment.config.isShowPagination==1){
        DDS.Comment.ShareCommentPagination(DDS.Comment.config.pageNum,0,1,2,share_id,'all');
    }
}
DDS.Comment.Addcomment=function(form_id){//添加评论
    var callback=escape('DDS.Comment.RealAddComment("'+form_id+'")');
    checkIsLogin(callback);
};
DDS.Comment.RealAddComment=function(form_id){//添加评论
    $.post(DDS.Comment.config.commentUrl, $(form_id).serialize(), function(d){
        if(d.code=='sucess'){
            var content = '';
            content += '<ul>';
            content += '<ol><img src="'+d.avatar+'" /></ol>';
            content += '<ol><li><span>'+d.addtime+'</span><a href="#nogo">'+d.user_name+'</a>';
            content += '<label class="comment_type">';
            if(d.type != ''){
                content += '('+d.type+')';
            }
            content += '<label>';
            content += '</li><li class="comment_content">'+d.content+'</li></ol></ul><dl class="clear"></dl>';
            $('#share_comment_list_div').prepend(content);
            $('#scomment_content').val('');
            $('input[name^=scomment_type]').removeAttr('checked');
        }else{
            alert(d.msg);
        }
    }, 'json');
};
DDS.Comment.ShareCommentContent=function (lists){//构造显示评论的内容
    var content = '';
    for(x in lists){
        content += '<ul>';
        content += '<ol><img src="'+lists[x]['avatar']+'" /></ol>';
        content += '<ol><li><span>'+lists[x]['addtime']+'</span><a href="#nogo" class="user-name">'+lists[x]['name']+'</a>';
        // content += '<label class="comment_type">';
        // if(lists[x]['type'] != ''){
        //     content += '('+lists[x]['type']+')';
        // }
        // content += '<label>';
        content += '</li><li class="comment_content">'+lists[x]['content']+'</li></ol></ul><dl class="clear"></dl>';
    }
    $(DDS.Comment.config.commentDiv).html(content);
}
DDS.Comment.ShareCommentPagination=function(total,pre_page,cur_page,next_page,shareid,type){//构造显示分页的内容
    if(total<=1){
        $(DDS.Comment.config.paginationDiv).html('');
        return false;
    }
    var min_step = max_step = 3;
    var pagination = '<p class="share_paginationsmall">';
    if(pre_page != 0){
        pagination += '<a href="#nogo" onclick="DDS.Comment.ShareCommentList(\''+pre_page+'\',\''+shareid+'\',\''+type+'\')">上一页</a>';
    }
    if(cur_page-min_step>1){
        pagination += '<a href="#nogo" onclick="DDS.Comment.ShareCommentList(\'1\',\''+shareid+'\',\''+type+'\')">1</a>';
        pagination += '<span>...</span>';
    }
    for(i=1;i<=total;i++){
        if(i == cur_page){
            pagination += '<span>'+cur_page+'</span>';
        }else{
            if(i>=(cur_page-min_step) && i<=(cur_page+max_step)){
                pagination += '<a href="#nogo" onclick="DDS.Comment.ShareCommentList(\''+i+'\',\''+shareid+'\',\''+type+'\')">'+i+'</a>';
            }
        }
    }
    if(cur_page+max_step<total){
        pagination += '<span>...</span>';
        pagination += '<a href="#nogo" onclick="DDS.Comment.ShareCommentList(\''+total+'\',\''+shareid+'\',\''+type+'\')">'+total+'</a>';
    }
    if(next_page != 0){
        pagination += '<a href="#nogo" onclick="DDS.Comment.ShareCommentList(\''+next_page+'\',\''+shareid+'\',\''+type+'\')">下一页</a>';
    }
    pagination += '</p>';
    $(DDS.Comment.config.paginationDiv).html(pagination);
}

DDS.Comment.ShareCommentList=function(page_no,shareid,type){
    $.post(DDS.Comment.config.commentListUrl, 
    {
        page_no:page_no,
        shareid:shareid,
        type:type
    }, function(d){
        if(d.code=='sucess'){
            DDS.Comment.ShareCommentContent(d.result.list);
            DDS.Comment.ShareCommentPagination(d.result.total_page,d.result.pre_page,d.result.cur_page,d.result.next_page,shareid,type);           
        }else if(d.code=='empty'){

        }else{
            alert(d.msg);
        }
    }, 'json');
};

//收藏相关
DDS.Fav={}
DDS.Fav.Goods={}
DDS.Fav.Goods.config={
    addCart:'.add_cart',
    delFav:'.del_fav',
    delFavMore:'.del_fav_more',
    selectAll:'.selectall',
    checkbox:'input[name="data_id"]'
}
DDS.Fav.Goods.addEventListener=function(config){
    if(typeof(config)=='undefined'){
        config=DDS.Fav.Goods.config;
    }
    $(config.addCart).click(function(){
        var id=$(this).attr('data_id');
        $.post('/account/fav/addcart',{
            id:id
        },function(d){
            if(d.code=='sucess'){
                if(confirm("宝贝已成功添加到购物车!\n点击[确定]跳转到购物车,[取消]继续添加宝贝")){
                    var url='/account/diybuy/confirm';
                    if(d.item_type==1){
                        url='/account/cart';
                    }
                    window.location.href=url;
                }
            }else{
                alert('加入购物车失败,请重试!')
            }
        },'json')
    });

    $(config.delFavMore).click(function(){
        var ids=[];
        $(config.checkbox).each(function(){
            if($(this).attr('checked')){
                ids.push($(this).val());
            }
        });

        if(ids.length<=0){
            alert('请至少选择一个进行操作');
            return false;
        }

        if(confirm('确定要删除该收藏吗?')){
            $.post('/account/fav/delgoods',{
                ids:ids
            },function(d){
                if(d.code=='sucess'){
                    window.location.reload();
                }else{
                    alert(d.msg);
                }
            },'json')
        }        
    });

    $(config.delFav).click(function(){
        var ids=[];
        ids.push($(this).attr('data_id'));
        if(confirm('确定要删除该收藏吗?')){
            $.post('/account/fav/delgoods',{
                ids:ids
            },function(d){
                if(d.code=='sucess'){
                    window.location.reload();
                }else{
                    alert(d.msg);
                }
            },'json')
        }        
    });

    $(config.selectAll).click(function(){
        if($(this).attr('checked')){
            $(config.checkbox).attr('checked','checked');
        }else{
            $(config.checkbox).removeAttr('checked');
        }
    });

};

DDS.Util = {
    /**
     DDS.Util.filterScript('123<script src="a.js"></script>456');
     结果:123456
     * @memberOf DDS.Util
     */
    filterScript: function (str) {
        str = str || '';
        str = decodeURIComponent(str);
        str = str.replace(/<.*>/g, ''); // 过滤标签注入
        str = str.replace(/(java|vb|action)script/gi, ''); // 过滤脚本注入
        str = str.replace(/[\"\'][\s ]*([^=\"\'\s ]+[\s ]*=[\s ]*[\"\']?[^\"\']+[\"\']?)+/gi, ''); // 过滤HTML属性注入
        str = str.replace(/[\s ]/g, '&nbsp;'); // 替换空格
        return str;
    },
    /**
     DDS.Util.getPara('type');

     返回值:1
     * @memberOf DDS.Util
     */
    getPara: function (name, url) {
        var para = (typeof url == 'undefined') ? window.location.search : url;
        para = para.split('?');
        para = (typeof para[1] == 'undefined') ? para[0] : para[1];
        var hashIndex = para.indexOf("#");
        if (hashIndex > 0) {
            para = para.substring(0, hashIndex);
        }
        para = para.split('&');
        for (var i = 0; para[i]; i++) {
            para[i] = para[i].split('=');
            if (para[i][0] == name) {
                try { // 防止FF等decodeURIComponent异常
                    return this.filterScript(para[i][1]);
                } catch (e) {
                }
            }
        }
        return '';
    }
};

DDS.Package={};
    DDS.Package.config={
        ex_info_ajax_url:'/logistics/trace?expressno',
        ex_tips_id:'#exdolog_info_layer',
        ex_infos:{},//存储以及读取过了的用户信息,
        ex_loading:'#loading',
        //post_params:['username'],
        //post_data:{username:''},
        i:null,
        j:null,
        show_tips_delay:300,//毫秒
        remove_tips_delay:500//毫秒,
    }
    DDS.Package.UserTips=function(target){  
        // $("body").on("mouseenter mouseleave", target, function(event){
        //     tmp_obj=$(this);
        //     if( event.type == "mouseenter"){
        //         DDS.Package.DoTips(tmp_obj);
        //         DDS.Package.config.show_tips_delay;
        //     } else if(event.type == "mouseleave" ){
        //         $(DDS.Package.config.ex_tips_id).remove();
        //         DDS.Package.config.remove_tips_delay;
        //     }           
        // });
    $(target).on({
        mouseenter: function() {
            tmp_obj=$(this);
            this.usercardEvent||    
            (
                // tmp_obj.unbind(),
                this.usercardEvent=!0,
                DDS.Package.config.j = setTimeout(function() {
                    DDS.Package.DoTips(tmp_obj);
                },
                DDS.Package.config.show_tips_delay),
                tmp_obj.hover(function() {                
                    clearTimeout(DDS.Package.config.i);
                    DDS.Package.config.j = setTimeout(function() {
                        DDS.Package.DoTips(tmp_obj);
                    },
                    DDS.Package.config.show_tips_delay)
                },
                function() {
                    clearTimeout(DDS.Package.config.j);
                    DDS.Package.config.i = setTimeout(function() {
                        $(DDS.Package.config.ex_tips_id).remove()
                    },
                    DDS.Package.config.remove_tips_delay)
                }))
        }
    })    

}
    DDS.Package.DoTips=function(obj){
        var track_express_no=obj.attr('data-expressno');
        var track_code=obj.attr('data-code');
        var delivery_name=obj.attr('date-delivery-name');
        var url = '';
        url= DDS.Package.config.ex_info_ajax_url+'='+track_express_no+'&code='+track_code+'&delivery_name='+delivery_name;   
        var ex_info='';
        if(DDS.Package.config.ex_infos[track_express_no]){
            ex_info=DDS.Package.config.ex_infos[track_express_no];

            DDS.Package.JCardHover(ex_info,obj);
        }else{
            $.ajax({
                url:"/logistics/track",
                type: 'get',
                data: {
                    express_no:track_express_no 
                },
                dataType: 'json',
                beforeSend:function(){
                   DDS.Package.show_loading(obj);
                },
                success:function(d){
                     $(DDS.Package.config.ex_loading).remove();
                     var msg = '<p style="margin-bottom:15px;"><strong>配送方式:</strong>' + delivery_name + '&nbsp;&nbsp;&nbsp;&nbsp;<strong>快递单号:</strong>' + track_express_no + '</p>';
                     ex_info=msg+d.data;
                     DDS.Package.config.ex_infos[track_express_no]=ex_info;
                     DDS.Package.JCardHover(ex_info,obj);           
                }
            })
        }
    }
    DDS.Package.loading=function(){
        var contents = '<div class="loading clearfix" id="loading"><div class="tack-boxy-arrow" style="top:-80px"><i style="margin-top: 21px;"></i></div>';
        contents += '<div><img src="http://static.dotdotbuy.com/images/loading_32_32.gif?t=2014"></div>';
        contents += '</div>';
        return contents;
    }
    DDS.Package.show_loading=function(obj){
         var content=DDS.Package.loading();
        $('body').append(content);
        var top=obj.position().top+30; 
        var left=obj.position().left-400;
        $(DDS.Package.config.ex_loading).css({
            'top':top,
            'left':left
        }) 
    }
    DDS.Package.get_content=function(ex_info){
        var content = '<div class="user_systemlinetips" id="exdolog_info_layer"><div class="tack-boxy-arrow"><i></i></div>';
        content += ex_info;
        content += '</div>';
        return content;
    }
    DDS.Package.show_tip=function(ex_info,obj){
        var content=DDS.Package.get_content(ex_info);    
        $('body').append(content);
        var top=obj.position().top+30; 
        var left=obj.position().left-407;
        $(DDS.Package.config.ex_tips_id).css({
            'top':top,
            'left':left
        }) 
    }
    DDS.Package.JCardHover=function(ex_info,obj){

        $(DDS.Package.config.ex_tips_id).length && $(DDS.Package.config.ex_tips_id).remove();
        clearTimeout(DDS.Package.config.i);  
        DDS.Package.show_tip(ex_info,obj);
        $(DDS.Package.config.ex_tips_id).unbind();
        $(DDS.Package.config.ex_tips_id).hover(
            function() {
                clearTimeout(DDS.Package.config.i)
            },
            function() {
                DDS.Package.config.i = setTimeout(function() {
                    $(DDS.Package.config.ex_tips_id).remove()
                },
                DDS.Package.config.remove_tips_delay)
            }
        )
    }