//SWFUpload.prototype.debug = function(str){console.log(str)}

/* This is an example of how to cancel all the files queued up.  It's made somewhat generic.  Just pass your SWFUpload
object in to this method and it loops through cancelling the uploads. */
function cancelQueue(instance) {
    //document.getElementById(instance.customSettings.cancelButtonId).disabled = true;
    instance.stopUpload();
    var stats;

    do {
        stats = instance.getStats();
        instance.cancelUpload();
    } while (stats.files_queued !== 0);

}

function fileQueueError(fileObj, error_code, message) {
    try {
        var error_name = "";
        switch(error_code) {
            case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
            //error_name = "You have attempted to queue too many files.";
            error_name = "ファイルが多すぎます。";
            break;
        }

        if (error_name !== "") {
            alert(error_name);
            return;
        }

        switch(error_code) {
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
            image_name = "zerobyte.gif";
            break;
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
            image_name = "toobig.gif";
            break;
            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
            image_name = "invalid.gif";
            break;
            default:
            //alert(message);
            image_name = "error.gif";
            break;
        }
        image_name = "create/upload_error.gif";

        AddImage("/images/" + image_name);

    } catch (ex) { this.debug(ex); }

}

function fileDialogStart(num_files_queued) {
    $("#SWFUploadFileListingFiles").slideDown('fast')
}

function fileDialogComplete(num_files_queued) {
    try {
        if (num_files_queued > 0) {
            $('#next_step').attr('src', $('#next_step').attr('src').replace('_active','_inactive'))
            $('#photo_ids')[0].onsubmit = function(){
                alert('アップロード完了までお待ちください');
                return false;
            };

            if (this.getStats().files_queued > 0) {
                //var progress = new FileProgress(fileObj,  this.customSettings.upload_target);
                var stats = this.getStats();
                this.total_queued += stats.num_files_queued;
            }
            var listingfiles = $('#thumbnails')[0];
            var span = document.createElement('span');
            listingfiles.insertBefore(span, (listingfiles.firstChild || null));
            this.startUpload();
        }
    } catch (ex) {
        this.debug(ex);
    }
}

function fileQueued(file) {
    var listingfiles = $('#thumbnails')[0];

    var div = document.createElement("div");
    div.id = file.id;
    div.className = "SWFUploadFileItem";
    listingfiles.insertBefore(div, (listingfiles.getElementsByTagName('span')[0] || null));
}

function cancelFile(id) {
}


function uploadProgress(file, bytesLoaded) {
    try {
        var percent = Math.ceil((bytesLoaded / file.size) * 100)
        var progress = new FileProgress(file,  this.customSettings.upload_target);
        progress.SetProgress(percent);
        if (percent === 100) {
            progress.SetStatus(file.name +" のサムネイルを作成中です");
            progress.ToggleCancel(false);
            progress.ToggleCancel(true, this, file.id);
        } else {
            progress.SetStatus(file.name + " をアップロード中です");
            progress.ToggleCancel(true, this, file.id);
        }
    } catch (ex) { this.debug(ex); }
}

function uploadSuccess(file, server_data) {
    try {
        if (server_data.match(/\d+,http:\/\/.+\.jpg/)) {
            var data = server_data.split(',');
            var photo_id = data[0];
            $('#photo_id')[0].value += "," + photo_id;
            var thumb_src = data[1];
            var progress = new FileProgress(file,  this.customSettings.upload_target);

            progress.SetComplete(photo_id,thumb_src);
            progress.SetStatus("サムネイルの作成が完了しました");
            progress.ToggleCancel(false);
        } else {
            var progress = new FileProgress(file,  this.customSettings.upload_target);
            progress.SetComplete(photo_id,"/images/create/upload_error.gif");
            progress.SetStatus("アップロードに失敗しました。");
            progress.ToggleCancel(false);
        }

    } catch (ex) { this.debug(ex); }
}

function uploadComplete(fileObj) {
    function getPageScroll() {
      var xScroll, yScroll;
      if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
      } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;	
      }
      return new Array(xScroll,yScroll) 
    }
    try {
        /*  I want the next upload to continue automatically so I'll call startUpload here */
        if (this.getStats().files_queued > 0) {
            this.startUpload();
        } else {
            setTimeout(function(){
                if (getPageScroll()[1] > 400 ) {
                    slowdownScroll();
                }
            },1000)

            var progress = new FileProgress(fileObj,  this.customSettings.upload_target);
            progress.SetStatus(this.customSettings.upload_complete_message);
            progress.ToggleCancel(false);

            if ($(".upload_sound input").attr('checked')) {
                sound('notice_loop');
            }

            var action = this.customSettings.form_action;
            $('#next_step').attr('src', $('#next_step').attr('src').replace('_inactive','_active'))
            $('#photo_ids')[0].onsubmit = function(){
                var frm = this;
                if (frm.photo_id.value.length < 2){ return false; }
                if (frm.posted_by && frm.posted_by.value.length < 1) {
                    alert('名前を入力してください');
                    return false;
                }
                if ((typeof album_owner != 'undefined' && !album_owner) && frm.password && frm.password.value.length < 1) {
                    if(!confirm('パスワードが空の場合、自分で写真を削除することができません。よろしいですか？')) {
                        return false;
                    }
                }
                frm.action = action;
                frm.method = "post";
                frm.submit();
                return false;
            }


            $(".step_area").fadeOut('slow',function(){
                $(".step_area_complete").fadeIn('slow')
            })

            // nandakana-
            var settings2 = swfu.settings;
            if (SWFUpload.movieCount == 1 && settings2.custom_settings.form_action == "/album/upload") {
                settings2.button_placeholder_id = "add_add";
                settings2.button_image_url = "/images/create/btn_more.gif";
                new SWFUpload(settings2);
            }
        }
    } catch (ex) { this.debug(ex); }
}

function AddThumbnail(fileObj, src, fn) {
    var li = document.getElementById(fileObj.id);
    var thumb = document.createElement('img');
    thumb.style.display="none";
    thumb.onload = function () { $(thumb).fadeIn(2000, fn); };
    thumb.src = src;
    li.insertBefore(thumb, (li.firstChild || null));
    li.className = "SWFUploadFileItem uploadCompleted";
}

function uploadError(fileObj, error_code, message) {
    var image_name =  "create/upload_error.gif";
    try {
        switch(error_code) {
            case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                try {
                    var progress = new FileProgress(fileObj,  this.customSettings.upload_target);
                    progress.SetCancelled();
                    progress.SetStatus("Stopped");
                    progress.ToggleCancel(true, this, fileObj.id);
                } catch (ex) { this.debug(ex); }
            case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                //image_name = "uploadlimit.gif";
                AddImage("/images/" + image_name);
                break;
            case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                $('#'+fileObj.id).fadeOut('slow');
                break;
            default:
                //alert(message);
                AddImage("/images/" + image_name);
            break;
        }

    } catch (ex) { this.debug(ex); }

}


/* ******************************************
 * FileProgress Object
 * Control object for displaying file info
 * ****************************************** */

function FileProgress(fileObj, target_id) {
  this.fileObj = fileObj;
  this.file_progress_id = "divFileProgress";

  this.fileProgressWrapper = $('#'+this.file_progress_id)[0];//document.getElementById(this.file_progress_id);
  if (!this.fileProgressWrapper) {

      this.fileProgressWrapper = document.createElement("div");
      this.fileProgressWrapper.className = "progressWrapper";
      this.fileProgressWrapper.id = this.file_progress_id;

      //this.fileProgressLeft = document.createElement("div");
      //this.fileProgressLeft.className = "left";

      //this.fileProgressCount = document.createElement('div');
      //this.fileProgressCount.className = "progressCount";
      //this.fileProgressCount.id = "count";
      //this.fileProgressCount.innerHTML = "1/10";

      //this.fileProgressLeft.appendChild(this.fileProgressCount);


      //this.fileProgressRight = document.createElement("div");
      //this.fileProgressRight.className = "right";

      this.fileProgressStatus = document.createElement('div');
      this.fileProgressStatus.className = "progressStatus";

      this.fileProgressBar = document.createElement('div');
      this.fileProgressBar.className = "fileProgressBar";

      this.fileProgressStop = document.createElement('div');
      this.fileProgressStop.className = "fileProgressStop";
      this.fileProgressStop.innerHTML = "<img src='/images/common/upload_cancel.gif'>";
      this.fileProgressStop.id = "cancel";
      this.fileProgressStop.onclick = function(){
          cancelQueue(SWFUpload.instances['SWFUpload_'+(SWFUpload.movieCount-1)]);
      }

    //this.fileProgressRight.appendChild(this.fileProgressStop);
    //this.fileProgressRight.appendChild(this.fileProgressStatus);
    //this.fileProgressRight.appendChild(this.fileProgressBar);

    //this.fileProgressWrapper.appendChild(this.fileProgressLeft);
    //this.fileProgressWrapper.appendChild(this.fileProgressRight);

    this.fileProgressWrapper.appendChild(this.fileProgressStop);
    this.fileProgressWrapper.appendChild(this.fileProgressStatus);
    this.fileProgressWrapper.appendChild(this.fileProgressBar);

    document.getElementById(target_id).appendChild(this.fileProgressWrapper);
  } else {
    this.fileProgressStatus = $('.progressStatus')[0];
    this.fileProgressBar = $('.fileProgressBar')[0];
  }

  this.fileProgressElement = $("#"+fileObj.id)[0].getElementsByTagName('div')[0];
  if (!this.fileProgressElement){
      this.fileProgressElement = document.createElement("div");
      this.fileProgressElement.className = "progressContainer";

      var progressCancel = document.createElement("a");
      progressCancel.className = "progressCancel";
      progressCancel.href = "#";
      progressCancel.style.visibility = "hidden";
      progressCancel.appendChild(document.createTextNode(" "));

      var progressText = document.createElement("div");
      progressText.className = "progressName";
      progressText.appendChild(document.createTextNode(fileObj.name));

      var progressBar = document.createElement("div");
      progressBar.className = "progressBarInProgress";


      this.fileProgressElement.appendChild(progressCancel);
      this.fileProgressElement.appendChild(progressText);
      this.fileProgressElement.appendChild(progressBar);

      $("#"+fileObj.id)[0].appendChild(this.fileProgressElement);

  } else {
      var hoge = this.fileProgressElement = $("#"+fileObj.id)[0].getElementsByTagName('div')[0];
      this.fileProgressElement.childNodes[1].firstChild.nodeValue = fileObj.name;
  }

  this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.SetProgress = function(percentage) {
    this.fileProgressBar.style.width = percentage + "%";
}
FileProgress.prototype.SetComplete = function(photo_id, thumb_src) {
    var fileprogress = this;
    AddThumbnail(this.fileObj, thumb_src, function(){
        var span = document.createElement('span');
        $(span).html('<img src="/images/common/delete_photo.gif" />');
        $(span).click(function(){
            deletePhoto(photo_id);
            $(this.parentNode).fadeOut('slow');
            $(this).hide();
        });
        fileprogress.fileProgressElement.parentNode.appendChild(span);
    });
}

function deletePhoto(del_id){
    var photo_ids = $('#photo_id').attr('value').split(",");
    var new_value = "";
    for (var i in photo_ids) {
        var photo_id = photo_ids[i];
        if (photo_id.match(/^\d+$/) && photo_id != del_id) {
            new_value += "," + photo_id;
        }
    }
    $('#photo_id').attr('value', new_value);
}

FileProgress.prototype.SetError = function() {
    this.fileProgressElement.className = "progressContainer red";
    this.fileProgressElement.childNodes[3].className = "progressBarError";
    this.fileProgressElement.childNodes[3].style.width = "";
}
FileProgress.prototype.SetCancelled = function() {
    //this.fileProgressElement.className = "progressContainer";
    //this.fileProgressElement.childNodes[3].className = "progressBarError";
    //this.fileProgressElement.childNodes[3].style.width = "";
}
FileProgress.prototype.SetStatus = function(status) {
  this.fileProgressStatus.innerHTML = status;
}

FileProgress.prototype.ToggleCancel = function(show, upload_obj, file_id) {
    this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
    if (upload_obj) {
        this.fileProgressElement.childNodes[0].onclick = function() { upload_obj.cancelUpload(); return false; };
    }
}

function AddImage(src) {
    var new_img = new Image();
    new_img.style.margin = "5px";

    $("#thumbnails")[0].appendChild(new_img);
    new_img.style.display = 'none';
    new_img.onload = function() { $(new_img).fadeIn(2000); };
    new_img.src = src;
}
