mui.ready(function(){

    //footer link
	mui("#nav-tabbar").on('tap','a',function(){
		window.top.location.href=this.href;
	});

    //slider
    var gallery = mui('.mui-slider');
    gallery.slider({
        interval:3000
    });

    //service
    $(".didi-server-online").on('click','.console',function(){
        if($(this).parent().hasClass('close')){
            $(this).parent().removeClass('close').addClass('open');
        }else{
            $(this).parent().removeClass('open').addClass('close');
        }
    });

    /**
     * form ajax
     */
    $('.submit-ajax').submit(function(){
        var url = $(this).attr('action');
        var data = $(this).serialize();
        var refresh = $(this).attr('data-refresh');
        var is_callback = $(this).attr('data-callback');
        var index = layer.load(2,{shade:[0.7,"#000000"]});
        $.ajax({
            type: "post",
            url:url,
            data:data,
            dataType:"json",
            success:function(data){
                if( is_callback != '' && is_callback != undefined ) {
                    submit_callback(data);
                    layer.close(index);
                    return false;
                }
                if( data.code == 200 ) {
                    layer.msg(data.msg,{icon:1},function(){
                        if( data.url != '' ) {
                            window.location.href = data.url;
                        } else {
                            if( refresh != 0 ) {
                                window.location.reload();
                            }
                        }
                        layer.close(index);
                    });
                } else {
                    layer.msg(data.msg,{icon:2},function(){
                        if( data.url != '' ) {
                            //window.location.href = data.url;
                        }
                        layer.close(index);
                    });
                }
            },
            error:function(xhr){
                layer.msg(xhr.status+':'+xhr.statusText);
                layer.close(index);
            }
        });
        return false;
    });

    //table toggle
    $(".layui-tab-title li").each(function(i,v){
        $(v).on('click',function(e){
            $(this).addClass('layui-this').siblings().removeClass('layui-this');
            $(".layui-tab-content .layui-tab-item:eq("+i+")").addClass('layui-show').siblings().removeClass('layui-show').find('input').val('');
        })
    });

    //open url
    $("[data-href]").on('click',function(){
        var url = $(this).attr('data-href');
        mui.plusReady(function(){
            plus.runtime.openURL(url);
            return false;
        });
        mui.openWindow({
            url:url,
            waiting:{
                autoShow:true,
                title:'loading...',
            }
        });
    });

    //show popup
    $("[data-popup='true']").on('click',function(){
        let popup = $('.popup');
        popup.show();
    });
    //close popup
    $(".popup-close").on('click',function(){
        $(this).parents('.popup').hide();
    });

    //copy document load
    $('.copy').each(function(i,e){
        var copyText = '';
        if(typeof($(this).attr("href"))!="undefined"){
            copyText = $(this).attr("href");
        }else{
            copyText = $(this).text();
        }
        $(this).wrap('<div class="copy-element"></div>').after('<span class="iconfont icon-copy" Copy data-clipboard-text="'+copyText+'"></span>');
    });

    //copy
    var clipboard = new ClipboardJS('[Copy]');
    clipboard.on('success', function(e) {
        layer.msg('Copy Successful');
    });

    clipboard.on('error', function(e) {
        layer.msg('Copy Failed');
    });

    //select country code
    $(".country_code_list .dd-table-view-cell").on('click',function(){
        var index = parent.layer.getFrameIndex(window.name);
        parent.$("input[name=country_code]").val($(this).attr('data-val'));
        parent.$("input[name=country]").val($(this).find('.country_name').html());
        parent.layer.close(index);
    });


    //open window
    $("[data-action=openWindow]").on('click',function(){
        var url = $(this).attr('data-open-url');
        var title = $(this).attr('data-open-title');
        if(url == ''){
            layer.msg('Waiting for development...',{icon:7});
        }else{
            layer.open({
                type:2,
                title:title,
                area:['100%','100%'],
                offset:'b',
                resize:false,
                shadeClose:true,
                closeBtn:1,
                anim:2,
                content:url,
            });
        }
    });

    //send code
    $(".send_code").on('click',function(){
        var self = $(this);
        var form = self.parents().find('form');
        var index = layer.load(2,{shade:[0.7,"#000000"]});
        //send code type
        var country_code = form.find('input[name="country_code"]').val();
        var phone = form.find('input[name="phone"]').val();
        var email = form.find('input[name="email"]').val();
        var id = form.find('input[name="id"]').val();

        if(typeof email != 'undefined' && typeof phone != 'undefined'){
            if(email.length < 1 && phone.length < 1 ){
                layer.msg('Please fill in the email address or phone number.',{icon:2},function(){
                    layer.close(index);
                });
                return false;
            }
        }else{
            if(typeof email != 'undefined'){
                if(email.length < 1 ){
                    layer.msg('Please fill in the email address.',{icon:2},function(){
                        layer.close(index);
                    });
                    return false;
                }
            }
            if(typeof phone != 'undefined'){
                if(phone.length < 1 ){
                    layer.msg('Please fill in the phone number.',{icon:2},function(){
                        layer.close(index);
                    });
                    return false;
                }
                if(phone.length > 1 && country_code.length < 1){
                    layer.msg('Please fill in the country code.',{icon:2},function(){
                        layer.close(index);
                    });
                    return false;
                }
            }
        }
        
        //request
        $.ajax({
            url:"/home/publics/send_code.html",
            type:'post',
            data:{
                'email':email,
                'phone':phone,
                'country_code':country_code,
                'id':id
            },
            success:function(data) {
                if(data.code == 200){
                    //disabled more click
                    settime(self);
                    layer.msg(data.msg,{icon:1},function(){
                        layer.close(index);
                    });
                }else{
                    layer.msg(data.msg,{icon:2},function(){
                        layer.close(index);
                    });
                }
            },
            error:function(xhr){
                layer.msg(xhr.error);
                layer.close(index);
            }
        });
        return false;
    });

    //otc order action
    $("[data-action=otcOrder]").on('click',function(){
        var action = $(this).attr('data-act');
        var orderId = $(this).attr('data-order-id');
        var userId = $(this).attr('data-user-id');
        var username = $(this).attr('data-user-name');
        var url = $(this).attr('data-action-url');
        var index = layer.load(2,{shade:[0.7,"#000000"]});
        var text = '';
        var notice = '';

        switch(action){
            case 'cancel':
            text = 'Are you sure you want to cancel the order?';
            notice = ''+username+' cancelled the order.';
            break;
            case 'release':
            text = 'Do you confirm that you have received the payment and release the assets to the Buyer immediately?';
            notice = ''+username+' released the assets.';
            break;
            case 'paid':
            text = 'Are you sure you have paid and have a screenshot of the payment record?';
            notice = ''+username+' has confirmed payment for the order.';
            break;
        }

        layer.confirm(text,{
            btn:['Confirm','Cancel'],
            cancel:function(){
                layer.close(index);
            }
        },function(){
            if(action == 'paid'){
                layer.closeAll();
                layer.open({
                    type:2,
                    title:'Submit payment information',
                    area:['100%','100%'],
                    offset:'b',
                    resize:false,
                    shadeClose:true,
                    closeBtn:1,
                    anim:2,
                    content:'/home/otc/paid/id/'+orderId+'/act/'+action+'.html',
                    success:function(layero,index){
                        $("#submit_payment_info", layero.find("iframe")[0].contentWindow.document).attr('action',url);
                    }
                });
            }else{
                //ajax request
                $.ajax({
                    url:url,
                    type:'post',
                    dataType:'json',
                    data:{
                        'act':action,
                        'id':orderId
                    },
                    success:function(data) {
                        if(data.code == 200){
                            ws.send(JSON.stringify({type:"system",msg:notice,order_id:orderId,member_id:userId}));
                            layer.msg(data.msg,{icon:1},function(){
                                window.location.reload();
                                layer.close(index);
                            });
                        }else{
                            layer.msg(data.msg,{icon:2},function(){
                                layer.close(index);
                            });
                        }
                    },
                    error:function(xhr){
                        layer.msg(xhr.error);
                    }
                });
            }
        },function(){
            layer.close(index);
        });
    });

    //view image
    $("[data-action=image]").on('click',function(){
        var img = $(this).attr('src');
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            area: ['80%', '90%'],
            content: "<div style='width:100%;text-align:center;'><img src="+ img + " width='auto' height='auto'/></div>"
       });
    });

    /**
     * custom select
     * start
    */
    $(".custom-select").on('click',function(){
        var showSelect = $(this).attr("data-select");
        $(this).find(".icon-down").addClass("icon-down-active");
        $("#"+showSelect+"").show().animate({opacity:"1"}).find(".custom-select-option").addClass('custom-select-option-show');
    });
    $(".custom-select-mask").on("click",function(){
        $(this).find(".custom-select-cancel").trigger("click");
    });
    $(".custom-select-option").on("click",function(e){
        e.stopPropagation();
    });
    $(".custom-select-cancel").on("click",function(e){
        var customSelect = $(this).parents('.custom-select-mask').attr("id");
        $("[data-select="+customSelect+"]").find(".icon-down").removeClass("icon-down-active");
        $(this).parents('.custom-select-mask').animate({opacity:"0"},function(){
            $(this).hide();
        }).find(".custom-select-option").removeClass('custom-select-option-show');
    });
    $(".custom-select-option").on("click",".custom-option-object",function(){
        var customSelect = $(this).parents('.custom-select-mask').attr("id");
        var selectOption = $(this).find(".option-value").html();
        $("[data-select="+customSelect+"]").find(".option-value").html(selectOption);
        $(this).addClass("custom-option-object-active").siblings().removeClass("custom-option-object-active");
        $(".custom-select-cancel").trigger("click");
    });
    /**
     * custom select
     * end
    */
});

//bd tj
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?29e31818484702dc695b0bc6ab628d8a";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();

//send code function
var count = 120;
var curcount = count;
var oldText;
function settime(obj) { 
    if(curcount == 120){
        oldText = obj.find('.btn-text').text();
    }
    if(curcount == 0){
        obj.removeAttr("disabled");
        obj.find('.btn-text').text(oldText);
        curcount = 120;
        return;
    }else{
        obj.attr("disabled", true);
        obj.find('.btn-text').text(curcount + "s");
        curcount--;
    }
    setTimeout(function(){
        settime(obj);
    },1000);
}

//send in img path ,save img - web
function saveAs(Url){
    var blob = new Blob([''],{type:'application/octet-stream'});
    var url = window.URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = Url;
    a.download = Url.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0];
    a.click();
    window.URL.revokeObjectURL(url);
}

//send in img path ,save img - app
function savePicture(url) {
    var imgDtask = plus.downloader.createDownload(url,{filename:"_doc/images/"}, function (d,status) {
        if(status == 200){
            plus.gallery.save(d.filename, function () {
                plus.nativeUI.alert('The download was successful and the image "'+d.filename+'" has been saved to the system album.');
            })
        }else{
            plus.nativeUI.alert('Image "'+d.filename+'" failed to download.');
            plus.downloader.clear();
        }
    });
    imgDtask.start();
}

//[custom guide tips]
//1,2,3,4表示方向
function guideTips(dom,text,id,dec=3){
    if($.cookie('guideTips_'+id) == null){
        layer.tips(text,dom,{
            time:0,
            tips:[dec,"#33c8b5"],
            closeBtn:1,
            tipsMore: true,
            success:function(layero,index){
                dom.addClass('t-select');
                layero.css({'z-index':99999999});
            },
            cancel:function(layero,index){
                dom.removeClass('t-select');
                $.cookie('guideTips_'+id,1,{expires:7});
            },
            end:function(layero,index){
                if($(".layui-layer-tips").length < 1){
                    layer.closeAll();
                }
            }
        });
    }
}