//上传文件,支持多插件
//2014-11-18
/*取值方式:1上传控件的files属性,2隐藏控件,3插件CumulativeUploadFiles变量
*/
var Upload = function (currentUploadName) {
    var controlType = 0, fileControl, _targetUrl, context, _multiple;
    var callbackFun = null; var hiddenFileControl = currentUploadName + '$';//隐藏控件的id
    this.styleObject = null;
    id = function (idstr) { return document.getElementById(idstr); },
    this.CumulativeUploadFiles = new Array(),//本控件累计上传成功的所有文件
    this.inital = function (fileInputId, targetUrl, multiple, autoUpload, fun) {//必须先初始化,文件框对象,上传地址,是否支持多选,自动上传,回调函数
        callbackFun = fun; _targetUrl = targetUrl; context = this; fileControl = id(fileInputId); _multiple = multiple == null || multiple == true ? true : false;
        if (typeof (Worker) == "function") {//ie10+
            controlType = 3;
            if (_multiple) {//多选
                if (fileControl.attributes["multiple"] == null && multiple == true) { fileControl.setAttribute("multiple", "multiple"); };
            }
            if (autoUpload == null || autoUpload == true) { html5UploadInital(fileControl, targetUrl); }
        } else {//ie6-ie9
            controlType = 1;
            if (autoUpload == null || autoUpload == true) { fileControl.onchange = function (evt) { singleUpload(targetUrl); } }
        }
    },
    this.upload = function () {//手动上传入口
        if (controlType == 1) {
            singleUpload(_targetUrl);
        } else if (controlType == 3) { html5Upload(fileControl.files, _targetUrl); }
    },
    this.singleUploadCallback = function (data) {
        var returnobj = eval('(' + data + ')');
        if (returnobj.error != null && returnobj.error != "") { alert(returnobj.error); } else { uploadSuccessCallback(returnobj); }
    },
    this.get = function () {
        var hiddenObj = id(hiddenFileControl);
        if (hiddenObj != null && hiddenObj.getAttribute("files") != null) {
            var fileList = hiddenObj.getAttribute("files").split(";");
            if (_multiple != null && _multiple == false) { if (fileList.length > 0) { return fileList[0]; } return ""; }//区分多还是单
            var returnstr = "[";
            for (var i = 0, j = fileList.length; i < j; i++) {
                if (fileList[i] != "") {
                    returnstr += "{\"img\":\"" + fileList[i] + "\",\"text\":\"\"}";
                }
            }
            returnstr += "]";
            id(hiddenFileControl).value = returnstr.replace(/}{/g, "},{");//方式2
            return id(hiddenFileControl).value;
        };
        return "[]";
    },
    this.set = function (data, cumulative) {//字符串,是否累加(多文件上传时,只有内部赋值时有效)
        //1上传的文件名用分号分隔,分别以files属性保存在文件控件和隐藏控件中,2隐藏控件的value和上传对象的get函数将获取的是格式化好的文件格式
        var hiddenObject = id(hiddenFileControl);
        if (fileControl != null) {
            if (hiddenObject == null) {
                var control = document.createElement("input");
                control.type = "hidden"; control.setAttribute("use", "file"); control.setAttribute("nosubmit", "nosubmit"); control.id = control.name = hiddenFileControl; control.value = "[]";
                fileControl.parentNode.appendChild(control);
                hiddenObject = id(hiddenFileControl);
            }
            if (cumulative == null || cumulative == false)//是否累计(多文件)
            {
                this.remove(null);//移除所有
                if (this.styleObject != null) { this.styleObject.removeAll(); }
                fileControl.setAttribute("files", data);//方式1
                hiddenObject.setAttribute("files", data);
            } else {
                if (fileControl.attributes["files"] == null) {
                    fileControl.setAttribute("files", "");
                    hiddenObject.setAttribute("files", "");
                }
                fileControl.setAttribute("files", fileControl.getAttribute("files") + data + ";");
                hiddenObject.setAttribute("files", hiddenObject.getAttribute("files") + data + ";");
            }
            if (data != null && data != "") {
                this.CumulativeUploadFiles.push(data);//方式3
            }
        };
        this.get();//同步值
    },
    this.remove = function (fileName) {
        if (fileControl.attributes["files"] != null) {
            var filestr = "";
            if (fileName != null && fileName != "") {
                filestr = fileControl.getAttribute("files").replace(fileName + ";", '');
            }
            fileControl.setAttribute("files", filestr);
            id(hiddenFileControl).setAttribute("files", filestr);
        };
        this.get();
    };
    this.count = function () {
        try {
            var f = eval('(' + id(hiddenFileControl).value + ')');
            return f.length;
        } catch (e) { return 0; }
        return 0;
    };
    var singleUpload = function (targetUrl) {
        var formobj = document.getElementsByTagName("form")[0]; var iframeobj = id("FormSubmitToIFrameUpload");
        if (iframeobj == null) {
            var obj = document.createElement("iframe"); obj.id = obj.name = "FormSubmitToIFrameUpload"; obj.style.display = "none"; iframeobj = obj; formobj.appendChild(obj);
        }
        //var oldTarget = formobj.target, oldAction = formobj.action;//保存原始状态
        if (currentUploadName != null && currentUploadName != "") {
            if (targetUrl.toUpperCase().indexOf("CALLBACK") == -1)//添加回调函数
            {
                targetUrl += (targetUrl.indexOf("?") != -1 ? "&callback=" : "?callback=") + currentUploadName + ".singleUploadCallback";
            }
        }
        formobj.setAttribute("method", "POST"), formobj.setAttribute("target", iframeobj.name); formobj.setAttribute("action", targetUrl);
        // formobj.setAttribute("enctype", "multipart/form-data");//在ie6下 enctype的值只能写在form里面,当前这种操作无效
        var att = document.createAttribute("enctype");//兼容所有
        att.value = "multipart/form-data"; formobj.setAttributeNode(att);
        try {
            id("FormSubmitToIFrameUpload").contentWindow.name = "FormSubmitToIFrameUpload";//这句只是解决ie6在新窗口中打开的问题(不能直接使用formobj)
            //window.form1.submit();//另一种方式
            formobj.submit();//ie6支持这种方式
        } catch (e) {
            formobj.removeAttribute("action");
            formobj.removeAttribute("target");
        }
    }
    var flashUpload = function (fileInputId, targetUrl) {
        $("#uploadify").uploadify({
            swf: 'Uploadify/uploadify.swf',
            uploader: targetUrl,
            auto: true,
            buttonText: "图片上传",
            onUploadSuccess: flashUploadSuccess,
            buttonImage: "btn.png",
            height: 31,
            width: 89
        });
    };
    var flashUploadSuccess = function (file, data, response) {//参数:文件对象,服务端输出数据,布尔值
        var returnobj = eval('(' + data + ')'); uploadSuccessCallback(returnobj);
    };
    var html5UploadInital = function (fileObj, target) {
        fileObj.addEventListener("change", function (evt) {
            var files = evt.target.files || evt.dataTransfer.files;//evt.target.files选择文件,evt.dataTransfer.files拖拽文件时获取数据
            html5Upload(files, target);
        });
    };
    var html5Upload = function (files, target) {
        // context.set("", false);
        for (var i = 0, j = files.length; i < j; i++) {
            var file = files[i];
            if (checkFileSuffix(file.name, ".jpg.jpeg.png")) {
                //XMLHttpRequest 2定义的FormData类型。FormData为序列化表单及创建与表单格式相同的数据提供了遍历
                //使用FormData的方便之处体现了不必明确地在XMLHttpRequest对象上设置请求头部。XHR对象能够识别传入的数据类型是FormData的实例，并配置适当的头部信息
                var fileData = new FormData();
                fileData.append(file.name, file);//文件名,数据,可以添加多个键值对
                var x = new XMLHttpRequest(); x.open("POST", target); x.responseType = "text";
                x.onload = function (result) {
                    var returnobj = eval('(' + result.currentTarget.response + ')');
                    if (returnobj.error != null && returnobj.error != "") { alert(returnobj.error); } else {
                        uploadSuccessCallback(returnobj);//输出结果
                    }
                };
                x.send(fileData);
            } else { alert("不合法"); }
        }
    };
    var checkFileSuffix = function (fileName, allowSuffix) {//检查文件扩展名,如果不传入则不限制
        if (allowSuffix != null && allowSuffix != "") {
            if (allowSuffix.toUpperCase().indexOf(fileName.substring(fileName.lastIndexOf("."), fileName.length).toUpperCase()) != -1) { return true; } return false;
        } else { return true; }
    };
    var uploadSuccessCallback = function (data) {//内部回调
        context.set(data.filepath, _multiple);//多文件上传默认为累加
        if (typeof (callbackFun) == "function") { callbackFun(data.filepath, data); }
    };
}
//--样式--
var UploadStyle = function (currentObjectName, showInput) {//当前对象名称,容器id,是否显示输入框(默认为true)
    var imgContainerId, fileId;
    var uploadObject = null, context = null, sigleFilePreviewId = "";
    this.rootPath = "",//默认根路径
    this.initial = function (targetUrl, _isMutiple) {
        uploadObject = new Upload(currentObjectName);
        if (context == null) { context = this; } 
        uploadObject.inital(fileId, targetUrl, (_isMutiple != null ? _isMutiple : false), true, function (filepath, data) {
            if (data.error != null && data.error != "") { alert(data.error); } else { context.set(filepath); }
        });
    },
    this.initialMultipleFile = function (targetUrl) {//初始化多文件上传
        imgContainerId = currentObjectName + "UploadImageContainer"; fileId = currentObjectName + "FileUpload"; context = this;
        if (window.attachEvent) { document.attachEvent("onclick", function (e) { context.changeInputStyle(); }); }
        else { window.addEventListener("click", function (e) { context.changeInputStyle(); }); }
        var html = ""
        html += '<div id=' + imgContainerId + '>';
        html += '</div>';
        html += '<div style="clear: both; position: relative;">';
        html += '  <input id="' + fileId + '" name="' + fileId + '" class="fileinput" type="file" />';
        html += '  <a href="javascript:void(0)" class="uploadbtn">图片上传</a>';
        html += '</div>';
        html += '<script>' + currentObjectName + '.initial("' + targetUrl + '",true);</script>';
        return html;
    },
    this.initialSingleFile = function (targetUrl) {
        sigleFilePreviewId = currentObjectName + "SingleImagePreview"; fileId = currentObjectName + "FileUpload"; context = this;
        var html = '';
        html += '<table class="singleImgbox" style="margin:0px;">';
        html += '    <tr>';
        html += '        <td rowspan="2"><span class="imgitem"><img id="' + sigleFilePreviewId + '" src="/plugin/upload/nopic.png" alt="图片预览" /></span></td>';
        html += '        <td><div style="clear: both; position: relative;"><input class="fileinput" id="' + fileId + '" name="' + fileId + '" type="file"/><a href="javascript:void(0)" class="uploadbtn">图片上传</a></div></td>';
        html += '    </tr>';
        html += '    <tr><td><em>允许上传.jpg .png .gif格式的图片</em></td></tr>';
        html += '</table>';
        html += '<script>' + currentObjectName + '.initial("' + targetUrl + '",false);</script>';
        return html;
    },
    this.singleUploadCallback = function (data) { //临时中转
        var returnobj = eval('(' + data + ')');
        if (uploadObject != null) { uploadObject.singleUploadCallback(data); }
    },
    this.add = function (img) {
        var imgbox = "";
        imgbox += '<span class="imgitem">'
        imgbox += '<a href="javascript:void(0);" onclick="' + currentObjectName + '.remove(\'' + img + '\',this);" class="itemclose">删除</a>';
        imgbox += '<img src="' + img + '" /></span>';
        imgbox += '<span class="imgiteminput" style="' + ((showInput == null || showInput == true) ? "" : "display:none;") + '"><textarea img="' + img + '" cols="20" rows="1" onclick="' + currentObjectName + '.changeInputStyle(this,event);"></textarea><em>图片描述</em></span>';
        var div = document.createElement("div");
        div.className = "imgbox";
        div.innerHTML = imgbox;
        id(imgContainerId).appendChild(div);
    },
    this.get = function () {
        if (imgContainerId == null || id(imgContainerId) == null) {//单文件
            return uploadObject.get();
        } else {//多文件
            var returnstr = "[";
            var textareaList = id(imgContainerId).getElementsByTagName("textarea");
            for (var i = 0, j = textareaList.length; i < j; i++) {
                if (textareaList[i].attributes["img"] != null) {
                    returnstr += "{\"img\":\"" + textareaList[i].attributes["img"].value + "\",\"text\":\"" + textareaList[i].value + "\"}";
                    if (i < j - 1) { returnstr += ","; }
                }
            }
            returnstr += "]";
            return returnstr;
        }
    },
    this.set = function (filepath) {
        var tempFilePath = this.rootPath + filepath;
        if (sigleFilePreviewId == "") { context.add(tempFilePath); uploadObject.set(filepath); } else { document.getElementById(sigleFilePreviewId).src = tempFilePath; uploadObject.set(filepath); }
    },
    this.remove = function (fileName, obj) {
        if (typeof (removeCallback) == "function") { removeCallback(fileName); }
        if (obj != null) { obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode); }
        // obj.parentNode.removeNode(obj.parentNode);//只支持ie
        uploadObject.remove(fileName);
    },
    this.removeAll = function () { id(imgContainerId).innerHTML = ""; },
    this.changeInputStyle = function (obj, evt) {
        var textareaList = document.getElementById(imgContainerId).getElementsByTagName("textarea");
        for (var i = 0; i < textareaList.length; i++) { textareaList[i].parentNode.className = "imgiteminput"; }
        if (evt != null) {
            obj.parentNode.className = "imgiteminput on";
            if (typeof (evt.stopPropagation) != "function") { evt.cancelBubble = true; } else { evt.stopPropagation(); }
        }
    }
}