$(document).ready(function(){

});

function newCriteriaOr() {
    //find next available ID for criteria_or_XXX
    var i = 0;
    while ($('#criteria_or_'+i).length) {
      i = i + 1;
    }
    $('#edit_rule_criteria').append('<div id="criteria_or_'+i+'" class="criteria_or"><div><button class="and_add_button" onclick="newCriteriaAnd('+i+');return false;"></button><button class="and_delete_button" onclick="$(this).parent().parent().remove();return false;"></button></div></div>');
    newCriteriaAnd(i);
}

function newCriteriaAnd(i) {
    var j = 0;
    while ($('#criteria_and_'+i+'_'+j).length) {
      j = j + 1;
    }
    $('#criteria_or_'+i).append('<div id="criteria_and_'+i+'_'+j+'" class="criteria_and"><select id="criteria_and_'+i+'_'+j+'_field" name=""><option value=""></option><option value="subject">Subject</option><option value="fromname">From name</option><option value="fromemail">From email</option><option value="toemail">To email</option></select> <select id="criteria_and_'+i+'_'+j+'_operation" name=""><option value="contains">contains</option><option value="equals">is</option><option value="beginswith">begins with</option><option value="endswith">ends with</option></select><br /><input type="text" id="criteria_and_'+i+'_'+j+'_data" name="" value="" /></div>');
}


function processMessages() {
    $('#process_progress').html('<p><img class="loading" src="images/loading-small.gif" alt="Loading..." /> Processing messages... this may take some time.</p>');
    $.ajax({
      type: "POST",
      url: "ajax.php",
      data: ({action : 'process'}),
      success: function(html){
         $('#process_progress').html(html);
         tb_init('a.thickbox, area.thickbox, input.thickbox');
      }
    });
}

function refreshImsList() {
    $('#list_ims').html('<p><img class="loading" src="images/loading-small.gif" alt="Loading..." /> Loading IM accounts...</p>');
    $.ajax({
      type: "POST",
      url: "ajax.php",
      data: ({action : 'list_ims'}),
      success: function(html){
         $('#list_ims').html(html);
         tb_init('a.thickbox, area.thickbox, input.thickbox');
      }
    });
}

function refreshSmsList() {
    $('#list_sms').html('<p><img class="loading" src="images/loading-small.gif" alt="Loading..." /> Loading SMS details...</p>');
    $.ajax({
      type: "POST",
      url: "ajax.php",
      data: ({action : 'list_sms'}),
      success: function(html){
         $('#list_sms').html(html);
         tb_init('a.thickbox, area.thickbox, input.thickbox');
      }
    });
}

function refreshStats() {
    $('#list_stats').html('<p><img class="loading" src="images/loading-small.gif" alt="Loading..." /> Loading statistics...</p>');
    $.ajax({
      type: "POST",
      url: "ajax.php",
      data: ({action : 'list_stats'}),
      success: function(html){
         $('#list_stats').html(html);
      }
    });
}

function refreshMaintenance() {
    $('#list_maintenance').html('<p><img class="loading" src="images/loading-small.gif" alt="Loading..." /> Loading maintenance data...</p>');
    $.ajax({
      type: "POST",
      url: "ajax.php",
      data: ({action : 'list_maintenance'}),
      success: function(html){
         $('#list_maintenance').html(html);
      }
    });
}


function im_edit_form_submit() {
      $('#im_edit_submit').attr('disabled', 'disabled').after('<img class="loading" src="images/loading-small.gif" alt="Loading..." />');
      $('div.errors').remove();
      $('div.messages').remove();
      
      $.ajax({
         type: "POST",
         url: "ajax.php",
         data: ({action : 'im_edit',
                 id:      $('#im_edit_id').val(),
                 type:    $('#im_edit_type').val(),
                 account: $('#im_edit_account').val()
                }),

         success: function(json){
          if (json == 'success') {
             displayMessages('["IM Account saved"]');
             tb_remove();
           } else {
             displayErrors(json);
           }
           $('#im_edit_submit').attr('disabled', '');
           $('.loading').remove();
         }
       }); 
      return false;
}

function sms_edit_form_submit() {
      $('#sms_edit_submit').attr('disabled', 'disabled').after('<img class="loading" src="images/loading-small.gif" alt="Loading..." />');
      $('div.errors').remove();
      $('div.messages').remove();
      
      $.ajax({
         type: "POST",
         url: "ajax.php",
         data: ({action : 'sms_edit',
                 id:      $('#sms_edit_id').val(),
                 name:    $('#sms_edit_name').val(),
                 number:  $('#sms_edit_number').val()
                }),

         success: function(json){
          if (json == 'success') {
             displayMessages('["SMS Account saved"]');
             tb_remove();
           } else {
             displayErrors(json);
           }
           $('#sms_edit_submit').attr('disabled', '');
           $('.loading').remove();
         }
       }); 
      return false;
}

function refreshRulesList() {
    $('#list_rules').html('<p><img class="loading" src="images/loading-small.gif" alt="Loading..." /> Loading rules...</p>');
    $.ajax({
      type: "POST",
      url: "ajax.php",
      data: ({action : 'list_rules'}),
      success: function(html){
         $('#list_rules').html(html);
         tb_init('a.thickbox, area.thickbox, input.thickbox');
      }
    });
}


function refreshFlaggedList() {
    $('#list_flagged').html('<p><img class="loading" src="images/loading-small.gif" alt="Loading..." /> Loading flagged messages...</p>');
    $.ajax({
      type: "POST",
      url: "ajax.php",
      data: ({action : 'list_flagged'}),
      success: function(html){
         $('#list_flagged').html(html);
         tb_init('a.thickbox, area.thickbox, input.thickbox');
      }
    });
}

function rules_add_form_submit() {
/* NEW RULE submit */
      $('#rules_add_submit').attr('disabled', 'disabled').after('<img class="loading" src="images/loading-small.gif" alt="Loading..." />');
      $('div.errors').remove();
      $('div.messages').remove();
      
      var unread = ($('#rules_add_unread:checked').val() == 1) ? true : false;
      var read   = ($('#rules_add_read:checked').val() == 1) ? true : false;
      var delay  = ($('#rules_add_enable_delay:checked').val() == 1) ? $('#rules_add_delay').val() : 0;
      
      var action_move   = ($('#rules_add_action_move:checked').val() == 1)   ? $('#rules_add_move_destination').val() : '';
      var action_delete = ($('#rules_add_action_delete:checked').val() == 1) ? true : false;
      var action_im     = ($('#rules_add_action_im:checked').val() == 1)     ? $('#rules_add_imid').val() : '';
      var action_sms    = ($('#rules_add_action_sms:checked').val() == 1)    ? $('#rules_add_smsid').val() : '';
      
      or_array = [];
      $('div.criteria_or').each(function(){
        and_array = [];
        $('#'+$(this).attr('id')+' div.criteria_and').each(function(){
          and_array[and_array.length] = [$('#'+$(this).attr('id')+'_field').val(), $('#'+$(this).attr('id')+'_operation').val(), $('#'+$(this).attr('id')+'_data').val()];
        });
        or_array[or_array.length] = and_array;
      });
      
      $.ajax({
         type: "POST",
         url: "ajax.php",
         data: ({action : 'rules_add',
                 id:            $('#rules_add_id').val(),
                 name:          $('#rules_add_name').val(),
                 criteria:      $('#rules_add_criteria').val(),
                 priority:      $('[name=rules_add_priority]:checked').val(),
                 unread:        unread,
                 read:          read,
                 delay:         delay,
                 action_move:   action_move,
                 action_delete: action_delete,
                 action_im:     action_im,
                 action_sms:     action_sms,
                 or_array:      $.toJSON(or_array)
                }),

         success: function(json){
          if (json == 'success') {
             displayMessages('["Rule saved"]');
             tb_remove();
           } else {
             displayErrors(json);
           }
           $('#rules_add_submit').attr('disabled', '');
           $('.loading').remove();
         }
       }); 
      return false;
}

function refreshAccountList() {
    $('#list_accounts').html('<p><img class="loading" src="images/loading-small.gif" alt="Loading..." /> Loading accounts...</p>');
    $.ajax({
      type: "POST",
      url: "ajax.php",
      data: ({action : 'list_accounts'}),
      success: function(html){
         $('#list_accounts').html(html);
         tb_init('a.thickbox, area.thickbox, input.thickbox');
      }
    });
}

function edit_account_form_submit() {
/* EDIT ACCOUNT - onclick */
      $('#edit_account_submit').attr('disabled', 'disabled').after('<img class="loading" src="images/loading-small.gif" alt="Loading..." />');
      $('div.errors').remove();
      $('div.messages').remove();
      $.ajax({
         type: "POST",
         url: "ajax.php",
         data: ({action : 'edit_account',
                 accountid: $('#edit_account_accountid').val(),
                 name:      $('#edit_account_name').val(),
                 host:      $('#edit_account_host').val(),
                 port:      $('#edit_account_port').val(),
                 username:  $('#edit_account_username').val(),
                 password:  $('#edit_account_password').val(),
                 type:      $('[name=edit_account_type]:checked').val()
                }),

         success: function(json){
          if (json == 'success') {
             displayMessages('["Account changes saved"]');
             refreshAccountList();
             tb_remove();
           } else {
             displayErrors(json);
           }
           $('.loading').remove();
           $('#edit_account_submit').attr('disabled', '');
         }
       }); 
      return false;
}

function update_renamed_folders() {
      $('#update_renamed_folders').attr('disabled', 'disabled').after('<img class="loading" src="images/loading-small.gif" alt="Loading..." />');
      $('div.errors').remove();
      $('div.messages').remove();
      
      //folderarray = new Array;
      var urf_folders = {};
      $("input[name=rename_destination]").each(function(id) {
       //myVar = $("input[name=rename_destination]").get(id);
       //folderarray.push(myVar.value);
       if ($(this).val() != '') {
         //folderarray.push($(this).attr('title')+'==='+$(this).val());
         urf_folders[$(this).attr('title')] = $(this).val();
       }
       //alert($(this).attr('title')+'='+$(this).val());
       //folderarray[$(this).attr('title')] = $(this).val();
      });
      
      $.ajax({
         type: "POST",
         url: "ajax.php",
         data: ({action : 'update_renamed_folders',
                 rename_destination: $.toJSON(urf_folders)
                }),

         success: function(json){
          if (json == 'success') {
             displayMessages('["Folder locations updated"]');
           } else {
             displayErrors(json);
           }
           $('.loading').remove();
         }
       }); 
      return false;
}

function delete_account_form_submit() {
/* DELETE ACCOUNT - onclick */
      $('#delete_account_submit').attr('disabled', 'disabled').after('<img class="loading" src="images/loading-small.gif" alt="Loading..." />');
      $('div.errors').remove();
      $('div.messages').remove();
      $.ajax({
         type: "POST",
         url: "ajax.php",
         data: ({action : 'delete_account',
                 accountid: $('#delete_account_accountid').val()
                }),

         success: function(json){
          if (json == 'success') {
             displayMessages('["Account deleted"]');
             refreshAccountList();
             tb_remove();
           } else {
             displayErrors(json);
           }
           $('.loading').remove();
         }
       }); 
      return false;
}

function displayErrors(json_data) {
  var json = eval("(" + json_data + ")"); 
  var html = '';
  for (var i=0; i < json.length; i++) {
    var html = html+'<li>'+json[i]+'</li>';
  }
  $('#content').prepend('<div class="errors hidden"><ul>'+html+'</ul></div>');
  $('div.errors').show('fast');
}

function displayMessages(json_data) {  
  var json = eval("(" + json_data + ")"); 
  var html = '';
  for (var i=0; i < json.length; i++) {
    var html = html+'<li>'+json[i]+'</li>';
  }
  $('#content').prepend('<div class="messages hidden"><ul>'+html+'</ul></div>');
  $('div.messages').show('fast');
}

function is_array(input){
  return typeof(input)=='object'&&(input instanceof Array);
}


/*
function displayError(request, errorType, errorThrown) {
  try {
    if (errorType == 'timeout') {
      alert('timeout error');
    }
  catch (e) {}
  }
}
*/