Reclabox = function() {};
Reclabox.LiveContentUpdater = function() {
  var api = {};

  /* 
    Update page content
  */
  var update_content = function(results) {
    // update live trackings
    if (results.live_trackings) {
      for (var i = 0; i < results["live_trackings"]["count"]; i++) {
        $('liveContent').insert({top: results["live_trackings"]["elements"][i]["html"]});
        var elemId = 'liveTracking' + results["live_trackings"]["elements"][i]["id"];
        new Effect.Morph(elemId, {
          style: 'height:28px',
          duration: 0.3 
        });
        new Effect.Opacity(elemId, {from: 0, to: 1, duration: 1});
      }
    }
    // update reclamations
    if (results.reclamations) {
      for (var i = 0; i < results["reclamations"]["count"]; i++) {
        $('articles').insert({top: results["reclamations"]["elements"][i]["html"]});
        var elemId = 'article' + results["reclamations"]["elements"][i]["id"];
        new Effect.Opacity(elemId, {from: 0, to: 1, duration: 1});
      }
    }		
    // update comments
    if (results.comments) {
      for (var i = 0; i < results["comments"]["count"]; i++) {
        $('newestComments').insert({top: results["comments"]["elements"][i]["html"]});
        var elemId = 'comment' + results["comments"]["elements"][i]["id"];
        new Effect.Morph(elemId, {
          style: 'height:28px',
          duration: 0.3 
        });
        new Effect.Opacity(elemId, { from: 0, to: 1, duration: 1 });
      }
    }				
  }

  /*
    Watch results and update content
  */
  var check_results = function(o) {
    try {
      var results = o.responseText.evalJSON();
      if (results) {
        update_content(results);
      }
    } catch(e) {
      console.log('watch_batch_results_cb error: ' + e);
    }
    if (results.reclamations) {
      data = {
        reclamations: {last_date: results["reclamations"]["last_date"]},	
        comments: {last_comment_or_vote_id: results["comments"]["last_comment_or_vote_id"]},		
        live_trackings: {last_id: results["live_trackings"]["last_id"]}
      };
    } else {
      data = {
        comments: {last_comment_or_vote_id: results["comments"]["last_comment_or_vote_id"]},		
        live_trackings: {last_id: results["live_trackings"]["last_id"]}
      };
    }
    setTimeout(function() {api.update(data);}, 6000);
  };

  /*
    Public LiveContentUpdater interface
  */
  api.update = function(data) {
    var base_url = "/articles/live_content";
    new Ajax.Request(base_url, {
      method: 'get',
      parameters: {authenticity_token: authenticity_token, data: Object.toJSON(data)},
      onSuccess: function(o){check_results(o);},
      onFailure: function() {}
    });
  };

  return api;
}();

function ToggleWriteForm() {
  toggleable_elements = document.getElementsByClassName('toggleable');
  for(var i = 0; i < toggleable_elements.length; i++){
    toggleable_elements[i].toggle();
  }
  SwapIDsNamesAndCopyValue(document.getElementById('on_firm_city'), document.getElementById('not_used_on_firm_city'));
  SwapIDsNamesAndCopyValue(document.getElementById('on_firm'), document.getElementById('not_used_on_firm'));

  var toggle_button = document.getElementById('togglebutt');
  if (toggle_button.value == "Weniger Angaben") {
    toggle_button.value = "Weitere Angaben";
  } else {
    toggle_button.value = "Weniger Angaben";
  }

};

function SwapIDsNamesAndCopyValue(old_element, new_element) {
  new_element.value = old_element.value;
  SwapAttrValue(old_element, new_element, 'id', true);
  SwapAttrValue(old_element, new_element, 'name', true);
  SwapAttrValue(old_element.style, new_element.style, 'color', false);
  validate(new_element.id);
};

function SwapAttrValue(element_p, element_q, attr, use_temp_value) {
  // avoid having two same attr values at the same time (e.g. for 'id' attribute) - use temporary value if 'use_temp_value'
  var p_value = element_p[attr];
  var q_value = element_q[attr];
  if (use_temp_value) {
    element_p[attr] = 'tmp_' + p_value;
  }
  element_q[attr] = p_value;
  element_p[attr] = q_value;
};

function aprichiudi(elemId)
{
	// new Effect.Morph(elemId, { style: 'height:0px;', duration: 0.5 });
	
	if (document.getElementById(elemId).style.display == 'none') {
		document.getElementById(elemId).style.display = 'block';
		document.getElementById(elemId+'Button').innerHTML = '<img src="/images/up2.gif" alt="Minimieren" title="Minimieren">';
	}
	else {
		document.getElementById(elemId).style.display = 'none';
		document.getElementById(elemId+'Button').innerHTML = '<img src="/images/down2.gif" alt="Maximieren" title="Maximieren">';
	}
};

function addOnLoad(func) {
  if (window.onload) {
    var temp = window.onload;
    window.onload = function () {
      temp();
      func();
    }
  } else {
    window.onload = func;
  }
};

function live_track_comment_read() {
  var address = window.location;
  /*
    The address format is "/beschwerde/123-some-thing" or "beschwerde/123-some-thing#comment1234" and
    we check that there are no other slashes in and after the "123-some-thing" part; the "-some-thing" part is optional:
  */
  if (address.pathname.match(/^\/beschwerde\/\d+(-[^\/]*)?$/)) {
    var article_id = address.pathname.match(/^\/beschwerde\/(\d+)/)[1];
    if (address.hash.match(/^#comment\d+$/)) {
      var comment_id = address.hash.match(/^#comment(\d+)$/)[1];
      var url = "/beschwerde/" + article_id + "/track_comment_read/" + comment_id;
    } else if (address.hash.match(/^#defence$/)) {
      var url = "/beschwerde/" + article_id + "/track_defence_read";
    } else if (address.hash == '' || address.hash.match(/^#comments$/) || address.hash.match(/^#gallery$/)) {
      var url = "/beschwerde/" + article_id + "/track_read";
    }
    /*
      We use the prototype.js here:
    */
    new Ajax.Request(url, {
      method: 'POST',
      parameters: {authenticity_token: authenticity_token}
    });
  }
};
addOnLoad(live_track_comment_read);

function count_link_click(link_id) {
  new Ajax.Request("/complaint_links/increment_clicks", {
    method: 'POST',
    parameters: {authenticity_token: authenticity_token, link_id: link_id}
  });
}

function show_weiterleiten_if_requested() {
  var address = window.location;
  /*
    The address format is "beschwerde/123-some-thing#weiterleiten" and
    we check that there are no other slashes in and after the "123-some-thing" part; the "-some-thing" part is optional:
  */
  if (address.pathname.match(/^\/beschwerde\/\d+(-[^\/]*)?$/)) {
    var article_id = address.pathname.match(/^\/beschwerde\/(\d+)/)[1];
    if (address.hash.match(/^#weiterleiten$/)) {
      ShowWin('weiterbox', 650);
    }
  }
};
addOnLoad(show_weiterleiten_if_requested);

function show_gallery_if_requested() {
  var address = window.location;
  /*
    The address format is "beschwerde/123-some-thing#gallery" and
    we check that there are no other slashes in and after the "123-some-thing" part; the "-some-thing" part is optional:
  */
  if (address.pathname.match(/^\/beschwerde\/\d+(-[^\/]*)?$/)) {
    var article_id = address.pathname.match(/^\/beschwerde\/(\d+)/)[1];
    if (address.hash.match(/^#gallery$/)) {
      new Ajax.Request(address.pathname + '/image-gallery', {
        method: 'GET',
        parameters: {for_complaint: 1}
      });
    }
  }
};
addOnLoad(show_gallery_if_requested);

function show_commentbox_if_requested() {
  var address = window.location;
  /*
    The address format is "beschwerde/123-some-thing#write_comment" and
    we check that there are no other slashes in and after the "123-some-thing" part; the "-some-thing" part is optional:
  */
  if (address.pathname.match(/^\/beschwerde\/\d+(-[^\/]*)?$/)) {
    var article_id = address.pathname.match(/^\/beschwerde\/(\d+)/)[1];
    if (address.hash.match(/^#write_comment$/)) {
      ShowWin('kommentbox', 650);
    }
  }
};
addOnLoad(show_commentbox_if_requested);

function show_nocommentbox_if_requested() {
  var address = window.location;
  /*
    The address format is "beschwerde/123-some-thing#write_nocomment" and
    we check that there are no other slashes in and after the "123-some-thing" part; the "-some-thing" part is optional:
  */
  if (address.pathname.match(/^\/beschwerde\/\d+(-[^\/]*)?$/)) {
    var article_id = address.pathname.match(/^\/beschwerde\/(\d+)/)[1];
    if (address.hash.match(/^#write_nocomment$/)) {
      ShowWin('nocommentbox', 450);
    }
  }
};
addOnLoad(show_nocommentbox_if_requested);

function show_regelbox(article_id, article_type) {
  document.getElementById('regelbox_article_id').value = article_id;
  document.getElementById('regelbox_article_type').value = article_type;
  ShowWin('regelbox', 650);
};

function reset_form(form_name) {
  document[form_name].reset();
};

function close_and_reset_commentbox() {
  HideWin('kommentbox');
  if (! typeof(already_uploaded_attachment_num) == 'undefined') {
    already_uploaded_attachment_num = 1;
  }
  if (! typeof(already_uploaded_video_attachment_num) == 'undefined') {
    already_uploaded_video_attachment_num = 1;
  }
  reset_input_rows();

  Element.update('comment_first_name', '');
  Element.update('comment_last_name', '');
  Element.update('comment_body', '');
  Element.update('error_messages_comment', '');
  Element.update('uploaded_images_report', '');

  document.getElementById('edit_comment_id').value = '';
  document.getElementById('comment_first_name').value = '';
  document.getElementById('comment_last_name').value = '';
  document.getElementById('comment_body').value = '';
  document.getElementById('error_messages_comment').value = '';
  document.getElementById('uploaded_images_report').value = '';
  document.getElementById('commentform_agb_confirmed').checked = false;

  new Ajax.Request('/beschwerde/reset_comment_write_session', {
    method: 'POST',
    parameters: {authenticity_token: authenticity_token}
  });
};

function close_and_reset_box(box_id, form_id, error_messages_id) {
  HideWin(box_id);
  reset_form(form_id);
  Element.update(error_messages_id, '');
};

function can_add_attachment_input_row() {
  var can_add = true;
  $$('#image_attachment_table input').each(function(input_element) {
    if (input_element.value.match(/^\s*$/)) {
      can_add = false;
    }
  });
  if (can_add && ((max_attachment_num - already_uploaded_attachment_num) > 0)) {
    already_uploaded_attachment_num += 1;
    return true;
  } else {
    return false;
  }
}

function can_add_video_attachment_input_row() {
  var can_add = true;
  $$('#video_attachment_table input').each(function(input_element) {
    if (input_element.value.match(/^\s*$/)) {
      can_add = false;
    }
  });
  if (can_add && ((max_video_attachment_num - already_uploaded_video_attachment_num) > 0)) {
    already_uploaded_video_attachment_num += 1;
    return true;
  } else {
    return false;
  }
}

function reset_upload_file_fields() {
  var tr_array = $('image_attachment_table').childElements()[0].childElements(); // there is a [tbody] betweent table and tr
  if (tr_array.size() > 1) {
    /* Remove (but first) input fields */
    tr_array.each(function(tr, index) {
      if (index != 0) {
        tr_array[index].remove();
      }
    })
  }
  /* Reset the value in the first input field */
  tr_array[0].childElements()[1].childElements()[0].value = ''; // tr has [td, td, td], the second td includes [input] which we need to reset
}

function swap_style_focused_image(new_focused_id) {
  SwapAttrValue(document.getElementById('thumbnail_' + focused_image_id).style,
    document.getElementById('thumbnail_' + new_focused_id).style, 'border', false);
  focused_image_id = new_focused_id;
}

function swap_style_focused_video(new_focused_id) {
  SwapAttrValue(document.getElementById('comment_video_thumbnail_' + comments_focused_video_id).style,
    document.getElementById('comment_video_thumbnail_' + new_focused_id).style, 'border', false);
  comments_focused_video_id = new_focused_id;
}

var search_text_field_cleared = false;
function clear_search_text_field() {
  if (! search_text_field_cleared) {
    var element = document.getElementById('searchstr');
    element.value = '';
    element.style.color = '#000';
    search_text_field_cleared = true;
  }
}

function reset_input_rows_for(element_id, max, current, add_row_fnc) {
  arr = $$('#' + element_id + ' tr');
  var start = 1;
  if (current >= max) {
    /* remove all the rows */
    start = 0;
  } else {
    arr_inputs = $$('#' + element_id + ' input');
    if (arr_inputs.length > 0) {
      /* reset the first input, it will stay there */
      $$('#' + element_id + ' input')[0].value = '';
    } else {
      /* there is no input now so add it */
      add_row_fnc();
    }
  }
  arr.slice(start, arr.length).each(function(tr_element) {
    Element.remove(tr_element);
  });
}

function reset_input_rows() {
  if (! (typeof(already_uploaded_attachment_num) == 'undefined') && ! (typeof(max_attachment_num) == 'undefined')) {
    reset_input_rows_for('image_attachment_table', max_attachment_num, already_uploaded_attachment_num - 1, add_attachment_input_row);
  }
  if (! (typeof(already_uploaded_video_attachment_num) == 'undefined') && ! (typeof(max_video_attachment_num) == 'undefined')) {
    reset_input_rows_for('video_attachment_table', max_video_attachment_num, already_uploaded_video_attachment_num - 1, add_video_attachment_input_row);
  }
}

function launch_edit_comment_countdown(element_id, wrap_element_id, seconds_left) {
  if (comments_edit_countdowns[element_id]) {
    /*
      don't add another countdown, if there is one already present
    */
  } else {
    comments_edit_countdowns[element_id] = true;
    edit_comment_countdown(element_id, wrap_element_id, seconds_left);
  }
}

function edit_comment_countdown(element_id, wrap_element_id, seconds_left) {
  if (seconds_left > 1) {
    seconds_left = seconds_left - 1;
    Element.update(element_id, 'Kommentar noch ' + seconds_left + ' Sekunden editierbar');
    setTimeout('edit_comment_countdown("' + element_id + '","' + wrap_element_id + '",' + seconds_left + ')', 1000);
  } else {
    Element.replace(wrap_element_id, '');
  }
}
