$('html').css('height', '100%');
(function () {
    var bodyWidth = document.body.clientWidth - 64;

    function getHeight(url) {
        var wh = url.split('?')[1].split(',');
        return parseFloat(wh[1]) / parseFloat(wh[0]) * bodyWidth;
    }

    var imgLength = $('.thumbnail_image img').length;
    for (var i = 0; i < imgLength; i++) {
        (function () {
            var j = i;
            var ele = $('.thumbnail_image img').eq(j);
            var url = ele.attr('data-original');
            if (url.indexOf("?") > -1) {
                ele.css({'width': bodyWidth + "px", 'height': getHeight(url) + "px"});
            }
        })(i)
    }
})();

(function(){
    if($('.open_app_btn').length > 0) {
        $('.bottom_flex a').css('margin-right','32px');
    }
})();

var Session_manage = (function(){
    if(!window.sessionStorage) {
        console.log('该设备不支持sessionStorage!');
        return;
    }
    return {
        set_storage:function(key,val){
            window.sessionStorage.setItem(key,val);
        },
        get_storage:function(key){
            return window.sessionStorage.getItem(key);
        },
        remove_storage:function(key){
            window.sessionStorage.removeItem(key);
        }
    }
})();


if (Session_manage.get_storage('skip')) {
    window.location.reload();
    Session_manage.remove_storage('skip');
    Session_manage.set_storage('is_skip', true);
};


var host = (function () {
    return window.location.protocol + "//" + window.location.host;
})();


(function(){
    if($('.button_null.button_vote').length >0 && $('.button_null.button_vote').text().indexOf('已经')) {
        $('input[type="radio"]').attr('disabled', 'disabled');
        $('input[type="checkbox"]').attr('disabled', 'disabled');
    }
})();

$('.thumbnail img').picLazyLoad({
    threshold:100
});

var specialId = (function () {
    var special_id = $('body').attr('data-special_id');
    return special_id;
})();

var Comment_type = '';

var need_scroll = true;

var event = function (obj, eventType, callback) {
    obj.live(eventType, callback);
};

var get_ajax = function (url, callback) {
    $.ajax({
        type: "get",
        async: false,
        url: url,
        dataType: "jsonp",
        jsonp: "callback",
        jsonpCallback: "flightHandler",
        success: callback
    });
};


var GetQueryString = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)return unescape(r[2]);
    return null;
};


var statShow = function () {
    if ($('.percentage').length > 0) {
        setTimeout(function () {
            for (var i = 0; i < $('.percentage').length; i++) {
                var num = $('.percentage')[i].innerHTML;
                $('.stat')[i].style.width = num;
            }
        }, 300);
        clearInterval(a);
    }
};
var a = setInterval(statShow, 10);


var Vote = function (obj,type) {
    var _self = this;
    this.type = type;
    this.answer = [];
    this.getAnswer = function () {
        return this.answer;
    };
    this.obj = obj;
    this.C = function () {
        event(_self.obj, 'change', function () {
            switch (_self.type) {
                case 0:
                case 1 : {
                    _self.answer = [];
                    $.each(_self.obj, function () {
                        if (this.checked) {
                            _self.answer.push($(this).val());
                        }
                    });
                    break;
                }
                case 2: {
                    var val = $(this).val();
                    if ($(this).prop('checked')) {
                        if (_self.answer.length >= 2) {
                            for (var g = 0; g < _self.obj.length; g++) {
                                if (_self.obj.eq(g).val() == _self.answer[0]) {
                                    _self.obj.eq(g).prop('checked', false);
                                    _self.answer.splice(0, 1);
                                    _self.answer.push(val);
                                    break;
                                }
                            }
                        }
                        else {
                            _self.answer = [];
                            $.each(_self.obj, function () {
                                if (this.checked) {
                                    _self.answer.push($(this).val());
                                }
                            });
                        }
                    }
                    else {
                        _self.answer = [];
                        $.each(_self.obj, function () {
                            if (this.checked) {
                                _self.answer.push($(this).val());
                            }
                        });
                    }
                }
            }
        });
    };
};

var VoteList = function(){
    var vote_items = [];
    (function () {
        var votes = $('.vote').length;
        var num = 0;
        var vote_nums = 'q' + num;
        for (var j = 0; j < votes; j++) {
            vote_nums = new Vote($('input[name="vote' + num + '"]'), parseInt($('.vote_type').eq(j).attr('data-type')));
            vote_items.push(vote_nums);
            vote_nums.C();
            num++;
        }
    })(vote_items);
    var formatDatas = function () {
        var options = function () {
            var options = [];
            for (var i = 0; i < $('.vote_options label').length; i++) {
                var option = $.trim($('.vote_options label').eq(i).text());
                options.push(option);
            }
            return options;
        };
        var sum_num = function (datas) {
            var sum = 0;
            for (var i = 0; i < datas.length; i++) {
                sum += parseFloat(datas[i]);
            }
            return sum;
        };
        return {
            result: function (data) {
                var option_items = options();
                var sum = sum_num(data);
                var vote_res = [];
                for (var i = 0; i < data.length; i++) {
                    var g = {};
                    g.name = option_items[i];
                    g.num = parseInt(data[i]);
                    g.percentage = data[i] ? Math.round(data[i] / sum * 100) : 0;
                    vote_res.push(g);
                }
                return vote_res;
            }
        }
    };
    var vote_html = function (datas) {
        var resData = datas;
        var html = '<div class="results">';
        for (var i = 0; i < resData.length; i++) {
            html += '<div class="result">' +
                '<div class="result_option">' + resData[i].name + '</div>' +
                '<div class="status">' +
                '<div class="status_line">' +
                '<div class="stat"></div>' +
                '<div class="status_bg"></div>' +
                '</div>' +
                '<span class="num">' + resData[i].num + '票</span>' +
                '<span class="percentage">' + resData[i].percentage + '%</span>' +
                '</div>' +
                '</div>';
        }
        html += '</div>';
        return html;
    };
    this.getAnswers = function () {
        var answers = [];
        for (var i = 0; i < vote_items.length; i++) {
            if (vote_items[i].getAnswer().length == 0) {
                continue;
            }
            var vote = {};
            vote.index = i;
            vote.answer = vote_items[i].getAnswer();
            answers.push(vote);
        }
        return answers;
    };
    this.result_html = function(datas){
        $('.vote_options').css('display', 'none');
        for(var i = 0;i<datas.length;i++) {
            $('.vote_pro').eq(i).after(vote_html(formatDatas().result(datas[i])));
        }
        statShow();
    }
};


var Question = function (obj, handleType) {
    this.obj = obj;
    this.handleType = handleType;
    this.answer = [];
    this.getAnswer = function () {
        return this.answer;
    };
    this.C = function () {
        var _self = this;
        _self.obj.on('change', function () {
            switch (_self.handleType) {
                case 0:
                case 1 : {
                    _self.answer = [];
                    $.each(_self.obj, function () {
                        if (this.checked) {
                            _self.answer.push($(this).val());
                        }
                    });
                    break;
                }
                case 2: {
                    var val = $(this).val();
                    if ($(this).prop('checked')) {
                        if (_self.answer.length >= 2) {
                            for (var g = 0; g < _self.obj.length; g++) {
                                if (_self.obj.eq(g).val() == _self.answer[0]) {
                                    _self.obj.eq(g).prop('checked', false);
                                    _self.answer.splice(0, 1);
                                    _self.answer.push(val);
                                    break;
                                }
                            }
                        }
                        else {
                            _self.answer = [];
                            $.each(_self.obj, function () {
                                if (this.checked) {
                                    _self.answer.push($(this).val());
                                }
                            });
                        }
                    }
                    else {
                        _self.answer = [];
                        $.each(_self.obj, function () {
                            if (this.checked) {
                                _self.answer.push($(this).val());
                            }
                        });
                    }
                    break;
                }
            }
        });
    }
};


var QuestionList = function () {
    var question_items = [];
    (function (question_items) {
        var questions = $('.question').length;
        var num = 0;
        var question_nums = 'q' + num;
        for (var j = 0; j < questions; j++) {
            question_nums = new Question($('input[name="question' + num + '"]'), parseInt($('.question_type').eq(j).attr('data-type')));
            question_items.push(question_nums);
            question_nums.C();
            num++;
        }
    })(question_items);
    this.getAnswers = function () {
        var answers = [];
        for (var i = 0; i < question_items.length; i++) {
            if (question_items[i].getAnswer().length == 0) {
                continue;
            }
            var question = {};
            question.index = i;
            question.answer = question_items[i].getAnswer();
            answers.push(question);
        }
        return answers;
    };
};






var ReplyItem = function (comment, members) {
    var proxy = function () {
        var getNickName = function (userId) {
            for (var i = 0; i < members.length; i++) {
                if (members[i]['member_id'] == userId) {
                    return members[i]['nickname'];
                }
            }
        };
        var getAvatar = function (userId) {
            for (var i = 0; i < members.length; i++) {
                if (members[i]['member_id'] == userId) {
                    return members[i]['avatar'];
                }
            }
        };
        var getTime = function (time) {
            var date = '';
            var location = parseInt(new Date().getTime() / 1000);
            var diffHour = parseInt((location - time) / 60 / 60);
            var diffMinutes = parseInt((location - time) / 60);
            if (diffHour <= 0) {
                if (diffMinutes >= 0 && diffMinutes < 5) {
                    date = "刚刚";
                }
                else {
                    date = diffMinutes + "分钟前";
                }
            }
            if (diffHour < 24 && diffHour > 0) {
                date = diffHour + '小时前';
            }
            if (diffHour >= 24) {
                var milliseconds = time * 1000;//秒变微秒
                var dat = new Date(milliseconds);//生成日期
                var month = dat.getMonth() + 1;    //取得月
                var date1 = dat.getDate(); //取得天
                var hour = dat.getHours();//取得小时
                var minutes = dat.getMinutes();//取得分钟
                if (hour < 10) {
                    hour = '0' + dat.getHours();
                }
                if (minutes < 10) {
                    minutes = '0' + dat.getMinutes();
                }
                date = month + '月' + date1 + '日' + hour + ':' + minutes;
            }
            return date;
        };
        return {
            getNickName: getNickName,
            getAvatar: getAvatar,
            getTime: getTime
        }
    };
    var commentdata = comment;
    var sub = '';
    var subnum = 10;
    if (comment) {
        var defaultSubNum = comment['sub_count'];
    }
    var load_btn = '';
    var loadpage = 2;
    var isLike = function () {
        var like = '';
        if (commentdata['supported'] == false) {
            like = '<a href="javascript:void(0)" class="like_btn" data-comment_id="' + commentdata['comment_id'] + '">' +
                '<span class="like_num">' + commentdata['likes'] + '</span><span class="like_icon_null"></span></a>';

        }
        else {
            like = '<a href="javascript:void(0)" class="like_btn active" data-comment_id="' + commentdata['comment_id'] + '">' +
                '<span class="like_num">' + commentdata['likes'] + '</span><span class="like_icon_null like_icon"></span></a>';
        }
        return like;
    };
    var parentHTML = function () {
        var html = '<div class="comment_item parent_reply" data-comment_id="' + commentdata['comment_id'] + '">' +
            '<div class="subject">' +
            '<div class="subject_box">' +
            '<div class="subject_image">' +
            '<img src="' + proxy().getAvatar(commentdata['user_id']) + '" alt="熊猫美妆">' +
            '</div>' +
            '<div class="subject_name">' +
            '<p class="name reply_people" data-parent="true" data-comment_id="' + commentdata['comment_id'] + '">' + proxy().getNickName(commentdata['user_id']) + '</p>' +
            '<p class="time">' + proxy().getTime(commentdata['addtime']) + '</p>' +
            '</div>' +
            '</div>' +
            '<div class="like">' + isLike() +
            '</div>' +
            '</div>' +
            '<p class="msg">' + commentdata['content'] + sub +
            '</p>' + load_btn +
            '</div>';
        return html;
    };
    var subHTML = function (comment) {
        var subHtml = '<p class="reply">' +
            '<span class="reply_people" data-comment_id="' + comment['comment_id'] + '">' + proxy().getNickName(comment['user_id']) + '</span>' +
            '回复' +
            '<span class="reply_people" data-comment_id="' + comment['comment_id'] + '"  data-response_id="' + comment['response_id'] + '">' +
            proxy().getNickName(comment['to_user']) + '</span>:' + comment['content'] + '</p>';
        return subHtml;
    };
    var empty = function () {
        var empty = '<p class="reply_empty">精彩评论虚位以待</p>';
        return empty;
    };

    return {
        exportHTML: function () {
            return parentHTML();
        },
        addSub: function (comment) {
            sub += subHTML(comment);
        },
        insert: function (comment) {
            return subHTML(comment);
        },
        empty: function () {
            $('.comment_list').append(empty());
        },
        addLoadBtn: function () {
            load_btn = '<div class="button_load_more" data-page="' + loadpage + '">查看更多评论</div>';
        },
        getLoadMore: function () {
            return defaultSubNum > subnum;
        },
        oneItem: subHTML
    }
};


var ReplyList = function () {
    var created = function (replys) {
        var replyList = [];
        var replyIndex = replyList.length;
        if (!replys || replys['comments'].length == 0) {
            return;
        }
        for (var i = 0; i < replys['comments'].length; i++) {
            if (replys['comments'][i]['response_id'] == 0) {
                replyList.push(new ReplyItem(replys['comments'][i], replys['members']));
                replyIndex++;
            }
            else {
                replyList[replyIndex - 1].addSub(replys['comments'][i]);
            }
        }
        return replyList;
    };
    var exportHTML = function (replyItem) {
        var datas = created(replyItem);
        if ($('.reply_empty').length > 0) {
            $('.reply_empty').css('display', 'none');
        }
        for (var i = 0; i < datas.length; i++) {
            if (datas[i].getLoadMore()) {
                datas[i].addLoadBtn();
            }
            $('.comment_list').append(datas[i].exportHTML());
        }
    };
    var specialReply = function (replyItem) {
        var datas = created(replyItem);
        if ($('.reply_empty').length > 0) {
            $('.reply_empty').css('display', 'none');
        }
        for (var i = 0; i < datas.length; i++) {
            $('.comment_list').prepend(datas[i].exportHTML());
        }
    };
    var curpage = 1;
    var isLoad = false;
    var getData = function () {
        isLoad = true;
        var url = host + '/mobile/index.php?act=member_ugc&op=comments&client_type=ajax&special_id=' + specialId + '&curpage=' + curpage;
        get_ajax(url, function (data) {
            isLoad = false;
            if (data.code !== 200) {
                alert(data.message);
            }
            else {
                var replyDatas = data.datas;
                if (replyDatas['comments'].length == 0) {
                    $('.comment_list').append(new ReplyItem().empty());
                    return;
                }
                exportHTML(replyDatas);
                if (need_scroll && GetQueryString('need_scroll')) {
                    need_scroll = false;
                    $('.comment_label').trigger('click');
                }
                if (replyDatas.mobile_page['hasmore'] == true) {
                    curpage++;
                    $(window).on('scroll', loadEvent);
                }
                else {
                    $(window).unbind('scroll',loadEvent);
                }
            }
        });
    };
    var loadEvent = function () {
        var scrollTop = $(this).scrollTop();
        var scrollHeight = $(document).height();
        var windowHeight = $(this).height();
        if ((scrollTop + windowHeight) - scrollHeight > -1000 && isLoad == false) {
            getData();
        }
    };
    (function () {
        getData();
    })();

    return {
        exportHTML: exportHTML,
        specialReply: specialReply
    }
};


var CommentsBox = function () {
    var maxSize = 150;
    var show = function () {
        $('.pop').show();
        $('.answer_comments').show();
        $('#comments').focus();
        $('.bottom_flex').css('opacity','0');
        $(document).on("touchmove", function (event) {
            event.preventDefault();
        });
    };

    var close = function () {
        $('.pop').hide();
        $('.answer_comments').hide();
        $('#comments').blur().val('');
        $('.surplus').html(maxSize);
        $(document).off("touchmove");
        setTimeout(function(){
            $('.bottom_flex').css('opacity','1');
        },500);
    };
    var surplusInput = function () {
        event($('#comments'), 'input', function () {
            var val = $(this).val().length;
            var surplus = 0;
            if (val <= maxSize) {
                surplus = maxSize - val;
            }
            else {
                $(this).val($(this).val().substring(0, maxSize));
            }
            $('.surplus').html(surplus);
        })
    };
    var res = {
        comment_id: '',
        response_id: ''
    };
    event($('.reply_people'), 'click', function () {
        if ($(this).hasClass('name')) {
            $(this).parents('.comment_item').addClass('insert');
        }
        else {
            $(this).parent('p').addClass('insert');
        }
        res.response_id = '';
        res.comment_id = '';
        var to_user_name = $(this).text();
        commentsBox.setPlaceHolder('回复' + to_user_name).show();
        Comment_type = 'res_people';
        if ($(this).attr('data-response_id') !== '' || $(this).attr('data-response_id')) {
            res.response_id = $(this).attr('data-response_id');
            res.comment_id = $(this).attr('data-comment_id');
        }
        else {
            res.comment_id = $(this).attr('data-comment_id');
        }
    });

    var submitComments = function () {
        var url = '';
        var submited = false;
        event($('.comments_submit'), 'click', function () {
            var _self = $(this);
            _self.addClass('submited');
            if(submited) {
                return;
            }
            submited = true;
            if ($('#comments').val() == '') {
                $('#comments').focus();
                _self.removeClass('submited');
                submited = false;
                return;
            }
            var textVal = $('#comments').val();
            if (Comment_type == 'special_id') {
                url = host + '/mobile/index.php?act=member_ugc&op=comment&client_type=ajax&special_id=' + specialId + '&content=' + encodeURI(textVal);
                get_ajax(url, function (data) {
                    submited = false;
                    _self.removeClass('submited');
                    if (data.code !== 200) {
                        alert(data.message);
                        return;
                    }
                    replyList.specialReply(data.datas);
                    commentsBox.close();
                    $('.handle_result').text('评论成功').addClass('show');
                    setTimeout(function () {
                        $('.handle_result').removeClass('show');
                    }, 1500);
                })
            }
            else {
                if (res.response_id) {
                    url = host + '/mobile/index.php?act=member_ugc&op=comment&client_type=ajax&special_id=' + specialId + '&content=' + encodeURI(textVal) + '&response_id=' + res.response_id + '&comment_id=' + res.comment_id;
                }
                else {
                    url = host + '/mobile/index.php?act=member_ugc&op=comment&client_type=ajax&special_id=' + specialId + '&content=' + encodeURI(textVal) + '&comment_id=' + res.comment_id;
                }
                get_ajax(url, function (data) {
                    submited = false;
                    _self.removeClass('submited');
                    if (data.code !== 200) {
                        alert(data.message);
                        $(this).removeClass('submited');
                        return;
                    }

                    var insertData = data.datas;
                    var sub = new ReplyItem(insertData['comments'][0], insertData['members']);
                    if ($('.insert').hasClass('comment_item')) {
                        if ($('.insert .reply').length > 0) {
                            $('.insert .reply').last().after(sub.insert(insertData['comments'][0], insertData['members']));
                        }
                        else {
                            $('.insert .msg').after(sub.insert(insertData['comments'][0], insertData['members']));
                        }
                    }
                    else {
                        $('.insert').after(sub.insert(insertData['comments'][0], insertData['members']));
                    }
                    $('.insert').removeClass('insert');
                    commentsBox.close();
                    $('.handle_result').text('评论成功').addClass('show');
                    setTimeout(function () {
                        $('.handle_result').removeClass('show');
                    }, 1500);
                })
            }
        });
    };
    var setPlaceHolder = function (content) {
        $('#comments').attr('placeholder', content);
        return this;
    };
    (function () {
        // close();
        surplusInput();
        submitComments();
        // inputFocus();
    })();
    return {
        show: show,
        setPlaceHolder: setPlaceHolder,
        close: close
    }
};

var PageVideo = function () {
    var createDom = function (videosrc, videoposter,is_iphone) {
        var a = document.createElement('video');
        a.poster = videoposter;
        a.src = videosrc;
        // a.setAttribute('x5-video-player-type','h5');
        // a.setAttribute('x5-video-orientation','portraint');
        // a.setAttribute('x5-video-player-fullscreen','true');
        a.setAttribute('webkit-playsinline',true);
        a.setAttribute('playsinline',true);
        if(is_iphone) {
            a.setAttribute('controls',true);
        }
        a.className = 'video_play';
        return a;
    };
    this.append = function () {
        var play_icon = '';
        if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
            for (var i = 0; i < $('.video_box').length; i++) {
                var videoSrc = $('.video_box').eq(i).attr('data-src');
                var videoVideoposter = $('.video_box').eq(i).attr('data-poster');
                $('.video_box').eq(i).append(createDom(videoSrc, videoVideoposter,true)).append(play_icon);
            }
        } else if (/(Android)/i.test(navigator.userAgent)) {
            play_icon = '<span class="play_icon"></span>';
            for (var i = 0; i < $('.video_box').length; i++) {
                var videoSrc = $('.video_box').eq(i).attr('data-src');
                var videoVideoposter = $('.video_box').eq(i).attr('data-poster');
                $('.video_box').eq(i).append(createDom(videoSrc, videoVideoposter)).append(play_icon);
            }
        } else {}

    };
};


event($('.play_icon'),'touchstart',function(){
    var _self = $(this);
    var index = $('.play_icon').index(this);
    document.getElementsByClassName('video_play')[index].addEventListener('play',function(){
        $('.bottom_flex').hide();
        _self.hide();
    },false);
    document.getElementsByClassName('video_play')[index].addEventListener('pause',function(){
        $('.bottom_flex').show();
        _self.show();
    },false);
    $('.video_play').get(index).play();
});



var vote_list = new VoteList();
var Pagevideo = new PageVideo();
Pagevideo.append();
var questionList = new QuestionList();
var commentsBox = new CommentsBox();
var replyList = new ReplyList();


$(window).on('scroll',function(){
    var top = $(this).scrollTop();
    $('.answer_comments').css('top',top+360);
    // $('.pop').css('top',top);
    $('.pop').css('height',$('body').height()+100);
});

event($('.bonus_item'), 'click', function () {
    if ($(this).hasClass('dis')) {
        return;
    }
    for (var i = 0; i < $('.bonus_item').length; i++) {
        if ($('.bonus_item').eq(i).hasClass('dis')) {
            continue;
        }
        else {
            $('.bonus_item').eq(i).removeClass('active');
        }
    }
    $(this).addClass('active');
});

event($('#discount'), 'change', function () {
    var val = $(this).val();
    var select_option = 0;
    $('.bonus_item').removeClass('dis').removeClass('active');
    for (var i = 0; i < $('#discount option').length; i++) {
        if ($('#discount option').eq(i).attr('value') == val) {
            select_option = i;
            break;
        }
    }
    for (var j = 0; j < $('.bonus_box .money').length; j++) {
        if (parseFloat($('.bonus_box .money').eq(j).text()) > parseFloat($('#discount option').eq(select_option).attr('data-money'))) {
            $('.bonus_item').eq(j).addClass('dis');
        }
    }
});


event($('.btn_appreciate'), 'click', function () {
    $('.loader').show();
    if (from_app && !logined) {
        call_native_handler('on_native_click', '{"action":"login"}', function (data) {
            $('.loader').hide();
            var jsdata = JSON.parse(data);
            if (!jsdata.login) {
                return;
            }
            else {
                logined = true;
                var url = host + '/mobile/index.php?act=member_ugc&op=mine_bonus&client_type=ajax';
                get_ajax(url, function (data) {
                    $('.loader').hide();
                    if (data.code !== 200) {
                        alert(data.message);
                        return;
                    }
                    var datas = data.datas['bonus_rate'];
                    var html = '';
                    for (var i = 0; i < datas.length; i++) {
                        html += '<option value="' + datas[i].rate + '" data-money="' + datas[i].total + '">' + datas[i].rate + '%</option>';
                    };
                    $('.appreciate_pop').removeClass('close').addClass('show');
                    $('#discount').append(html).trigger('change');
                });
            }
        });
    }
    else {
        $('.loader').hide();
        var url = host + '/mobile/index.php?act=member_ugc&op=mine_bonus&client_type=ajax';
        get_ajax(url, function (data) {
            $('.loader').hide();
            if (data.code !== 200) {
                alert(data.message);
                return;
            }
            var datas = data.datas['bonus_rate'];
            var html = '';
            for (var i = 0; i < datas.length; i++) {
                for (var i = 0; i < datas.length; i++) {
                    html += '<option value="' + datas[i].rate + '" data-money="' + datas[i].total + '">' + datas[i].rate + '%(余额: '+datas[i].total+'元)</option>';
                };
            };
            $('.appreciate_pop').removeClass('close').addClass('show');
            $('#discount').append(html).trigger('change');
        });
    }
});

event($('#close_appreciate'), 'click', function () {
    $('#discount').empty();
    $('.bonus_item').removeClass('active').removeClass('dis');
    $('.live_msg').val('');
    $('.appreciate_pop').removeClass('show').addClass('close');
    $('.pop').hide();
});


event($('#submit_appreciate'), 'click', function () {
    var rate = $('#discount').val();
    var money = $('.bonus_item.active .money').text();
    var content = $('#live_msg').val();
    var url = host + '/mobile/index.php?act=member_ugc&op=appreciate&client_type=ajax&rate=' + rate + '&money=' + money + '&content=' + encodeURI(content) + '&special_id=' + specialId;
    get_ajax(url, function (data) {
        if (data.code !== 200) {
            alert(data.message);
            return;
        }
        $('.handle_result').text('打赏成功').addClass('show');
        $('#close_appreciate').trigger('click');
        setTimeout(function () {
            $('.handle_result').removeClass('show');
            window.location.reload();
        }, 1500);
    })
});


event($('.msg_btn'), 'click', function () {
    if (from_app && !logined) {
        call_native_handler('on_native_click', '{"action":"login"}', function (data) {
            var jsdata = JSON.parse(data);
            if (!jsdata.login) {
                return;
            }
            else {
                logined = true;
                commentsBox.setPlaceHolder('我来说两句').show();
                Comment_type = 'special_id';
            }
        });
    }
    else {
        commentsBox.setPlaceHolder('我来说两句').show();
        Comment_type = 'special_id';
    }
});


event($('.focus'),'touchstart',function(){
    var _self = $(this);
    if(_self.hasClass('active')) {
        return;
    }
    if (from_app && !logined) {
        call_native_handler('on_native_click', '{"action":"login"}', function (data) {
            var jsdata = JSON.parse(data);
            if (!jsdata.login) {
                return;
            }
            else {
                logined = true;
                var url = host + "/mobile/index.php?act=member_ugc&op=subscribe_author&client_type=ajax&special_id=" + specialId;
                get_ajax(url,function(data){
                    if (data.code !== 200) {
                        alert(data.message);
                        return;
                    }
                    _self.addClass('active').text('已关注');
                });
            }
        });
    }
    else {
        var url = host + "/mobile/index.php?act=member_ugc&op=subscribe_author&client_type=ajax&special_id=" + specialId;
        get_ajax(url,function(data){
            if (data.code !== 200) {
                alert(data.message);
                return;
            }
            _self.addClass('active').text('已关注');
        });
    }
});


$('#submit_btn').on('click', function () {
    var _self = $(this);
    $('.loader').show();
    $(this).addClass('button_null');
    var allAnswers = {};
    var voteAnswers = vote_list.getAnswers() || [];
    var resAnswers = questionList.getAnswers() || [];
    if ($('.vote').length > 0 && voteAnswers.length !== $('.vote').length) {
        $(this).removeClass('button_null');
        $('.loader').hide();
        alert('亲!请完成投票');
        return;
    }
    if ($('.vote').length > 0) {
        allAnswers.vote = voteAnswers;
    }
    if ($('.question_list').length > 0) {
        allAnswers.question = resAnswers;
    }
    var url = host + "/mobile/index.php?act=special&op=submit&client_type=ajax&special_id=" + specialId + '&content=' + encodeURI(JSON.stringify(allAnswers));
    get_ajax(url, function (data) {
        $('.loader').hide();
        if (data.code !== 200) {
            alert(data.message);
            $('.loader').hide();
            return;
        }
        _self.css('display', 'none');

        if ($('.vote').length <= 0 && $('.question_list').length <= 0) {
            if (data.datas['bonus_url'] !== "") {
                $('.pop').show();
                $('.bonus_label').html('感谢您的参与<br/>恭喜获得'+data.datas['amount']+'元红包');
                $('.bonus_page').attr('href', data.datas["bonus_url"]).addClass('fade-in').show();
                $('.close_icon').addClass('rotate').show();
                $('.bonus_page img').attr('src', data.datas["sender_avatar"]);
            }
        }

        if ($('.vote').length > 0 && $('.question_list').length <= 0) {
            vote_list.result_html(data.datas['vote_result']);
            if (data.datas['bonus_url'] !== "") {
                $('.pop').show();
                $('.bonus_label').html('感谢您的参与<br/>恭喜获得'+data.datas['amount']+'元红包');
                $('.bonus_page').attr('href', data.datas["bonus_url"]).addClass('fade-in').show();
                $('.close_icon').addClass('rotate').show();
                $('.bonus_page img').attr('src', data.datas["sender_avatar"]);
            }
        }

        if ($('.question_list').length > 0) {
            if($('.vote').length > 0) {
                vote_list.result_html(data.datas['vote_result']);
            }
            var answerDiff = data.datas['answer_diff'];
            var correct = 0;
            var error = 0;
            var result_msg = '';
            for (var i = 0; i < answerDiff.length; i++) {
                var diff_correct = answerDiff[i]['origin'];
                var correct_answers = [];
                for(var j=0;j<diff_correct.length;j++) {
                    var answer_num = String.fromCharCode(diff_correct[j]+65);
                    correct_answers.push(answer_num);
                }
                $('.question_options').eq(i).after('<div class="right_answer">正确答案：'+correct_answers.join('')+'</div>');
                if (answerDiff[i]['correct']) {
                    $('.question_options').eq(i).addClass('state_right');
                    correct++;
                }
                else {
                    $('.question_options').eq(i).addClass('state_error');
                    error++;
                }
            }
            if(correct == 0) {
                result_msg = '很抱歉！您全答错了，您需要加把劲哦！';
                $('.question_result p').text(result_msg);
                $('.question_result').addClass('show');
                $('.question_result .close').on('click',function(){
                    $('.question_result').removeClass('show');
                });
                return;
            }
            if (error == 0 && correct == answerDiff.length) {
                result_msg = '恭喜您！您全答对了！<br />获得'+data.datas['amount']+'元红包';
            }
            if (error !== 0 && correct > 0 && correct < answerDiff.length){
                result_msg = '恭喜你，答对了'+correct+'道题<br/>获得'+data.datas['amount']+'元红包';
            }
            if (data.datas['bonus_url'] !== "") {
                $('.pop').show();
                $('.bonus_label').html(result_msg);
                $('.bonus_page').attr('href', data.datas["bonus_url"]).addClass('fade-in').show();
                $('.close_icon').addClass('rotate').show();
                $('.bonus_page img').attr('src', data.datas["sender_avatar"]);
            }
        }
        $('.bonus_page').on('click',function () {
            if(!Session_manage.get_storage('is_skip')) {
                Session_manage.set_storage('skip',true);
            }
        });
        $('input[type="radio"]').attr('disabled', 'disabled');
        $('input[type="checkbox"]').attr('disabled', 'disabled');
    });
});


event($('.like_btn'), 'click', function () {
    $('.loader').show();
    var url = '';
    var $this = $(this);
    if ($(this).attr('data-comment_id')) {
        var comment_id = $(this).attr('data-comment_id');
        url = host + '/mobile/index.php?act=member_ugc&op=support&client_type=ajax&special_id=' + specialId + '&comment_id=' + comment_id;
        get_ajax(url, function (data) {
            $('.loader').hide();
            if (data.code !== 200) {
                alert(data.message);
                $('.loader').hide();
                return;
            }
            var localLike = $this.find('.like_num').text();
            if (data.datas['supported'] == true) {
                $this.find('.like_num').text(parseInt(localLike) + 1);
            }
            else {
                $this.find('.like_num').text(parseInt(localLike) - 1);
            }
            $this.toggleClass('active');
            $this.find('.like_icon_null').toggleClass('like_icon');
        });
    }
    else {
        url = host + '/mobile/index.php?act=member_ugc&op=support&client_type=ajax&special_id=' + specialId;
        get_ajax(url, function (data) {
            $('.loader').hide();
            if (data.code !== 200) {
                alert(data.message);
                $('.loader').hide();
                return;
            }
            $this.find('.like_icon_null').toggleClass('like_icon');
        })
    }
});

$('.close_icon').on('click', function () {
    $('.pop').hide();
    $('.bonus_page').hide();
    $('.close_icon').hide();
});


event($('.button_load_more'), 'click', function () {
    var _self = $(this);
    $('.loader').show();
    var comment_id = $(this).parent('.comment_item').attr('data-comment_id');
    var curpage = $(this).attr('data-page');
    var url = host + '/mobile/index.php?act=member_ugc&op=comments&client_type=ajax&special_id=' + specialId + '&comment_id=' + comment_id + '&curpage=' + curpage + '&page=4';
    get_ajax(url, function (data) {
        $('.loader').hide();
        if (data.code !== 200) {
            alert(data.message);
            return;
        }
        var items = '';
        var datas = data.datas['comments'];
        for (var i = 0; i < datas.length; i++) {
            items += new ReplyItem([], data.datas['members']).oneItem(datas[i]);
        }
        _self.before(items);
        if (!data['datas'].mobile_page['hasmore']) {
            _self.css('display', 'none');
        }
        else {
            _self.attr('data-page', parseInt(curpage) + 1);
        }
    })
});

event($('.comment_label'), 'click', function () {
    // var container = $(window).offset().top,
    var    scrollTo = $('.comment').offset().top;
    $(window).scrollTop(scrollTo);
});

event($('.pop'), 'click', function () {
    commentsBox.close();
});

event($('.share_icon_null'), 'touchend', function (e)
{
    e.preventDefault();
    function addslashes (str) {
        return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
    }

    var share_title = addslashes(title);
    var share_sub_title = addslashes(sub_title);

    var jsonobject = {
        action:"share_page",
        params: {
            title:share_title,
            sub_title:share_sub_title,
            img_url:img_url,
            url:url
        }
    };
    call_native_handler('on_native_click',JSON.stringify(jsonobject));
});


register_js_hander('onKeyboardClose', function (data, callback) {
    commentsBox.close();
});

function app() {
    var app = navigator.userAgent.toLowerCase(),//判断设备
        app_nav = navigator.appVersion.toLowerCase(),
        href = '';
    if (app_nav.indexOf('iphone') > -1 && app.indexOf('iphone')) {
        href = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.lrlz.beautyshop';
    } else if (app.indexOf('micromessenger') > -1 && app_nav.indexOf('android') > -1) {
        href = "http://p.lrlz.com/hfive/android_down/index.html";
    }
    else {
        href = "javascript:void(0)";
    }

    return href;
}

var open_href = app();
$('.open_app_btn').attr('href', open_href);
