$(document).ready(function(){

  /* insertion */
	$('.form').submit(function(e){
		e.preventDefault();
                var id = $(this).attr('id');
		$(this).find('.btn-submit').attr('disabled', 'disabled');
		var url = $(this).attr('cluster-url');
                if( typeof CKEDITOR !== "undefined" )
                {
                    for (var i in CKEDITOR.instances) {
                      CKEDITOR.instances[i].updateElement();
                  };
                }
		var data = $(this).serializeArray();
		var current = $(this);

                var warning = $(this).attr('cluster-warning');
                if (typeof warning !== typeof undefined && warning !== false) {

                }
                else 
                {
                  warning  = 'Please wait while we process your input....';
                }

		var redirect = $(this).attr('cluster-redirect');
                var after = $(this).attr('cluster-after');

		$(current).find('.error-main').html('<div class="alert alert-warning">' + warning + '</div>');
                window.location.hash = '#' + id;
                $.post(url, {data:data}, function(res){
                    $(current).find('.btn-submit').removeAttr('disabled');
                           console.log(res);
                    $(current).find('.error-main').html('<div class="alert alert-success">' + res.message + '</div>').show();
                    $(current).find('.btn-submit').removeAttr('disabled');
                    window.location.hash = '#' + id;
                    if (typeof after !== typeof undefined && after !== false) {
                        eval(after);
                    }
                    if(redirect == 'edit')
                    {
                      window.location.href = 'edit.php?id=' + res.id;
                    }
                    else if(redirect == 'flip')
                    {
                      var flipRedirect = $(current).attr('cluster-redirect-flip');
                       if (typeof flipRedirect !== typeof undefined && flipRedirect !== false) {
                        window.location.href = flipRedirect + '?id=' + res.id;
                      }

                    }
                    else if (typeof redirect !== typeof undefined && redirect !== false) {
                        window.location.href = redirect;
                    }
            

        },'json')
      .fail(function(xhr) {

        $(current).find('.btn-submit').removeAttr('disabled');
        $(current).find('.error-main').html('<div class="alert alert-danger">Following errors are listed. Please check errors and resubmit the form.</div>').show();
        	$('.error-input').html('');
          var html = '';
          var res = xhr.responseJSON;
          console.log(xhr);
          if (typeof res === 'undefined') {
          	$(current).find('.error-main').html('<div class="alert alert-danger">Something went wrong</div>').show();
                return;
          }
          
            if(typeof res.error_text === 'undefined')
            {
            	$(current).find('.error-main').html('<div class="alert alert-danger">Something went wrong</div>').show();
            	window.location.hash = '#' + id;
            	return;
            }
            else
            {
            	$(current).find('.error-main').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
            	
            }
          
        
        // var res1 = $.parseJSON('"' + res + '"');
         $.each(res.error_description, function(i, value) {
         		var parent = $(current).find("[name='" + i + "']").parents('.input-container').first();
         		$(parent).find('.error-input').append('<div class="alert alert-danger alert-flat">' + value + '</div>');
              
          });
          
          
          window.location.hash = '#' + id;
      },'json');;
  });


    if ($(".file_url").length > 0) {
  var url = $('.file_url').val();
  var domain = $('.domain').val();
    $('.fileupload').fileupload({
          url: url,
          dataType: 'json',
          submit: function(e,data){
            var parent = $(this).parents('.file_upload_container').first();
            $(parent).find('.files_area').html('');
            $(parent).find('.error_area').html('<div class="alert alert-warning">Upload in progress</div>');
            $(parent).find('.progress .progress-bar').removeAttr('style');


          },
          done: function (e, data) {
              /*$.each(data.result.files, function (index, file) {
                  console.log(file);
              });*/
             
              var parent = $(this).parents('.file_upload_container').first();
             
              
              $(parent).find('.error_area').html('');
              $(parent).find('.file_url').val(data.result.file);

              console.log(data.result.fileType);
              if(data.result.fileType == 'image')
              {
               $(parent).find('.files_area').html('<img src="' + data.result.url + '" style="max-width:40px" />');
              }
              else  if(data.result.fileType == 'file')
              {
                $(parent).find('.files_area').html('<div><a style="margin-right:5px" href="' + data.result.url + '" target="_blank" >' + data.result.file + '</a><button type="button" class="btn btn-danger btn-sm btn-delete-file-temp"><i class="fa fa-trash"></i></button></div>');
              }
          },
          fail: function (e, data) {
            var parent = $(this).parents('.file_upload_container').first();
            $(parent).find('.error_area').html('<div class="alert alert-danger">' + data.jqXHR.responseJSON.error_text + '</div>');
            $(parent).find('.progress .progress-bar').css(
                  'background-color',
                  'salmon'
              );
          },
          progressall: function (e, data) {
            var parent = $(this).parents('.file_upload_container').first();
              var progress = parseInt(data.loaded / data.total * 100, 10);
               $(parent).find('.progress .progress-bar').css(
                  'width',
                  progress + '%'
              );
          }
      }).prop('disabled', !$.support.fileInput)
          .parent().addClass($.support.fileInput ? undefined : 'disabled');
   
  }
 
});

$(document).on('click', '.btn-delete', function(res){
  var confirmMessage = $(this).attr('cluster-confirm');
    if (typeof confirmMessage !== typeof undefined && confirmMessage !== false) {
       var conf = confirm(confirmMessage);
        if(!conf)
        {
            return;
        }
    } 
   

  
  $(this).attr('disabled', 'disabled').text('Deleting......');

  var current = $(this);
  var href = $(this).attr('cluster-href');
  var parent = $(this).parents('tr').first();
  $.post(href, function(){
      
     $(parent).remove();
  },'json').fail(function(xhr){
    
     var res = xhr.responseJSON;
       $(current).removeAttr('disabled').html('<i class="fa fa-trash"></i>');
    if (typeof res === 'undefined') {
            $(parent).find('.error-input').html('<div class="alert alert-danger">Something went wrong</div>').show();
          }
         
          if(typeof res.error_text === 'undefined')
          {
            $(parent).find('.error-input').html('<div class="alert alert-danger">Something went wrong</div>').show();
            window.location.href = '#body_part';
            return;
          }
          else
          {
            $(parent).find('.error-input').html('<div class="alert alert-danger">' + res.error_text + '</div>').show();
            window.location.href = '#body_part';
            return;
          }

    
  },'json');
});    