$(function () {
    'use strict';
    //主页面
    $(document).on("pageInit", "#login-page", function(e, id, page) {
        $(page).on("click", "#login", function(e) {
            var username = $.trim($("#username").val());
            var password = $.trim($("#password").val());
            if(false == checkNull()) return false;//检查空输入
            $.ajax({
                url: 'index.php?d=wap_user&c=login&m=check_login',   //后台处理程序
                type: "post",         //数据发送方式
                dataType:"json",    //接受数据格式
                beforeSend: function () {
                    //加载提示符
                    $.showIndicator();
                },
                complete: function () {
                    $.hideIndicator();
                },
                data:{username:username,password:password},  //要传递的数据
                success:function(data) {
                    if (data.err_code!=0) {
                        $.alert(data.err_msg);

                    }else
                    {
                        $.toast(data.err_msg, 2000, 'success top');
                        window.location.replace('index.php?d=wap_user&c=home&m=index');
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    $.alert(errorThrown);
                }
            });
        });
        function checkNull(){
            $("#username").val($.trim($("#username").val()));
            if(!$("#username").val() || !$("#password").val() || $("#username").val() == $("#username").attr('prompt')) {
                if(!$("#username").val() || $("#username").val() == $("#username").attr('prompt')){
                    $.alert('请输入用户名!');
                    return false;
                }
                if(!$("#password").val()){

                    $.alert('请输入密码!');
                    return false;
                }
            }
            return true;
        }
    });
    //密码修改页面
    $(document).on("pageInit", "#change-password-page", function(e, id, page) {
        $(page).on("click", "#submit", function(e) {
            var old_password = $.trim($("#old_password").val());
            var new_password = $.trim($("#new_password").val());
            var re_new_password = $.trim($("#re_new_password").val());
            if(false == checkNull()) return false;//检查空输入
            if(new_password!=re_new_password)
            {
                $.alert('两次输入密码不一致');
                return false;
            }
            $.ajax({

                url: 'index.php?d=wap_user&c=home&m=password_save',   //后台处理程序
                type: "post",         //数据发送方式
                dataType:"json",    //接受数据格式
                data:{old_password:old_password,new_password:new_password},  //要传递的数据
                success:function(data) {
                    if (data.err_code!=0) {
                        $.alert(data.err_msg);
                    }
                    else
                    {
                        $.toast('操作成功，正在跳转...', 2000, 'success top');
                        window.location.replace('index.php?d=wap_user&c=login&m=index');
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    $.alert(errorThrown);
                }
            });
        });
        function checkNull(){
            $("#old_password").val($.trim($("#old_password").val()));
            if(!$("#old_password").val() || !$("#new_password").val() || !$("#re_new_password").val() || $("#old_password").val() == $("#old_password").attr('prompt')) {
                if(!$("#old_password").val() || $("#old_password").val() == $("#old_password").attr('prompt')){
                    $.alert('请输入旧密码');
                    return false;
                }
                if(!$("#new_password").val()){
                    $.alert('请输入新密码');
                    return false;
                }
                if(!$("#re_new_password").val()){
                    $.alert('请输入确认密码');
                    return false;
                }
            }
            return true;
        }
    });
    //头像修改
    $(document).on("pageInit", "#change-avatar-page", function(e, id, page) {
        var f = document.querySelector('#image-uploader');
        f.onchange = function () {
            lrz(this.files[0],{width:640,fieldName:"upfile"}).then(function (rst) {
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'index.php?d=wap_user&c=file&m=image_upload');

                xhr.onload = function () {
                    if (xhr.status === 200) {
                        var obj = eval('(' + xhr.responseText + ')');
                        $('#thumb').attr('src',obj.full_url );
                        $("#headimgurl").val(obj.url);
                    } else {
                        // 处理其他情况
                    }
                };

                xhr.onerror = function () {
                    // 处理错误
                };

                xhr.upload.onprogress = function (e) {
                    // 上传进度
                    var percentComplete = ((e.loaded / e.total) || 0) * 100;
                }

                // 添加参数
                rst.formData.append('size', rst.fileLen);
                rst.formData.append('base64', rst.base64);
                // 触发上传
                xhr.send(rst.formData);

                return rst;
            })

                .catch(function (err) {
                    alert(err);
                })

                .always(function () {// 不管是成功失败，这里都会执行
                });
        }
        $(page).on("click", "#submit", function(e) {
            var headimgurl = $.trim($("#headimgurl").val());

            if(headimgurl=='')
            {
                $.alert('照片不能为空');
                return false;
            }
            $.ajax({
                url: 'index.php?d=wap_user&c=home&m=avatar_save',   //后台处理程序
                type: "post",         //数据发送方式
                dataType:"json",    //接受数据格式
                data:{thumb:headimgurl},  //要传递的数据
                success:function(data) {
                    if (data.hasOwnProperty('error_code')) {
                        $.alert(data.error_msg);
                    }
                    else
                    {
                        $.toast('操作成功，正在跳转...', 2000, 'success top');
                        window.location.replace('index.php?d=wap_user&c=home&m=user_info');
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    $.alert(errorThrown);
                }
            });
        });
    });
    /*反馈添加**/
    $(document).on("pageInit", "#feedback-add-page", function(e, id, page) {
        $(page).on("click", "#submit", function(e) {
            var email = $("#email").val();
            var content=$("#content").val();
            var reg =  /^[\u4e00-\u9fa5\S]{3,20}$/;
            var reg2 = /^[\u4e00-\u9fa5\S]{10,300}$/;
            if(email=='')
            {
                $.alert('联系方式不能为空！');
                return false;
            }else if(!reg.test(email))
            {
                $.alert("联系方式格式错误，至少三个字符！");
                return false;
            }
            if(content=='')
            {
                $.alert('内容不能为空！');
                return false;
            }else if(!reg2.test(content)){
                $.alert("内容格式错误，至少十个字符！");
                return false;
            }
            $.ajax({

                url: 'index.php?d=wap_user&c=feedback&m=save',   //后台处理程序
                type: "post",         //数据发送方式
                dataType:"json",    //接受数据格式
                data:{email:email,content:content},  //要传递的数据
                beforeSend: function () {
                    $.showIndicator();
                },
                complete: function () {
                    $.hideIndicator();
                },
                success:function(data) {
                    if (data.err_code!=0) {
                        $.alert(data.err_msg);
                    }
                    else
                    {
                        $.toast(data.err_msg, 2000, 'success top');
                        window.location.replace('index.php?d=wap_user&c=feedback&m=index');
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    $.alert(errorThrown);
                }
            });
        });
    });
    /*约车*/
    $(document).on("pageInit", "#train-booking-page", function(e, id, page){
        $(".starCon").each(function () {
            var obj = $(this);
            var star = obj.attr('data-star');
            obj.find('li').each(function () {
                var item_star = $(this).attr('data-item-star');
                if (star >= item_star) {
                    $(this).addClass('on');
                }
            });
        });
        $(page).on("click", ".retrie dt a", function(e) {
            var $t=$(this);
            if($t.hasClass('up')){
                $(".retrie dt a").removeClass('up');
                $('.downlist').hide();
                $('.mask').hide();
            }else{
                $(".retrie dt a").removeClass('up');
                $('.downlist').hide();
                $t.addClass('up');
                $('.downlist').eq($(".retrie dt a").index($(this)[0])).show();
                $('.mask').show();
            }
            $(".grade ul li a:contains('"+$('#grade').text()+"')").addClass('selected');
            $(".lesson ul li a:contains('"+$('#lesson').text()+"')").addClass('selected');
        });
    });
    $(document).on("pageInit", "#train-booking-add-page", function(e, id, page) {
        $('.today').html(dates[0]);
        $('.page-list').attr('data-date',dates[0]);
        set_timeline();
        //车辆选择
        $(page).on('click', '#vehicle', function () {
                var list=vehicle;
                var html = '<div class="list-block media-list"><ul>';
                for (var i in list) {

                    html += '<li> ' +
                    '<label class="label-checkbox item-content"> ' +
                    '<input type="radio" name="my-radio" data-key='+list[i]['vehicle_id']+' value="' +list[i]['vehicle_num']+ '"> ' +
                    '<div class="item-media"><i class="icon icon-form-checkbox"></i></div> ' +
                    '<div class="item-inner"> ' +
                    '<div class="item-title-row"> ' +
                    '<div class="item-title">' + list[i]['vehicle_num']+ '</div> ' +
                    '</div> ' +
                    '</div> ' +
                    '</label> ' +
                    '</li>';
                }
                html += '</<ul></div>';
                $.modal({
                    title: '车辆选择：',
                    extraClass: 'home-modal',
                    text: html,
                    buttons: [
                        {
                            text: '确认',
                            bold: true,
                            onClick: function () {
                                var key = $("input[name='my-radio']:checked").attr('data-key');
                                var checked_value = $("input[name='my-radio']:checked").attr('value');
                                if (key != undefined) {
                                    $('#vehicle').val(checked_value);
                                    $('#vehicleid').val(key);
                                }
                            }
                        }
                    ]
                });
        });
        $(page).on('click','.pre-day',function(){
            $('.page-list').attr('data-timeline','');
            var key=parseInt($('.page-list').attr('data-key'));
            if(key==0)
            {
                return false;
            }
            $('.today').html(dates[key-1]);
            $('.page-list').attr('data-date',dates[key-1]);
            $('.page-list').attr('data-key',key-1);
            set_timeline();
        });
        $(page).on('click','.next-day',function(){
            $('.page-list').attr('data-timeline','');
            var key=parseInt($('.page-list').attr('data-key'));
            if(key==6)
            {
                return false;
            }
            $('.today').html(dates[key+1]);
            $('.page-list').attr('data-date',dates[key+1]);
            $('.page-list').attr('data-key',key+1);
            set_timeline();
        });
        $(page).on("click", "#submit", function(e) {
            var subject=$("#subject").val();
            var vehicleid = $.trim($("#vehicleid").val());
            var content=$("#content").val();
            var date=$('.page-list').attr('data-date');
            var timeline=$('.page-list').attr('data-timeline');
            if(vehicleid=='')
            {
                $.alert('请选择车辆信息');
                return false;
            }
            if(date=='')
            {
                $.alert('请选择时间');
                return false;
            }
            if(timeline=='')
            {
                $.alert('请选择时间段');
                return false;
            }
            $.ajax({
                url: 'index.php?d=wap_user&c=train_booking&m=save',   //后台处理程序
                type: "post",         //数据发送方式
                dataType:"json",    //接受数据格式
                data:{teacherid:teacherid,subject:subject,vehicleid:vehicleid,date:date,timeline:timeline,content:content},  //要传递的数据
                beforeSend: function () {
                    $.showIndicator();
                },
                complete: function () {
                    $.hideIndicator();
                },
                success:function(data) {
                    if (data.hasOwnProperty('error_code')) {
                        $.alert(data.error_msg);
                    }
                    else
                    {
                        $.toast(data.msg, 2000, 'success top');
                        window.location.replace('index.php?d=wap_user&c=train_booking&m=index');
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    $.alert(errorThrown);
                }
            });
        });
        $(page).on('click','.col-33',function(e){
            var obj=$(this);
            var status=obj.attr('data-status');
            var time=obj.attr('data-time');
            if(status==2 || status==3)
            {
                return false;
            }
            $('.page-list').attr('data-timeline',time);
            obj.siblings().removeClass('col-33-blue');
            obj.parent().parent().find('.col-33').removeClass('col-33-blue');
            obj.addClass('col-33-blue');
        });
        function set_timeline()
        {
            var time=$('.page-list').attr('data-date');
            var data=list[time];
            var html='<div class="row">';
            for(var i in data){
                if(i%3===1 && i!=1){
                    html+=' </div><div class="row">';
                }
                if(data[i]['status']===2){
                    html+='<div class="col-33 col-33-grey" data-status="'+data[i]['status']+'" data-time="'+data[i]['time']+'"> <div>'+data[i]['time']+'</div> <div>预约中</div> <div>已过期</div></div>';
                }
                else if(data[i]['status']===3){
                    html+='<div class="col-33 col-33-red" data-status="'+data[i]['status']+'" data-time="'+data[i]['time']+'"> <div>'+data[i]['time']+'</div> <div>预约中</div> <div>已选满</div></div>';
                }
                else{
                    html+='<div class="col-33" data-status="'+data[i]['status']+'" data-time="'+data[i]['time']+'"> <div>'+data[i]['time']+'</div> <div>预约中</div> <div>已约'+data[i]['has_total']+'人 可约4人</div></div>';
                }

            }
            html+='</div>';
            $('.timeline').empty().html(html);
        }
    });
    $(document).on("pageInit", "#train-add-page", function (e, id, page) {
        $(page).on("click", "#submit", function(e) {
            var teacherid = $.trim($("#teacherid").val());
            var begintime = $.trim($("#begintime").val());
            //var endtime = $.trim($("#endtime").val());
            var vehicleid = $.trim($("#vehicleid").val());
            var content = $.trim($("#content").val());
            if(teacherid=='')
            {
                $.alert('请选择教练');
                return false;
            }
            if(begintime=='')
            {
                $.alert('请选择开始时间');
                return false;
            }
            /*if(endtime=='')
            {
                $.alert('请选择结束时间');
                return false;
            }*/
            if(vehicleid=='')
            {
                $.alert('请选择车辆信息');
                return false;
            }
            var value={
                teacherid:teacherid,
                begintime:begintime,
                //endtime:endtime,
                vehicleid:vehicleid,
                content:content
            };
            $.ajax({
                url: 'index.php?d=wap_user&c=train&m=temp_save',   //后台处理程序
                type: "post",         //数据发送方式
                dataType:"json",    //接受数据格式
                data:{value:value},  //要传递的数据
                success:function(data) {
                    if (data.err_code!=0) {
                        $.alert(data.err_msg);
                    }
                    else
                    {
                        $.toast('操作成功，正在跳转...', 2000, 'success top');
                        var temp_id=data.id;
                        window.location.replace('index.php?d=wap_user&c=train&m=timer&id='+temp_id);
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    $.alert(errorThrown);
                }
            });
        });
        $(page).on('click', '#teacher', function () {
            $('#vehicle').val('');
            $('#vehicleid').val('');
            var list=teacher;
            var html = '<div class="list-block media-list"><ul>';
            for (var i in list) {

                html += '<li> ' +
                '<label class="label-checkbox item-content"> ' +
                '<input type="radio" name="my-radio" data-key='+list[i]['coach_id']+' value="' +list[i]['real_name']+ '"> ' +
                '<div class="item-media"><i class="icon icon-form-checkbox"></i></div> ' +
                '<div class="item-inner"> ' +
                '<div class="item-title-row"> ' +
                '<div class="item-title">' + list[i]['real_name']+ '</div> ' +
                '</div> ' +
                '</div> ' +
                '</label> ' +
                '</li>';
            }
            html += '</<ul></div>';
            $.modal({
                title: '教练选择：',
                extraClass: 'home-modal',
                text: html,
                buttons: [
                    {
                        text: '确认',
                        bold: true,
                        onClick: function () {
                            var key = $("input[name='my-radio']:checked").attr('data-key');
                            var checked_value = $("input[name='my-radio']:checked").attr('value');
                            if (key != undefined) {
                                $('#teacher').val(checked_value);
                                $('#teacherid').val(key);
                            }
                        }
                    }
                ]
            });
        });
        $(page).on('click', '#vehicle', function () {
            var teacherid=$('#teacherid').val();
            if(teacherid=='')
            {
                $.alert('请先选择教练！');
                return false;
            }
            $.ajax({
                url: 'index.php?d=wap_user&c=train&m=get_vehicle',   //后台处理程序
                type: "post",         //数据发送方式
                dataType:"json",    //接受数据格式
                data:{teacherid:teacherid},  //要传递的数据
                success:function(data) {
                    if (data.err_code!=0) {
                        $.alert(data.err_msg);
                        return false;
                    }
                    else
                    {
                        var list=data.list;
                        var html = '<div class="list-block media-list"><ul>';
                        for (var i in list) {

                            html += '<li> ' +
                            '<label class="label-checkbox item-content"> ' +
                            '<input type="radio" name="my-radio" data-key='+list[i]['vehicle_id']+' value="' +list[i]['vehicle_num']+ '"> ' +
                            '<div class="item-media"><i class="icon icon-form-checkbox"></i></div> ' +
                            '<div class="item-inner"> ' +
                            '<div class="item-title-row"> ' +
                            '<div class="item-title">' + list[i]['vehicle_num']+ '</div> ' +
                            '</div> ' +
                            '</div> ' +
                            '</label> ' +
                            '</li>';
                        }
                        html += '</<ul></div>';
                        $.modal({
                            title: '车辆选择：',
                            extraClass: 'home-modal',
                            text: html,
                            buttons: [
                                {
                                    text: '确认',
                                    bold: true,
                                    onClick: function () {
                                        var key = $("input[name='my-radio']:checked").attr('data-key');
                                        var checked_value = $("input[name='my-radio']:checked").attr('value');
                                        if (key != undefined) {
                                            $('#vehicle').val(checked_value);
                                            $('#vehicleid').val(key);
                                        }
                                    }
                                }
                            ]
                        });
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    $.alert(errorThrown);
                }
            });
        });
    });
    $(document).on("pageInit", "#train-review-add-page", function(e, id, page) {
        starComm('star1');
        function starComm(starId){
            var oStar = document.getElementById(starId);
            var aLi = oStar.getElementsByTagName("li");
            var oUl = oStar.getElementsByTagName("ul")[0];
            var oP = oStar.getElementsByTagName("input")[0];
            var i = 0;
            var iScore=0;
            var iStar=0;
            for (i = 1; i <= aLi.length; i++){
                aLi[i - 1].index = i;
                //点击后进行评分处理
                aLi[i - 1].onclick = function (){
                    iStar = this.index;
                    fnPoint(iStar);
                    oP.value=iStar;
                }
            }
            //评分处理
            var fnPoint=function(iArg){
                //分数赋值
                iScore = iArg || iStar;
                for (i = 0; i < aLi.length; i++) aLi[i].className = i < iScore ? "on" : "";
            }
        }
        //学期选择
        $(page).on('click', '#submit', function () {
            var title=$("#title").val();
            var semester=$("#semester").val();
            var data_ = {
                'train_id':train_id,
                'teacherid':teacherid,
                'title':title,
                'star':$("#star").val()
            } ;
            if(title=='')
            {
                $.toast('请填写评价内容！',1000);
                return false;
            }
            $.ajax({
                url: 'index.php?d=wap_user&c=train_review&m=save',   //后台处理程序
                type: "post",         //数据发送方式
                dataType:"json",    //接受数据格式
                data:data_,  //要传递的数据
                success:function(data) {
                    if (data.hasOwnProperty('error_code')) {
                        $.alert(data.error_msg);
                        return false;
                    }
                    else
                    {
                        $.alert('评价教练成功。', function () {
                            window.location.replace('index.php?d=wap_user&c=train_review&m=index');
                        });
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    $.alert(errorThrown);
                }
            });
        });
    });
    $(document).on("pageInit", "#train-review-page", function(e, id, page) {
        $(".starCon").each(function () {
            var obj = $(this);
            var star = obj.attr('data-star');
            obj.find('li').each(function () {
                var item_star = $(this).attr('data-item-star');
                if (star >= item_star) {
                    $(this).addClass('on');
                }
            });
        });
    });
    /*
    练车计时器
     */
    $(document).on("pageInit", "#timer-page", function(e, id, page) {
        $(page).on('click', '#submit', function () {
            $.post("index.php?d=wap_user&c=train&m=get_time",function(data){
                var end_time=data;
                $.confirm('练车开始时间：'+start_time+'练车结束时间：'+end_time+'练车用时：'+hours+':'+mins+':'+seconds, function () {
                    $.ajax({
                        url: 'index.php?d=wap_user&c=train&m=save',   //后台处理程序
                        type: "post",         //数据发送方式
                        dataType:"json",    //接受数据格式
                        data:{id:temp_id,endtime:end_time},  //要传递的数据
                        success:function(data) {
                            if (data.hasOwnProperty('error_code')) {
                                $.alert(data.error_msg);
                                return false;
                            }
                            else
                            {
                                $.toast('操作成功，正在跳转...', 2000, 'success top');
                                window.location.replace('index.php?d=wap_user&c=train&m=index');
                            }
                        },
                        error:function(XMLHttpRequest, textStatus, errorThrown)
                        {
                            $.alert(errorThrown);
                        }
                    });
                });
            });
        });
    });
    $.init();
});

