var uploadedCount = new Array();

function addAjaxUploadForm(uploadButton, uploadedFileList, textareaId, uploadItemCount)
{
    var button = $(uploadButton);
    uploadedCount[textareaId] = uploadItemCount;

    new AjaxUpload(button, {
        action: 'Upload_Post.jsp',
        name: 'userFile',
        data: { },

        onSubmit : function(file, ext)
        {
            // TODO: image only
            if (!ext || /^(jpg|jpeg|png|bmp|gif)$/.test(ext) == false)
            {
                alert("지정한 이미지 파일 형식(JPG, BMP, PNG, GIF)만 업로드 가능합니다.");
                return false;
            }

            // TODO: 업로드 수 제한 (4개)
            if(uploadedCount[textareaId] >= 4)
            {
                alert("한번에 최대 4개의 파일만 업로드하실 수 있습니다.");
                return false;
            }

            // change button text, when user selects file
            button.text('업로드 중입니다');

            // If you want to allow uploading only 1 file at time,
            // you can disable upload button
            this.disable();

            // Uploading -> Uploading. -> Uploading...
            interval = window.setInterval(function()
                       {
                           var text = button.text();
                           if (text.length < 11)
                           {
                               button.text(text + '.');
                           }
                           else
                           {
                               button.text('업로드 중입니다');
                           }
                       }, 200);
        },
        onComplete: function(file, response)
        {
            // alert("완료:" + response);
            
            button.text('첨부파일 추가');

            window.clearInterval(interval);

            // enable upload button
            this.enable();

            // 성공
            if(response.indexOf("UPLOAD_SUCCESS") > 0)
            {
                // get returned linkTag code
                codePosition = response.indexOf("TAG=");
                linkTag = response.substr(codePosition+4, 32);

                // add file to the list
                fileAddTag = "<div id=\"attachmentItem_" + linkTag + "\" class=\"uploadedFileItem\">" +
                             "<input type=\"hidden\" name=\"attachmentItem\" value=\"" + linkTag + "\" />" + file + " " +
                             "<a href=\"javascript:EmbedUploaded('" + linkTag + "', '" + textareaId + "');\" title=\"글 내용에 첨부하기\"><img src=\"" + siteConfig['staticStyleURL'] + "/" + bbsConfig['skinName'] + "/button_upload_embed.jpg\" alt=\"글 내용에 첨부하기\" border=\"0\" style=\"vertical-align:middle; padding-bottom:2px;\" /></a> " +
                             "<a href=\"javascript:DeleteUploaded('" + linkTag + "', '" + textareaId + "');\" title=\"첨부파일 삭제하기\"><img src=\"" + siteConfig['staticStyleURL'] + "/" + bbsConfig['skinName'] + "/button_upload_delete.jpg\" alt=\"첨부파일 삭제하기\" border=\"0\" style=\"vertical-align:middle; padding-bottom:2px;\" /></a>" +
                             "</div>";

                uploadedCount[textareaId] += 1;
                $(uploadedFileList).append(fileAddTag);
                EmbedUploaded(linkTag, textareaId);
            }
            else if(response.indexOf("TYPE_MISMATCH") > 0)
            {
                // 큰 실패
                alert("지정한 이미지 파일 형식(JPG, BMP, PNG, GIF)만 업로드 가능합니다.");
            }
            else
            {
                // 실패
                alert("업로드 처리 도중 문제가 발생하였습니다.\n첨부한 파일이 너무 크거나, 서버 설정으로 인해 업로드 공간이 제한되었습니다.");
            }
        }
    });
}

function DeleteUploaded(linkTag, textareaId)
{
    var confirmMsg = confirm("이 첨부파일을 삭제하시겠습니까?");
    if(!confirmMsg)
    {
        return;
    }

    targetStr = siteConfig['staticImageCDNURL'] + "?linkTag=" + linkTag;

    if(tinyMCE.get(textareaId).getContent().indexOf(targetStr, 0) >= 0)
    {
        alert("파일 삭제 전, HTML 편집기에 삽입된 첨부파일 관련 내용을 모두 제거하십시오.");
        return;
    }

    // just remove this from DOM object from now
    $("#attachmentItem_" + linkTag).remove();
    uploadedCount[textareaId] -= 1;
}

function EmbedUploaded(linkTag, textareaId)
{
    // TODO: image only
    tinyMCE.get(textareaId).setContent(tinyMCE.get(textareaId).getContent() + 
        "<a href=\"" + siteConfig['staticImageCDNURL'] + "?linkTag=" + linkTag + "\" rel=\"prettyPhoto\"><img src=\"" +
        siteConfig['staticImageCDNURL'] + "?linkTag=" + linkTag + "&isDownload=true\" border=\"0\" alt=\"\" /></a>");
}

