function ajaxError(param, msg){
   if (param) {
      switch (param) {
         case 'server' :
            $("#server").append(''
               + '<p><b>-- [ Error ] --</b></p>'
               + '<p>Trouble has occurred on the server.</p>'
               + '<p>Error Code : '+msg+'</p>'
            );
            $("#server").slideDown('fast');
         break;
         default :
            $("#"+param).append(
               '<img src="/static/common/img/icon_floating_arrow.png" class="arrow">'
            );
            var errAry = msg.split(",");
            for (var i = 0; i < errAry.length; i++) {
               $("#"+param).append('<p>'+errAry[i]+'</p>');
            }
            $("#"+param).slideDown('fast');
         break;
      }  
   } else {
      $("#server").append(''
         + '<p><b>-- [ Error ] --</b></p>'
         + '<p>Something is wrong.</p>'
      );
      $("#server").slideDown('fast');
   }
   return false;
}

function ajaxFormSuccess(res, status, options){

   function successDefault(result) {
      var page = new String();
      if (result.file.page != void 0) { page = '/' + result.file.page; }
      location.href = '/file/' + result.file.id + page;
   } 

   displayModal(false);
   if (res.status == "success"){
      switch (res.file.page) {
         case 'show' :
            if (res.file.count == void 0) {
               successDefault(res);
            }
            else {
               switch (res.file.dec) {
                  case 'tag' :
                     showTagAjax(res.file);
                  break;
                  case 'comment' :
                     showCommentAjax(res.file);
                  break;
               }
            }
         break;
         case 'auth' :
            if (res.file.count == void 0) {
               successDefault(res);
            }
            else {
               authPrivateAjax(res.file);
            }
         break;
         default :
            successDefault(res);
         break;
      }
      return false;
   }
   else {
      if (status != "success") {
         ajaxError('server', 'Server Error');
         return false;
      }
      else if (!res.errors) {
         ajaxError('server', 'Server Error');
         return false;
      } else {
         for (var i = 0; i < res.errors.length; i++) {
            ajaxError(res.errors[i]['param'], res.errors[i]['msg']);
         }
         return false;
      }
      ajaxError();
   }
   return false;
}

function ajaxFormError(res, status, options){
   displayModal(false);
   var error = res.status+' ( '+options+' ) ';
   ajaxError('server', error);
   return false;
}

function ajaxFormValidate(res, status, options){
   $(".form_error_input").css('display', 'none');
   $(".form_error_input").html('');
   $(".form_error_server").css('display', 'none');
   $(".form_error_server").html('');
   return true;
}
function ajaxFormValidateProgress(res, status, options){
   $(".form_error_input").css('display', 'none');
   $(".form_error_input").html('');
   $(".form_error_server").css('display', 'none');
   $(".form_error_server").html('');
   var url ='/file/progress-modal';
   setModal(url, 320, 180, true);
   return true;
}
function ajaxFormProgress(event, position, total, percent){
   if (percent >= 100) {
      $(".progress .status .middle").fadeOut('fast');
      setTimeout(function(){
         $(".progress .status .complate").fadeIn('fast');
      }, 1000);
   } else {
      progressBar(percent);
   } 
   return true;
}

function ajaxFormMain(id, page){
   if ($('form#'+id).size() < 1){return false;};

   var url = new String();
   if ($('form#'+id).data('num') == void 0) {
      url = '/ajax/file/' + page;
   } else {
      url = '/ajax/file/' + $('form#'+id).data('num') + '/' + page;
   }

   switch (id) {
      case 'upload' :
      case 'file'   :
         var options = {
            url            : url,
            beforeSend     : ajaxFormValidateProgress,
            uploadProgress : ajaxFormProgress,
            success        : ajaxFormSuccess,
            error          : ajaxFormError
         }
      break;
      default :
         var options = {
            url          : url,
            beforeSend   : ajaxFormValidate,
            success      : ajaxFormSuccess,
            error        : ajaxFormError
         }
      break; 
   }

   $('form#'+id).ajaxForm(options);
}



function formFileCheckView(data,target) {
   if ($('#form_file').size() < 1){return false;}
   if (data == void 0){return false;}

   var view = new String();

   function imgSelect(select) {
      return '<img src="/static/common/img/form_base_file_'+select+'.png">';
   }

   if (data == 'loading') {
      view = ''
         + '<table><tr class="loading"><td>'
            + '<img src="/static/common/img/icon_loading40.gif">'
            + '<span>Now Loading...</span>'
         + '</td></tr></table>';
   }
   else if (data == 'click') {
      view = '<div>'+imgSelect("click")+'</div>';
   }
   else if (data == 'error') {
      view = '<div>'+imgSelect("error")+'</div>';
   }
   else if (data == 'not_supported') {
      view = '<div>'+imgSelect("not_supported")+'</div>';
   }
   else {
      switch (target) {
         case 'file' :
            view = ''
               + '<table>'
                  + '<tr class="file"><th>'
                     + '<img src="/static/common/img/icon_file128.png">'
                  + '</th></tr>'
                  + '<tr class="file"><td>'
                     + '<p>'+data.file_name+'</p>'
                     + '<p>SIZE : '+data.file_size+'</p>'
                  + '</td></tr>'
               + '</table>';
         break;
         case 'thumbnail' :
            view = ''
               + '<table><tr class="thumbnail"><td>'
                  + '<img src="'+data+'">'
               + '</td></tr></table>'
         break;
      }
   }

   return view;
}

function formFileCheck(target) {
  if ($('#form_file').size() < 1){return false;}

  var view = new String();
   
  if(!window.FileReader){
      $('#form_file').hide();
      view = formFileCheckView('not_supported', target);
      $('#form_file_view').html(view);
      return false;
   }
   else {
      var util = {
         stop: function(e) {
            e.preventDefault();
            e.stopPropagation();
         }
      }
      var setFile = function(e, dec) {
         view = formFileCheckView('loading', target);
         $('#form_file_view').html(view);

         var files = new Object();
         switch (dec) {
            case 'drop' :
               files = e.originalEvent.dataTransfer.files;
            break;
            case 'change' :
               files = document.getElementById('form_file').files;
            break;
         }
         if (files != void 0  && files.length != 0) {
            var file = files[0];
            var name = checkFileName(file.name, $('#form_file').data('name'));
            var ext  = checkFileExt(file.name, $('#form_file').data('exts'));
            var size = checkFileSize(file.size, $('#form_file').data('size'));

            if (name && ext && size) {
               switch (target) {
                  case 'file' :
                     var data = new Object();
                     data.file_name = name;
                     data.file_size = size;

                     view = formFileCheckView(data, target);
                     $('#form_file_view').html(view); 
                  break;
                  case 'thumbnail' :
                     var reader = new FileReader();

                     reader.onerror = function (evt) {
                        view = formFileCheckView('error', target);
                        $('#form_file_view').html(view);
                     }
                     reader.onload = function (evt) {
                        view = formFileCheckView(evt.target.result, target)
                        $('#form_file_view').html(view); 
                     }
                     reader.readAsDataURL(file);
                  break;
               }
               return false;
            }
            else {
               $('#form_file').clearFields();
               view = formFileCheckView('error', target)
               $('#form_file_view').html(view);
               return false;
            }
         }
         view = formFileCheckView('click', target)
         $('#form_file_view').html(view);
         return false;
      }

      $('#form_file').on({
         'dragover' : util.stop,
         'drop' : function(e) {
            util.stop(e);
            setFile(e, 'drop');
         },
         'change' : function(e) {
            util.stop(e);
            setFile(e, 'change');
         }
      });
      return false;
   }
}

$(document).ready(function(){
   if ($('form#upload').size() > 0) {
      formFileCheck('file');
      ajaxFormMain('upload', 'upload');
   }

   if ($('form#show_tag_create').size() > 0) {
      ajaxFormMain('show_tag_create', 'show_tag_create');
   }
   if ($('form#show_report').size() > 0) {
      ajaxFormMain('show_report', 'show_report');
   }
   if ($('form#show_comment_create').size() > 0) {
      ajaxFormMain('show_comment_create', 'show_comment_create');
   }


   if ($('form#page_title').size() > 0) {
      ajaxFormMain('page_title', 'page_title');
   }
   if ($('form#page_anonymous').size() > 0) {
      ajaxFormMain('page_anonymous', 'page_anonymous');
   }
   if ($('form#page_locks').size() > 0) {
      ajaxFormMain('page_locks', 'page_locks');
   }
   if ($('form#page_thumbnail').size() > 0) {
      ajaxFormMain('page_thumbnail', 'page_thumbnail');
      formFileCheck('thumbnail');
   }
   if ($('form#page_description').size() > 0) {
      ajaxFormMain('page_description', 'page_description');
   }

   if ($('form#file').size() > 0) {
      formFileCheck('file');
      ajaxFormMain('file', 'file');
   }

   if ($('form#auth_public').size() > 0) {
      ajaxFormMain('auth_public', 'auth_public');
   }
   if ($('form#auth_select_myself').size() > 0) {
      ajaxFormMain('auth_select_myself', 'auth_private_control');
   }
   if ($('form#auth_select_user').size() > 0) {
      ajaxFormMain('auth_select_user', 'auth_private_control');
   }
   if ($('form#auth_select_referer').size() > 0) {
      ajaxFormMain('auth_select_referer', 'auth_private_control');
   }
   if ($('form#auth_user_create_one').size() > 0) {
      ajaxFormMain('auth_user_create_one', 'auth_user_create_one');
   }
   if ($('form#auth_user_delete').size() > 0) {
      ajaxFormMain('auth_user_delete', 'auth_user_delete');
   }
   if ($('form#auth_referer_create').size() > 0) {
      ajaxFormMain('auth_referer_create', 'auth_referer_create');
   }
   if ($('form#auth_referer_delete').size() > 0) {
      ajaxFormMain('auth_referer_delete', 'auth_referer_delete');
   }

   return false;
});
