(function($){
  $.create = function(str) { return $(document.createElement(str)); }
  $.id = function(str) { return $(document.getElementById(str)); }
})(jQuery)


jQuery.ajaxSetup({
  beforeSend: function (xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

$(document).ajaxSend(function(event, request, settings) {
  if (settings.type == 'GET' || settings.type == 'get' || typeof(AUTH_TOKEN) == "undefined") return;
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

var Valipat = {

  init: function(){
    $('.print-page').click(Valipat.print_page);
    $('.check-all').click(function(){ Valipat.check_all($(this), true); return false; } );
    $('.uncheck-all').click(function(){ Valipat.check_all($(this), false); return false; } );
    $('.js-confirm').click(Valipat.confirm);
    $('input.wait').click(function(){ setTimeout( function(){ $('img.spinner').attr('src', '/images/spinner.gif') }, "", 50); $('img.spinner').css('visibility', 'visible'); } );
    Valipat.Dashboard.init();
    Valipat.Templates.init();
    Valipat.WordCount.init();
    Valipat.Agents.init();
    Valipat.SpecialRequests.init();
    Valipat.Powers.init();
    Valipat.QuoteBasis.init();
    Valipat.Details.init();
    Valipat.Contacts.init();
    Valipat.UserSessions.init();
    // Valipat.Invoices.init();
    Valipat.CreditNotes.init();
    Valipat.Requests.init();
    Valipat.Search.init();
    Valipat.Workflows.init();

    Engine.utils.links();
    Engine.utils.mails();
  },

  confirm: function(){
    return confirm($(this).attr('title'));
  },

  print_page: function(){
    window.print();
    return false;
  },

  check_all: function(elt, value){
    $(elt.attr("class").split(" ")).each(
      function(){
        $('input[type=\'checkbox\'].' + this).attr('checked', value);
      }
    );
  }
};

Valipat.Dashboard = {
    init: function() {
	$('#statuses').hide();
	$('.toggle-statuses').click(function() { $('#statuses').toggle(); });
    }
};

Valipat.QuoteBasis = {

	init: function() {
		$("span.title-tooltip").tooltip({
		    bodyHandler: function() {
		        return "<h3>" + $(this).children("label")[0].title + "</h3>";
		    },
		    showURL: false
		});
	}

};

Valipat.Templates = {

  init: function(){
    $('#ajax-error').hide();
    $('#create-template-section').hide();
    $('#create-template-button').click(Valipat.Templates.create_template);
    $('#template-select').change(Valipat.Templates.change_template);
    $('#create-template-link').click(Valipat.Templates.show_new_template_section);
    $('.cancel-template-creation').click(Valipat.Templates.cancel_template_creation);
  },

  create_template: function(){
    $('#ajax-error').hide();
    url  = '/quote_templates';
    data = $('div.countries-a input, .epo-countries input').serialize() + "&" + $('#template-name').serialize();
    $.post(url, data, Valipat.Templates.template_created, 'json');
    $.ajax({ url: url,
             type: 'POST',
             data: data,
             dataType: 'json',
             success: Valipat.Templates.template_created,
             error: function(){ $('#ajax-error').show(); }
           });
    return false;
  },

  template_created: function(data){
    template = data.quote_template;
    $('optgroup.existing-templates').append( $.create('option').attr('value', template.id).text(template.name) );
    $('#template-select').val(template.id);
    Valipat.Templates.cancel_template_creation();
    $('p#choose-template-section .note-a').html('<strong>The template has been successfully created</strong> and you are using it right now.');
  },

  cancel_template_creation: function(){
    $('#template-name').val('');
    $('#ajax-error').hide();
    $('#create-template-section').hide();
    $('#choose-template-section').show();
    return false;
  },

  change_template: function(){
    template_id = $(this).val();
    if( template_id == 'new' ){
      Valipat.Templates.show_new_template_section();
    }else if(isFinite(template_id)){
      url = '/quote_templates/' + $(this).val();
      $.getJSON(url, Valipat.Templates.fill_country_choices);
    }
  },

  show_new_template_section: function(){
    $('#choose-template-section').hide();
    $('#create-template-section').show();
    return false;
  },

  fill_country_choices: function(data){
    $('input:checkbox.validation-country,input:checkbox.provided-language,input:checkbox.representation-country').each(
      function(){
        $(this).attr('checked', false);
      }
    );
    countries = data.quote_template.countries;
    for(country in countries){
      $('#country-' + country.toUpperCase()).attr('checked', Number(countries[country]));
    }
    languages = data.quote_template.provided_translations;
    for(language in languages){
      $('#provided-' + language).attr('checked', Number(languages[language]));
    }
		languages_for_epo = data.quote_template.translations_for_epo;
    for(language in languages_for_epo){
      $('#translations-for-epo-' + language).attr('checked', Number(languages_for_epo[language]));
    }
  }
};

Valipat.WordCount = {
  init: function(){
    $('p.estimate-a > span').hide();
    $('p.estimate-a a').click(Valipat.WordCount.show_estimate_bubble);
    $('p.estimate-a input[type=submit]').click(Valipat.WordCount.calculate_nb_of_words);
    $('.section').hide();
    if($('#quote_patent_attributes_word_count_method_valipat').attr('checked')){ Valipat.WordCount.show_valipat(); };
    if($('#quote_patent_attributes_word_count_method_estimate').attr('checked')){ Valipat.WordCount.show_estimate(); };
    if($('#quote_patent_attributes_word_count_method_rough_estimate').attr('checked')){ Valipat.WordCount.show_rough_estimate(); };
    $('#quote_patent_attributes_word_count_method_valipat').click(function(){ Valipat.WordCount.show_valipat(); });
    $('#quote_patent_attributes_word_count_method_estimate').click(function(){ Valipat.WordCount.show_estimate(); });
    $('#quote_patent_attributes_word_count_method_rough_estimate').click(function(){ Valipat.WordCount.show_rough_estimate(); });
    $('.nb-drawings').keyup(Valipat.WordCount.display_special_conditions);
    Valipat.WordCount.display_special_conditions;

    $('#quote_patent_attributes_has_text_on_drawings_true').click(function() { alert('Extra costs will apply due to the translations required on the drawings.'); });
  },

  display_special_conditions: function(){
    nb_drawings = Number($(this).val());
    if( isFinite(nb_drawings) && nb_drawings > 0 ){
      $('.special-conditions').show();
    }else{
      $('.special-conditions').hide();
    }
  },

  show_estimate_bubble: function(){
    $(this).next('span').toggle();
    return false;
  },

  calculate_nb_of_words: function(){
    nb_of_pages = $(this).prev('input[type=text]').val();
    if(nb_of_pages != "" && isFinite(Number(nb_of_pages))){
      nb_of_words = Number(nb_of_pages) * 300
      $(this).parents('p.estimate-a').prev().children('input').val(nb_of_words);
    }
    $(this).parents('span').hide();
    return false;
  },

  show_estimate: function() {
    $('.section').hide();
    $('.word_count_requested_fields').hide();
    $('.estimate-quote.section').show();
    $('.word_count_reuested_estimate').show();
    Valipat.WordCount.display_special_conditions.call($('#quote_patent_attributes_nb_of_pages_of_drawing_estimated'));
    return false;
  },

  show_valipat: function() {
    $('.section').hide();
    $('.word_count_requested_fields').hide();
    $('.valipat-quote.section').show();
    $('.word_count_reuested_valipat').show();
    $('.special-conditions').hide();
    return false;
  },

  show_rough_estimate: function() {
    $('.section').hide();
    $('.word_count_requested_fields').hide();
    $('.estimate-rough-quote.section').show();
    $('.word_count_reuested_rough_estimate').show();
    Valipat.WordCount.display_special_conditions.call($('#quote_patent_attributes_nb_of_pages_of_drawing_rough_estimated'));
    return false;
  }
};

Valipat.Agents = {
  init: function(){
    $('div.change-agent-a').hide();
    $('div.change-agent-a p.fields').hide();
    $('div.change-agent-a p.tick').hide();
    $('a.change-agent').click(Valipat.Agents.show_custom_agent_box);
    $('a.cancel').click(Valipat.Agents.cancel);
    $('select.custom-agent').change(Valipat.Agents.toggle_custom_agent_fields);
    $('.change-agent-a input.confirm').click(Valipat.Agents.change_agent);
  },

  cancel: function(){
    $(this).parents('div.change-agent-a').fadeOut(300);
    custom_agent_select = $(this).parents('div.change-agent-a').find('select')[0];
    custom_agent_hidden = $(this).parents('div.change-agent-a').find('input.custom-agent');
    $(custom_agent_select).val($(custom_agent_hidden).val());
    Valipat.Agents.toggle_custom_agent_fields.call(custom_agent_select);
    if($(custom_agent_select).val() == '0'){$(this).parents('div.change-agent-a').find('p.fields input').val("");}
    return false;
  },

  show_custom_agent_box: function(){
    $('div.change-agent-a').hide();
    custom_agent_select = $(this).parents('td.agent-choice').find('select')[0];
    Valipat.Agents.toggle_custom_agent_fields.call(custom_agent_select);
    $(this).next('div.change-agent-a').fadeIn(300);
    return false;
  },

  toggle_custom_agent_fields: function(){
    if($(this).val() == '1'){
      $(this).parents('div.change-agent-a').find('p.fields').show();
      $(this).parents('div.change-agent-a').find('p.tick').show();
    }else{
      $(this).parents('div.change-agent-a').find('p.fields').hide();
      $(this).parents('div.change-agent-a').find('p.tick').hide();
    }
  },

  change_agent: function(){
    change_agent_box    = $(this).parents('div.change-agent-a')
    agent_fields        = change_agent_box.find('.fields input');
    agent_name          = $(agent_fields[0]).val();
    agent_email         = $(agent_fields[1]).val();
    custom_agent_select = change_agent_box.find('select')[0];

    if($(custom_agent_select).val() == '0' || (agent_name != "" && agent_email != "")){

      custom_agent_hidden = change_agent_box.find('input.custom-agent');
      $(custom_agent_hidden).val($(custom_agent_select).val());
      $(this).parents('td.agent-choice').find('a.change-agent').text($(custom_agent_select.options[custom_agent_select.selectedIndex]).text().substring(0,8));
      $(this).parents('div.change-agent-a').fadeOut(300);
      if($(custom_agent_select).val() == '0'){$(this).parents('div.change-agent-a').find('p.fields input').val("");}
    }else{
      Valipat.Agents.cancel.call($(this).parents('div.change-agent-a').find('a.cancel'));
    }
    return false;
  }
};

Valipat.SpecialRequests = {
  init: function(){
    $('div.first-annuities').hide();
    $('div.annuities').hide();
    $('input#first_annuities_choice').click(function(){ $('div.first-annuities').toggle(); });
    $('input#annuities_choice').click(function(){ $('div.annuities').toggle(); });
		$('input#user_external').click(function(){ $('div#user_approval_notification').toggle(); });
  }
};

Valipat.Powers = {
  init: function(){
    $("ul.ownership-changed").hide();
    $('input.ownership-changed[checked=checked]').each(function(){ $(this).parent().next('ul.ownership-changed').show(); });
    $('input.ownership-changed').click(function(){ $(this).parent().next('ul.ownership-changed').toggle(); });
  }
};

Valipat.Details = {
  init: function(){
    $('div.country-law-a').hide();
    $('a.country-law').click(function(){ $('div.country-law-a').hide(); $(this).next('div.country-law-a').toggle(); return false; });
    $('div.country-law-a a.cancel').click(function(){ $('div.country-law-a').hide(); return false; });

    $('div.saving-explanation-a').hide();
    $('a.saving-explanation').click(function(){ $('div.saving-explanation-a').hide(); $(this).next('div.saving-explanation-a').toggle(); return false; });
    $('div.saving-explanation-a a.cancel').click(function(){ $('div.saving-explanation-a').hide(); return false; });
    $('select.belgium.de-warning').change(function(){ Valipat.Details.check_belgium_language(this); });
  },

  check_belgium_language: function(select){
    if ($(select).find(':selected').val() == "de") {
      alert("IMPORTANT WARNING\n\nYour decision to validate this EP, filed prior to 13 December 2007, in the German language, is legally unsafe. According to the Official Journal EPO 5/1999 : \" it is for the Belgian courts to decide on the validity in Belgium of European Patents which have not been translated into French or Dutch\".\n\nIn the absence of such final decision by the Courts, we recommend to select either French or Dutch for this validation.");
    }
  }
};

Valipat.Contacts = {

  init: function(){
    $('a.open-contacts-list').live("click", Valipat.Contacts.show_contacts);
    $('a.open-parents-list').live("click", Valipat.Contacts.show_parents);
    $('a.open-company-list').live("click", Valipat.Contacts.show_companies);
    $('a.close-contacts-list').click(Valipat.Contacts.hide_list);
    $('a.close-parents-list').click(Valipat.Contacts.hide_list);
    $('a.close-companies-list').click(Valipat.Contacts.hide_list);
    $('a.delete-value').click(Valipat.Contacts.remove_value_line);
    $('div#contacts-ajax div.pagination a').live("click", Valipat.Contacts.navigate_contacts_pages);
    $('div#contacts-ajax a.select-contact').live("click", Valipat.Contacts.select_contact);
    $('div#overlay-contacts-table input[type=submit]').click(Valipat.Contacts.search_contacts);
    $('div#overlay-contacts-table input[type=text]').live("keyup", Valipat.Contacts.search_contacts);
    $('div#overlay-table-content-parents div.pagination a').live("click", Valipat.Contacts.navigate_parents_pages);
    $('div#overlay-table-content-companies div.pagination a').live("click", Valipat.Contacts.navigate_companies_pages);
    $('div#overlay-table-content-parents a.select-parent').live("click", Valipat.Contacts.select_parent);
    $('div#overlay-companies-table a.select-parent').live("click", Valipat.Contacts.select_company);
    $('div#overlay-parents-table input[type=submit]').click(Valipat.Contacts.search_parents);
    $('div#overlay-parents-table input[type=text]').live("keyup", Valipat.Contacts.search_parents);
    $('div#overlay-companies-table input[type=text]').live("keyup", Valipat.Contacts.search_companies);
    $('div#overlay-companies-table input[type=submit]').click(Valipat.Contacts.search_companies);
    $('span#inline-search-approved-contacts input[type=text]').live("keyup", Valipat.Contacts.request_search);
    $('div#requests-ajax a.select-request-contact').live("click", Valipat.Contacts.select_request_contact);
    $('a#copy-contact-info').click(Valipat.Contacts.copy_from_user_to_contact);
    $('a.unset-parent').live("click", Valipat.Contacts.unset_parent);
    $('a.unset-parent-as-person').live("click", Valipat.Contacts.unset_parent_as_person);
  },

  show_contacts: function() {
    $('div#overlay-contacts-table input[type=submit]').val("")
    $('#overlay-table-content-contacts').load("/admin/contacts/companies.js");
    $.blockUI({ message: $('#overlay-contacts-table'), css: { width: '800px', top: '100px', left: '100px' } });
    return false;
  },

  hide_list: function() {
    $.unblockUI();
    return false;
  },

  show_parents: function() {
    $('div#overlay-parents-table input[type=submit]').val("")
    $('#overlay-table-content-parents').load("/admin/contacts/parents.js");
    $.blockUI({ message: $('#overlay-parents-table'), css: { width: '800px', top: '100px', left: '100px' } });
    return false;
  },

  show_companies: function() {
    $('div#overlay-companies-table input[type=submit]').val("")
    $('#overlay-table-content-companies').load("/admin/contacts/parents.js");
    $.blockUI({ message: $('#overlay-companies-table'), css: { width: '800px', top: '100px', left: '100px' } });
    return false;
  },

  remove_value_line: function() {
    $(this).parents("div.value-container").animate({
            opacity: 0,
            height: '0px'
          }, 400 );
    $(this).parents("div.value-container").children("input.delete").val("1");
    return false;
  },

  navigate_contacts_pages: function() {
    $('#overlay-table-content-contacts').load(this.href);
    return false;
  },

  navigate_parents_pages: function() {
    $('#overlay-table-content-parents').load(this.href);
    return false;
  },

  navigate_companies_pages: function() {
    $('#overlay-table-content-companies').load(this.href);
    return false;
  },

  select_contact: function() {
    $.post("/admin/contacts",
           { child_id: this.id, parent_id: $("div#overlay-contacts-table input#parent_id").val() },
           function (data, textStatus) {
              //$("#sidebar").load("/admin/contacts/companies/" + $("input#parent_id").val() + ".js");
              //$.unblockUI();
							location.reload();
           });
    return false;
  },

  select_parent: function() {
    $.post("/admin/contacts/parents",
           { child_id: this.id, parent_id: $("div#overlay-parents-table input#parent_id").val() },
           function (data, textStatus) {
              //$("#sidebar").load("/admin/contacts/companies/" + $("input#parent_id").val() + ".js");
              //$.unblockUI();
							location.reload();
           });
    return false;
  },

  select_company: function() {
		selected_id = this.id
    $.post("/admin/contacts/parents",
           { child_id: this.id },
           function (data, textStatus) {
 	       			$("input[type=hidden]#contact_parent_id").val(selected_id);
 	       			// $("span#current_selected_company").text(data.name);
							$("#company_details").html(data);
	       			$.unblockUI();
           });
    return false;
  },

  unset_parent:function() {
    $.post(this.href,
           { _method: "delete" },
           function (data, textStatus) {
              $("#sidebar").load("/admin/contacts/companies/" + $("a.unset-parent").attr("id") + ".js");
           });
    return false;
  },

	unset_parent_as_person:function() {
	  $.post(this.href,
	         { _method: "delete" },
	         function (data, textStatus) {
	            $("#sidebar").load("/admin/contacts/people/" + $("a.unset-parent-as-person").attr("id") + ".js");
	         });
	  return false;
	},

  search_contacts: function() {
    $.get("/admin/contacts/companies.js",
           { search: $('div#overlay-contacts-table input[type=text]').val() },
           function (data, textStatus) {
              $('#overlay-table-content-contacts').html(data);
           });
    return false;
  },

  select_request_contact: function() {
    $("#legal_entity_new").attr("checked", false);
    $("#legal_entity_existing").attr("checked", true);
    $("#selected_company_id").val(this.id);
    $("tr.selected").removeClass("selected");
    $(this).parent().parent().addClass("selected");
    return false;
  },

  search_parents: function() {
    $.get("/admin/contacts/parents.js",
           { search: $('div#overlay-parents-table input[type=text]').val() },
           function (data, textStatus) {
              $('#overlay-table-content-parents').html(data);
           });
    return false;
  },

  search_companies: function() {
    $.get("/admin/contacts/parents.js",
           { search: $('div#overlay-companies-table input[type=text]').val() },
           function (data, textStatus) {
              $('#overlay-table-content-companies').html(data);
           });
    return false;
  },

  request_search: function() {
    $.get("/admin/requests/" + $('#current_user_id').val() + "/edit.js",
       { search: $('input[type=text]').val() },
       function (data, textStatus) {
          $('#approved-contacts-table').html(data);
       });
    return false;
  },

  copy_from_user_to_contact: function() {
    $("div#replaceable-contact-form").load("/admin/contacts/" + $("#current_contact_id").val() + "/edit.js");
    return false;
  }
}

Valipat.UserSessions = {
  init: function() {
    $("#login-failed").hide();
    $('#new_user_session').submit(Valipat.UserSessions.login);
    $('#reset_password').submit(Valipat.UserSessions.reset_passwd);
  },

  login: function() {
    $("#login-failed").hide();
    url = '/user_sessions';
    data = $("#new_user_session").serialize();
    $.ajax({ url: url,
             type: 'POST',
             data: data,
             dataType: 'text',
             success: function(xhr) { document.location = '/user_sessions'; },
             error: function(xhr) {
               if (xhr.status == 403) { $("#login-failed").show(); }
               else { alert('Unknown error, please try again. (' + xhr.status + ')'); }
             }
    });
    return false;
  },

  reset_passwd: function() {
    $('#lost-pass-box').hide();
    url = '/password_resets';
    data = $("#reset_password").serialize();
    $.ajax({ url: url,
             type: 'POST',
             data: data,
             dataType: 'text',
             success: function(xhr) { $('#new-pass-sent-box').show(); },
             error: function(xhr) {
    alert('An error occured, please try again.');
               $('#lost-pass-box').show();
             }
    });
    return false;
  },

  show_reset_password_box: function() {
    $('#login-box').hide();
    $('#lost-pass-box').show();
    return false;
  },

  hide_reset_password_box: function() {
    $('#lost-pass-box').hide();
    $('#login-box').show();
    return false;
  }
};

Valipat.Invoices = {
/*  init: function(){
    $('a.remove-invoice-line').live("click", Valipat.Invoices.remove_line);
    $('tr.invoice-input input[type=submit]').click(Valipat.Invoices.add_line);
    $('input[type=checkbox].disable-invoice-line').click(Valipat.Invoices.enable_disable_line);
    $('input[type=checkbox].select-all-lines').click(Valipat.Invoices.select_all_none_lines);

		$('div#invoice input[type=text][name*=official]').live("keyup", Valipat.Invoices.change_line);
		$('div#invoice input[type=text][name*=service]').live("keyup", Valipat.Invoices.change_line);
		$('div#invoice input[type=text][name*=translation]').live("keyup", Valipat.Invoices.change_line);

    $('input[type=checkbox].select-all-lines').each(function(e) {
      all_checked = true;
      $("div#invoice tr." + $(this).val() + "-line input[type=checkbox]").each(function (i) {
        if (!$(this).attr("checked")) {
          all_checked = false;
          return;
        }
      });
      if (all_checked) {
        $(this).attr("checked", "checked");
      } else {
        $(this).attr("checked", "");
      }
    });
  },

  enable_disable_line: function() {
    if ($(this).attr("checked")) {
      $(this).parents("tr").removeClass("disabled-line");
    } else {
      $(this).parents("tr").addClass("disabled-line");
    }
  },

  select_all_none_lines: function() {
    if ($(this).attr("checked")) {
      $("div#invoice tr." + $(this).val() + "-line").removeClass("disabled-line");
      $("div#invoice tr." + $(this).val() + "-line input[type=checkbox]").attr("checked", "checked");
    } else {
      $("div#invoice tr." + $(this).val() + "-line").addClass("disabled-line");
      $("div#invoice tr." + $(this).val() + "-line input[type=checkbox]").attr("checked", "");
    }

  },

	remove_line: function() {
		$(this).parents("tr").remove();
		return false;
	},

	add_line: function() {
		official_float = parseFloat($("tr.invoice-input input[type=text][name*=official]").val());
		official_float = isNaN(official_float) ? 0 : parseInt(official_float.toFixed(0));
		service_float = parseFloat($("tr.invoice-input input[type=text][name*=service]").val());
		service_float = isNaN(service_float) ? 0 : parseInt(service_float.toFixed(0));
		translation_float = parseFloat($("tr.invoice-input input[type=text][name*=translation]").val());
		translation_float = isNaN(translation_float) ? 0 : parseInt(translation_float.toFixed(0));
		sum = official_float + service_float + translation_float;
		sum = sum.toFixed(0);
		type_field = $.create("input").attr("type", "hidden").attr("name", "invoice[custom_lines][][type]").val("other");
		label_field = $.create("input").attr("type", "text").attr("name", "invoice[custom_lines][][label]").val($("tr.invoice-input input[type=text][name*=label]").val()).attr("style", "width: 385px");
		official_field = $.create("input").attr("type", "text").attr("name", "invoice[custom_lines][][official]").addClass("money").val(official_float).attr("style", "width: 60px");
		service_field = $.create("input").attr("type", "text").attr("name", "invoice[custom_lines][][service]").addClass("money").val(service_float).attr("style", "width: 60px");
		translation_field = $.create("input").attr("type", "text").attr("name", "invoice[custom_lines][][translation]").addClass("money").val(translation_float).attr("style", "width: 60px");
		total_field = $.create("input").attr("type", "hidden").attr("name", "invoice[custom_lines][][total]").val(sum);
		remove_link = $.create("a").attr("href", "#").addClass("remove-invoice-line").html("remove");

		$("tr.invoice-input").before(
			$.create("tr")
				.append($.create("td"))
				.append($.create("td").append(type_field).append(label_field))
				.append($.create("td").addClass("money").append(official_field))
				.append($.create("td").addClass("money").append(service_field))
				.append($.create("td").addClass("money").append(translation_field))
				.append($.create("td").text(sum).addClass("money").append(total_field))
				.append($.create("td").append(remove_link))
		)
		$("tr.invoice-input input[type=hidden]").val("other");
		$("tr.invoice-input input[type=text][name*=label]").val("");
		$("tr.invoice-input input[type=text][name*=official]").val("");
		$("tr.invoice-input input[type=text][name*=service]").val("");
		$("tr.invoice-input input[type=text][name*=translation]").val("");
		$("tr.invoice-input td:last").prev().text("");

		return false;
	}	,

	change_line: function() {
		official_float = parseFloat($(this).parents("tr").find("input[type=text][name*=official]").val());
		official_float = isNaN(official_float) ? 0 : parseInt(official_float.toFixed(0));
		service_float = parseFloat($(this).parents("tr").find("input[type=text][name*=service]").val());
		service_float = isNaN(service_float) ? 0 : parseInt(service_float.toFixed(0));
		translation_float = parseFloat($(this).parents("tr").find("input[type=text][name*=translation]").val());
		translation_float = isNaN(translation_float) ? 0 : parseInt(translation_float.toFixed(0));
		sum = official_float + service_float + translation_float;
		sum = sum.toFixed(0);
		total_field = $.create("input").attr("type", "hidden").attr("name", "credit_note[lines][][total]").val(sum);
		$(this).parents("tr").find("td:last").prev().text(sum).append(total_field);
		return false;
	}
*/
};

Valipat.Search = {

	init: function() {
		$("input[type=submit]#query-search").click(Valipat.Search.quick);
	},

	quick: function() {
		var field = $("input[type=text]#query");
	  $("div#search-results").html("<table><tr><td>Searching...</td></tr></table>");
	        $("div#search-results").load(
			field.parents("form").attr("action") + ".js",
			field.serialize()
		);
		return false;
	}

};

Valipat.CreditNotes = {
  init: function(){
    $('a.remove-credit-note-line').live("click", Valipat.CreditNotes.remove_line);
    $('tr.credit-note-input input[type=submit]').click(Valipat.CreditNotes.add_line);

		$('div#credit-note input[type=text][name*=official]').live("keyup", Valipat.CreditNotes.change_line);
		$('div#credit-note input[type=text][name*=service]').live("keyup", Valipat.CreditNotes.change_line);
		$('div#credit-note input[type=text][name*=translation]').live("keyup", Valipat.CreditNotes.change_line);
  },

  remove_line: function() {
    $(this).parents("tr").remove();
    return false;
  },

  add_line: function() {
    official_float = parseFloat($("tr.credit-note-input input[type=text][name*=official]").val());
		official_float = isNaN(official_float) ? 0 : parseInt(official_float.toFixed(0));
		service_float = parseFloat($("tr.credit-note-input input[type=text][name*=service]").val());
		service_float = isNaN(service_float) ? 0 : parseInt(service_float.toFixed(0));
		translation_float = parseFloat($("tr.credit-note-input input[type=text][name*=translation]").val());
		translation_float = isNaN(translation_float) ? 0 : parseInt(translation_float.toFixed(0));
		sum = official_float + service_float + translation_float;
		sum = sum.toFixed(0);
		type_field = $.create("input").attr("type", "hidden").attr("name", "credit_note[lines][][type]").val($("tr.credit-note-input input[type=hidden]").val());
    label_field = $.create("input").attr("type", "text").attr("name", "credit_note[lines][][label]").val($("tr.credit-note-input input[type=text][name*=label]").val()).attr("style", "width: 385px");
    official_field = $.create("input").attr("type", "text").attr("name", "credit_note[lines][][official]").addClass("money").val(official_float).attr("style", "width: 60px");
    service_field = $.create("input").attr("type", "text").attr("name", "credit_note[lines][][service]").addClass("money").val(service_float).attr("style", "width: 60px");
    translation_field = $.create("input").attr("type", "text").attr("name", "credit_note[lines][][translation]").addClass("money").val(translation_float).attr("style", "width: 60px");
    total_field = $.create("input").attr("type", "hidden").attr("name", "credit_note[lines][][total]").val(sum);
    remove_link = $.create("a").attr("href", "#").addClass("remove-credit-note-line").html("remove");

    $("tr.credit-note-input").before(
      $.create("tr")
        .append($.create("td").append(type_field).append(label_field))
        .append($.create("td").addClass("money").append(official_field))
        .append($.create("td").addClass("money").append(service_field))
        .append($.create("td").addClass("money").append(translation_field))
        .append($.create("td").text(sum).addClass("money").append(total_field))
        .append($.create("td").append(remove_link))
    )
    $("tr.credit-note-input input[type=hidden]").val("other");
    $("tr.credit-note-input input[type=text][name*=label]").val("");
    $("tr.credit-note-input input[type=text][name*=official]").val("");
    $("tr.credit-note-input input[type=text][name*=service]").val("");
    $("tr.credit-note-input input[type=text][name*=translation]").val("");
		$("tr.credit-note-input td:last").prev().text("");
    return false;
  },

	change_line: function() {
		official_float = parseFloat($(this).parents("tr").find("input[type=text][name*=official]").val());
		official_float = isNaN(official_float) ? 0 : official_float;
		service_float = parseFloat($(this).parents("tr").find("input[type=text][name*=service]").val());
		service_float = isNaN(service_float) ? 0 : service_float;
		translation_float = parseFloat($(this).parents("tr").find("input[type=text][name*=translation]").val());
		translation_float = isNaN(translation_float) ? 0 : translation_float;
		sum = official_float + service_float + translation_float;
		sum = sum.toFixed(0);
		total_field = $.create("input").attr("type", "hidden").attr("name", "credit_note[lines][][total]").val(sum);
		$(this).parents("tr").find("td:last").prev().text(sum).append(total_field);
		return false;
	}
};

Valipat.Workflows = {

	init: function() {
		$("form#country-selection select[name=country]").live("change", function() { $("form#country-selection").submit() });
		$("form#country-selection input[type=submit]").remove();
	}

};

Valipat.Requests = {

  init: function(){
    $('a#reject-request').click(Valipat.Requests.open_reject_form);
  },

	open_reject_form: function() {
		$("div#reject-form").slideDown("normal", function() {
			$.scrollTo("input[type=submit][name=reject]", 500);
		});
		return false;
	}

};

var Engine = {
  utils : {
    links : function(){
      $('a[rel*=external]').click(function(e){
          e.preventDefault();
          window.open($(this).attr('href'));
        });
    },
    mails : function(){
      $('a[href^=mailto:]').each(function(){
          var mail = $(this).attr('href').replace('mailto:','');
          var replaced = mail.replace('/at/','@');
          $(this).attr('href','mailto:'+replaced);
          if($(this).text() == mail) {
            $(this).text(replaced);
          }
        });
    }
  }
};

$(Valipat.init);
