function delAttach(id) {
    //var curattlength = $('attachbody').childNodes.length;
    $('attachbody').removeChild($('attach_' + id).parentNode.parentNode);
    $('attachbody').innerHTML == '' && addAttach();
	countNum2Upload();
    if (num2upload > 0 && (!$("attach_" + (aid-1)) || $("attach_" + (aid-1)).value != ""))
	    addAttach();
	if ($('localimgpreview_' + id + '_menu') )
		document.body.removeChild($('localimgpreview_' + id + '_menu'));
}

function addAttach() {
    if ($('attachbody').childNodes.length + ($('attachuploaded') ? $('attachuploaded').childNodes.length : 0) > maxattachments - 1){
		countNum2Upload();
		//num2upload++;
		return;
	}

    newnode = $('attachbodyhidden').firstChild.cloneNode(true);
    var id = aid;
    var tags;
    tags = findtags(newnode, 'input');
    for(i in tags) {
        if(tags[i].name == 'postfile') {
            tags[i].id = 'attach_' + id;
            tags[i].onchange = function() {
	            insertAttach(id);
            };
            tags[i].unselectable = 'on';
        }
        if(tags[i].name == 'localid') {
            tags[i].value = id;
        }
    }
    tags = findtags(newnode, 'span');
    for(i in tags) {
        if(tags[i].id == 'localfile[]') {
            tags[i].id = 'localfile_' + id;
        }
    }
	if (caninsertalbum) {
		tags = findtags(newnode, 'select');
		for(i in tags) {
			if(tags[i].name == 'albums') {
				tags[i].id = 'albums' + id;
			}
		}
	}
    aid++;
    $('attachbody').appendChild(newnode);
	countNum2Upload();
}

function insertAttach(id) {
    var localimgpreview = '';
    var path = $('attach_' + id).value;
    var extensions = exts;
    var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
    var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
    var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);

    if(path == '') 
        return;

    if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
        alert('对不起，不支持上传此类扩展名的附件。');
        return;
    }
    attachexts[id] = is_ie && in_array(ext, ['gif', 'jpg', 'jpeg', 'png', 'bmp']) ? 2 : 1;

    var err = false;
    if(attachexts[id] == 2) {
        $('img_hidden').alt = id;
        try {
	        $('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = 'image';
        } catch (e) {
			err = true;
		}
        try {
            $('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = $('attach_' + id).value;
        } catch (e) {
			alert('无效的图片文件。');
			delAttach(id);
			err = true;		
            return;
        }
        var wh = {'w' : $('img_hidden').offsetWidth, 'h' : $('img_hidden').offsetHeight};
        var aid = $('img_hidden').alt;
        if(wh['w'] >= thumbwidth || wh['h'] >= thumbheight) {
            wh = thumbImg(wh['w'], wh['h']);
        }
        attachwh[id] = wh;
        $('img_hidden').style.width = wh['w']
        $('img_hidden').style.height = wh['h'];
        try {
	        $('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = 'scale';
        } catch (e) {}
        if (err == true) {
	        $('img_hidden').src = $('attach_' + id).value;
        }
        div = document.createElement('div');
        div.id = 'localimgpreview_' + id + '_menu';
        div.style.display = 'none';
        div.style.marginLeft = '20px';
        div.className = 'popupmenu_popup';
        document.body.appendChild(div);
        div.innerHTML = '<img style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\'' + $('attach_' + id).value.replace(')','%29').replace('(','%28') +'\');width:'+wh['w']+';height:'+wh['h']+'" src=\'images/common/none.gif\' border="0" aid="attach_'+ aid +'" alt="" /><br /><br />';
    }
    var isimg = in_array(ext, ['gif', 'jpg', 'jpeg', 'png', 'bmp']) ? 2 : 1;
    if (caninsertalbum) {
		if(isimg == 2) {
			$('albums' + id).style.display='';
			$('albums' + id).disabled = tempaccounts;
		}
    }
    $('localfile_' + id).innerHTML = '<a href="###delAttach" onclick="delAttach(' + id + ')">[删除]</a> <a href="###insertAttach" title="点击这里将本附件插入帖子内容中当前光标的位置" onclick="insertAttachtext(' + id + ', ' + err + ');return false;">[插入]</a> ' +
    (attachexts[id] == 2 ? '<span id="localimgpreview_' + id + '" onmouseover="showMenu(this.id, 0, 0, 1, 0)"> <span class="smalltxt">[' + id + ']</span> <a href="###attachment" onclick="insertAttachtext(' + id + ', ' + err + ');return false;">' + localfile + '</a></span>' : '<span class="smalltxt">[' + id + ']</span> ' + localfile);
    $('attach_' + id).style.display = 'none';
    /*if(isimg == 2)
        insertAttachtext(id, err);*/
    addAttach();
}

function insertAttachtext(id, iserr) {
    if(!attachexts[id]) {
        return;
    }
    if(attachexts[id] == 2) {
        bbinsert && wysiwyg && iserr == false ? insertText($('localimgpreview_' + id + '_menu').innerHTML, false) : AddText('[localimg=' + attachwh[id]['w'] + ',' + attachwh[id]['h'] + ']' + id + '[/localimg]\r\n\r\n');
    } else {
        bbinsert && wysiwyg ? insertText('[local]' + id + '[/local]', false) : AddText('[local]' + id + '[/local]');
    }
}

function thumbImg(w, h) {
    var x_ratio = thumbwidth / w;
    var y_ratio = thumbheight / h;
    var wh = new Array();

    if((x_ratio * h) < thumbheight) {
        wh['h'] = Math.ceil(x_ratio * h);
        wh['w'] = thumbwidth;
    } else {
        wh['w'] = Math.ceil(y_ratio * w);
        wh['h'] = thumbheight;
    }
    return wh;
}

function addAttachUploaded(attaches) {
	var num = 1;
	for (i in attaches){
		if (num  > num2upload)
			break;
		addSingleAttachUploaded(attaches[i]);
		num++;
	}
	$('attachuploadednote').style.display = 'none';
	if (attaches.length >= num2upload && num2upload > 0)
		delAttach(aid - 1) ;
	countNum2Upload();
}

function countNum2Upload(){
	var empty = ($('attach_' + (aid-1)) && $('attach_' + (aid-1)).value=='') ? 1 : 0
	var locallength = $('attachbody').childNodes.length - empty;
	var uploadedlength = $('attachuploaded').childNodes.length;
	num2upload = maxattachments - locallength - uploadedlength;
	if (num2upload == 0 && $('batchupload'))
		$('batchupload').style.display = 'none';
	if (num2upload > 0)
		$('batchupload').style.display = '';
	if (num2upload < 0)
		num2upload = 0;
	$('num2upload').innerHTML = num2upload;
	$('num2upload2').innerHTML = num2upload;

	if (attaches.length > num2upload)
		$("maxattachnote").style.display="";
}

function addSingleAttachUploaded(attach){
	var newnode = $('attachuploadedhidden').firstChild.cloneNode(true);
    var id = attach.aid;
	var path = attach.attachment;
    var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
	var isimg = in_array(ext, ['gif', 'jpg', 'jpeg', 'png', 'bmp']) ? 2 : 1;

    var tags;
    tags = findtags(newnode, 'input');
    for(i in tags) {
        if(tags[i].name == 'attachid') {
            tags[i].value = id;
        }
    }
    tags = findtags(newnode, 'span');
    for(i in tags) {
        if(tags[i].id == 'attachfile[]') {
            tags[i].id = 'attachfile_' + id;
        }
    }
	if (caninsertalbum) {
		tags = findtags(newnode, 'select');
		for(i in tags) {
			if(tags[i].name == 'albums') {
				tags[i].id = 'albums' + id;
			}
		}
	}
    auid++;
    $('attachuploaded').appendChild(newnode);
	var err = false;
	$('attachfile_' + id).innerHTML = '<a href="###delAttach" onclick="delUploadedAttach(' + id + ')">[删除]</a> <a href="###insertAttach" title="点击这里将本附件插入帖子内容中当前光标的位置" onclick="insertUploadedAttach' + (isimg == 2 ? 'img' : '') + 'Tag(' + id + ');return false;">[插入]</a> ' +
    (isimg == 2 ? '<span id="attachimgpreview_' + id + '" onmouseover="showMenu(this.id, 0, 0, 1, 0);$(\'attachimgpreview_' + id + '_menu\').style.width=$(\'attachimgpreview_' + id + '_image\').width + \'px\';"> <span class="smalltxt">[' + id + ']</span> <a href="###attachment" onclick="insertUploadedAttachimgTag(' + id + ');return false;">' + attach.attachment + '</a></span>' 
	+ '<div class="popupmenu_popup" id="attachimgpreview_' + id + '_menu" style="display: none;max-width:420px;text-align:center"><img style="max-width: 400px; max-height: 400px" id="attachimgpreview_' + id + '_image" src="attachment.aspx?attachmentid=' + id + '" onerror="this.onerror=null;this.src=\'attachment.aspx?attachmentid=' + id + '\';" /></div>'	
	: '<span class="smalltxt">[' + id + ']</span> ' + attach.attachment);



}

function insertUploadedAttachTag(aid) {
	if (bbinsert && wysiwyg) {
		insertText('[attach]' + aid + '[/attach]', false);
	} else {
		AddText('[attach]' + aid + '[/attach]');
	}
}
function insertUploadedAttachimgTag(aid) {
	if (bbinsert && wysiwyg) {
		var attachimgurl = 'attachment.aspx?attachmentid=' + aid;
		insertText('<img src="' + attachimgurl + '" border="0" aid="attachimg_' + aid + '" alt="" /><br /><br />', false);
	} else {
		AddText('[attachimg]' + aid + '[/attachimg]\r\n\r\n');
	}
}

function delUploadedAttach(id) {
    $('attachuploaded').removeChild($('attachfile_' + id).parentNode.parentNode);
	countNum2Upload();
    if (num2upload > 0 && (!$("attach_" + (aid-1)) || $("attach_" + (aid-1)).value != ""))
	    addAttach();
	if ($('attachimgpreview_' + id + '_menu') )
		document.body.removeChild($('attachimgpreview_' + id + '_menu'));
}
