Class(function(extend, using, self){

//    <script type="text/javascript" src="js/common.js"></script>
//    <script type="text/javascript" src="js/plugin/cropper/cropper.js"></script>
//        <script type="text/javascript" src="js/plugin/json2.js"></script>
//        <script type="text/javascript" src="js/upload-header.js"></script>

    extend("pages/page");
    using("lib/jquery.min.js");
    using("plugin/cropper")

    var info_imgs = '';
    var glob_image = new Array();
    var img_has_index = Array();
    var img_no_index = Array();
    var globe_index_id = 0;
    var glob_file_path = "";;

    var images_info = new Array();
    self.modify_card_image_ref = null;
    self.filename = "";
    self.img_contains = [];
    self.del_imgs = [];
    self.img_init_flag = [];
    self.img_fixed_flag = [];
    self.del_img_id = 0;
    self.insert_ids_qt = [];
    self.contents = '';
    self.img_no_len = 2;
    self.img_open_cout = 1;  //图片开放多少个
    self.btn_ok_flag = 0; //没有选择图片或者删除，提交无效
    self.initPage = function () {
        this.initDelImage();
        this.initImgFlag();
        this.initInsertId();
        this.bindUserImage();
    }
    // 绑定用户头像
    self.bindUserImage = function () {
        var that = this;
        info_imgs = this.modify_card_image_ref.getcardinfo();
        var user_info = this.modify_card_image_ref.getuserinfo();
        var i = 0;
        var level = user_info.level;
        var imgs_cout_on_serv = 0; //服务器图片有多少个

        this.initDefaultImg(level);
        $.each(info_imgs, function () {
            if(this.img.length > 0) {
                var val = this.index + "|" + this.img;//
                img_has_index.push(this.index);
                imagepath =  "file:///" + this.img + "?t=" + Math.random();
                that.img_init_flag[this.index] = 1;
                that.img_fixed_flag[this.index] = 1;
                $("#img_" + this.index).attr( "src", imagepath);
                $("#img_" + this.index).next().show();
                $(".box-close-item" + this.index).show();
                imgs_cout_on_serv++;
            } else {
                // $("#img_" + this.index).attr( "src", imagepath); 默认图
            }
        });

        //通过等级与服务器图片个数判断 选择图片按钮状态
        if(imgs_cout_on_serv >= that.img_open_cout) {
            this.setBtnStatue(false);
        } else{
            this.setBtnStatue(true);
        }


        for (var i = 1; i < that.img_no_len; i++) {
            if($.inArray( i, img_has_index) == -1) {
                img_no_index.push(i);
            }
        };


    }
    self.setImgpathStatus = function() {

    }
    self.showTag = function(flag) {
        var $arr2 = ["#img_container_1", "#img_container_2", "#img_container_3",  "#img_container_4", "#img_container_5", ".image-edit-box"];
        $.each($arr2, function ( index, item) {
            var f = index + 1;
            if(flag == f) {
                $(item).show();
            } else {
                $(item).hide();
            }
        });
    }
    self.images = function( index, file_path, left, top, width, height){
        this.index = index;
        this.file_path = file_path;
        this.left = left;
        this.top = top;
        this.width = width;
        this.height = height;
    }
    self.delPic = function(id){
        var that = this;
        delete img_has_index[id];
        delete that.img_contains[id];
        var img_tag = $("#img_" + id);
        img_no_index.push(id);
        that.sort(img_no_index);
        that.del_imgs[id] = 1;
        if(that.img_init_flag[id] == 1) {
            that.img_init_flag[id] = 0;
        } else {
            $("#img_container_" + id + " img").cropper("destroy");
            $("#img_container_" + id + " img").hide();
        }
        img_tag.attr( "src", "static/images/uploadheader/default.png");
        $("#new-icon_" + id).parent().hide();
        that.showTag(0);
        $("#image-edit-box").show();
        img_tag.show();
        img_tag.next().hide();
        $(".box-close-item" + id).hide();
        images_info[id] = null;
        if(img_no_index.length > 0) {
            that.setBtnStatue(true);
        }
    }
    self.initDelImage = function() {
        for (var i = 0; i < 6; i++) {
            this.del_imgs[i] = 0;
        };
    }
    self.initImgFlag = function() {
        for (var i = 0; i < 6; i++) {
            this.img_init_flag[i] = 0;
            this.img_fixed_flag[i] = 0;
        };
    }
    self.initInsertId = function() {
        for (var i = 0; i < 6; i++) {
            this.insert_ids_qt[i] = 0;
        };
    }
    self.setBtnStatue = function(status) {
        var butt = $(".file-btn");
        if(status == true) {
            butt.removeClass("disabled");
        } else {
            butt.addClass("disabled");
        }
    }
    self.initDefaultImg = function(level) {
        var that = this;
        if(level >= 5) {
            $("#img_2").attr("src", "static/images/uploadheader/default.png");
            that.img_no_len = 3;
            that.img_open_cout = 2;
            if(level >= 10) {
                $("#img_3").attr("src", "static/images/uploadheader/default.png");
                that.img_no_len = 4;
                that.img_open_cout = 3;
                if(level >= 15) {
                    $("#img_4").attr("src", "static/images/uploadheader/default.png");
                    that.img_no_len = 5;
                    that.img_open_cout = 4;
                    if(level >= 20) {
                        $("#img_5").attr("src", "static/images/uploadheader/default.png");
                        that.img_no_len = 6;
                        that.img_open_cout = 5;
                    }
                }
            }
        }
    }

    self.initEvent = function(){
        var that = this;
        $(document).delegate(".file-btn", "click", function () {

            if(img_no_index.length <= 0) return;
            glob_file_path = that.modify_card_image_ref.btn_select_file();
            if(glob_file_path.length <= 0) return;

            var shift_id = img_no_index.shift();
            img_has_index.push(shift_id);
            that.img_contains.push(shift_id);
            that.sort(img_has_index);
            that.showTag(0);
            var $img_container = $("#img_container_" + shift_id);
            $("#img_" + shift_id).hide();
            $img_container.find("img:first").attr( "src", "file:///" + glob_file_path);
            $img_container.show();
            cat_img(shift_id, glob_file_path);
        });

        $(document).delegate(".btn-box button:eq(0)", "click", function () {
            if(that.btn_ok_flag == 0) that.modify_card_image_ref.close();;

            // $(".custom-loading").show();
            startAnimation();

            var img_del = new Array(), del_txt = '',del_str = '', arr = [], filt_undefine = '' , obj = '',str = '', arr2 = [];

            $.each( images_info, function () {
                filt_undefine = typeof(this.index);
                if (filt_undefine != "undefined") {
                    that.insert_ids_qt[this.index] = 1;
                    obj = { type: 1, index: this.index, img: this.file_path, left: this.left, top: this.top, width: this.width, height: this.height};
                    str = JSON.stringify(obj);
                    arr2.push(this.index);
                    arr.push(str);
                }
            });
            var flag = 0;
            for (var i = 1; i < 6; i++) {
                if(that.img_fixed_flag[i] != that.img_init_flag[i]) {
                    for (var j = 0; j < arr2.length; j++) {
                        if (arr2[j] == i) flag = 1;
                    };

                    if(flag == 0) {
                        del_str = { type: 2, index: i};
                        del_str = JSON.stringify(del_str);
                        arr.push(del_str);
                    }
                }
                flag = 0;
            };

            if(arr.length > 0) {
                arr = arr.join(",");
                var txt = "[" + arr + "]";
                that.modify_card_image_ref.commitask(txt);
            }
        });

        $(document).delegate(".flex-box .box", "click", function () {
            var id = $(this).find(".img-preview").attr("rol");
            $.each(that.img_contains, function (index) {
                if(this == id) that.showTag(id);
            });
        });

        $(document).delegate(".flex-box .box-close .close", "click", function (event) {
            event.stopPropagation();
            var rol_id = parseInt($(this).attr("rol"));
            that.btn_ok_flag = 1;
            that.delPic(rol_id);
        });

        $(document).delegate(".btn-box button:eq(1)", "click", function () {
            that.modify_card_image_ref.btn_cancel_click();
        });

        /* 鼠标移上去，tip提示 */
        $(document).delegate('.tool .lamp', 'mousemove', function () {
            $(this).css("background-image","url(static/images/uploadheader/tips2.png)");
        }).delegate('.tool .lamp', 'mouseleave', function () {
            $(this).css("background-image","url(static/images/uploadheader/tips.png)");
        });
    }

    self.func(function(curData){
        var that = this;

        that.addCall("on_opt_result", function( op_type, index, flag) {
            // $(".custom-loading").hide();
            cancelAnimation();
            if(op_type == 2) {
                if(flag == true) {
                    that.modify_card_image_ref.close();
                }
            }
            if(op_type == 1) {
                /*添加成功或者失败后做处理*/
                if(flag == true) {
                    that.modify_card_image_ref.close();
                }
            }
        });

        that.addCall("cat_img", function(id, glob_file_path) {
            var $image = $("#img_container_" + id + " img"),
                $dataX = $("#dataX"),
                $dataY = $("#dataY"),
                $dataHeight = $("#dataHeight"),
                $dataWidth = $("#dataWidth");
            $image.cropper({
                aspectRatio: 5 / 3,
                multiple: false,
                zoomable: false,
                resizable:true,
                rotatable: false,
                preview: "#preview_" + id,
                done: function(data) {
                    var x = data.x;
                    var y = data.y;
                    var width = data.width;
                    var height = data.height;
                    $dataX.val(x);
                    $dataY.val(y);
                    $dataHeight.val(height);
                    $dataWidth.val(width);
                    $("#new-icon_" + id).parent().show();
                    $("#img_" + id).next().show();
                    $(".box-close-item" + id).show();
                    images_info[id] = new that.images( id, glob_file_path, x, y, width, height);
                    if(img_no_index.length <= 0) {
                        that.setBtnStatue(false);
                    }
                    that.btn_ok_flag = 1;
                }
            });
        });
        //
        var _can_canvas = document.getElementById("custom-loading");
        var _can_ctx = _can_canvas.getContext("2d");
        var _can_images = [];

        for(var i = 1; i <= 13; i++) {
            var img = new Image();

            img.onload = function() {
                _can_images[this.num - 1] = this;
            };
            img.num = i;
            img.src = "static/images/loading/" + i + ".png";
        }

        var _can_index = 0;
        var _can_tid = null;
        var _can_isAnimation = false;
        var _can_requestAnimationFrame = window.webkitRequestAnimationFrame;
        var _can_cancelAnimationFrame = window.webkitCancelRequestAnimationFrame;

        that.addCall("can_showLoading", function() {
            _can_tid = setTimeout(function() {
                if(_can_tid) {
                    clearTimeout(_can_tid);
                    _can_tid = null;
                }

                _can_canvas.width = _can_canvas.width;
                _can_ctx.drawImage(_can_images[_can_index], 0, 0);

                _can_index = _can_index >= 12 ? 0 : _can_index + 1;
                _can_requestAnimationFrame(can_showLoading);
            }, 45);
        });

        that.addCall("startAnimation", function() {
            if(_can_isAnimation) {
                return;
            }
            _can_index = 0;
            _can_isAnimation = true;
            $("#custom-loading").show();
            can_showLoading();
        });

        that.addCall("cancelAnimation", function() {
            _can_isAnimation = false;
            $("#custom-loading").hide();

            if(_can_tid) {
                clearTimeout(_can_tid);
                _can_tid = null;
            }
            _can_cancelAnimationFrame(can_showLoading);
        });

        that.modify_card_image_ref =  curData; //cardset;

        that.sup().constructor(curData);

        that.initPage();
        that.initEvent();
    })
})