//general functionality
//set the today's date as the default value 
$.fn.todayAsDefault = function(){
  Date.format = "yyyy-mm-dd";
  var today = new Date();
  if($(this).val() == "") { $(this).val(today.asString()); }
};

$.fn.setDefaultDate = function(default_date){
  Date.format = "yyyy-mm-dd";
  //var today = new Date();
  if($(this).val() == "") { $(this).val(default_date.asString()); }
};


$.fn.deleteAction = function(link) {
    var form = $("<form method='post' style='display:none'></form>");

    form.attr("action", $(link).attr('href'));
    $("<input type='hidden'/>").attr("name", "_method")
                             .attr("value", "delete")
                             .appendTo(form);

    $("<input type='hidden'/>").attr("name", "authenticity_token")
                             .attr("value", AUTH_TOKEN)
                             .appendTo(form);
    
    $("body").append(form);

    form.trigger("submit");
};

$.fn.clickableRow = function(link_class){
  clickable_url = $(this).find('.clickable_url a').attr('href');
  document.location = clickable_url;
};

$(function() {
      datepicker_extension = "";

      if($(".invoiceable_form").length > 0){ 
      //dates specific
      datepicker_extension = { onSelect : function(date){ Invoice.calcDueDate($(".due_date_select").val(), date)}}; 
      $("div#custom_due_container").hide();
      $(".due_date_select").change(Invoice.showDueDate);

      //line items fields 
      $(".line_item .description, #invoice_notes").autogrow();
      //put a placeholder for line item description field
      //$(".line_item .description").form_prompt("Type item name to find existing or enter details for a new", { className: 'searchPrompt'} )
      if($(".line_item .description").length > 0)
        Invoice.suggestItems(".line_item .description");
      
      if($(".line_item").length <= 0) Invoice.addItem();
      $(".line_item input.numeric").livequery("blur", Invoice.setLineTotal);
      //set the invoice line total on load
      Invoice.setLineTotal.call($(".line_item:first").find("input.numeric:first"));
      $("#add_item").click(Invoice.addItem);
      $(".line_action_image a").live("click", Invoice.showLineActions);

      $(".delete_line").livequery("click", Invoice.removeItem)
      $(".save_line").livequery("click", Invoice.saveItem);

      //line items sortable
      $("#line_items").sortable({
        items: '.line_item',
        containment: 'parent',
        cursor: 'move',
        update: Invoice.updateItemSortOrder,
        handle: 'td.draggable',
        opacity: 0.6
      });

      //tax and discount fields
      $("input#invoice_discount, input#invoice_tax, input#invoice_tax2, input#invoice_shipping").change(Invoice.updateFinalTotal); 

      //client fields
      $("a#new_client_link").click(Invoice.showNewClient);
      if($("#suggest_client_field").length > 0)
        Invoice.suggestClients();
      $("#suggest_client_field").blur(function(ev){
        if($(this).next(".suggestion_results_list").css("display") == "none"){
          if($(this).val().length < 3 || ($("#selected_client_details").css("display") != "none"))
            return false;

          Invoice.showNewClient();
          $(this).unbind(ev);
        }  
      });
      
      //recurring profile fields
      $("div#custom_frequency").hide();
      $("#invoice_frequency").change(RecurringProfile.showCustomFrequency);

    }
        
      $(".date_field").datepicker($.extend({dateFormat: 'yy-mm-dd', showOn: 'both', duration: '', buttonImage: '/images/calendar.png', buttonImageOnly: true }, datepicker_extension))
                    .setDefaultDate(new Date());

      recurring_start_date = new Date();
      recurring_start_date.setDate(recurring_start_date.getDate()+1);

      $(".recurring_date_field").datepicker($.extend({dateFormat: 'yy-mm-dd', showOn: 'both', duration: '', buttonImage: '/images/calendar.png', buttonImageOnly: true, minDate: recurring_start_date }, datepicker_extension))
                    .setDefaultDate(recurring_start_date);

    /* Clients section */
    //load client summaries using AJAX
    $("ul#client_summary_links a").click(Client.showTable);
    $("ul#client_summary_links a[rel*=invoice]").trigger("click");
    
     /* Logos & Colors */
    //AJAX uploading
    $("input.uploader").change(function(){
      $("input#ajax_upload").val("true");
      options = {
        beforeSubmit: function(formData){
          $("img#loader").show();
        },
        success: function(response){
          $("img#loader").hide(); 
          processed_response = eval(response);
          if($.isArray(processed_response[0]))
            $.each(processed_response, function(){
              alert(this[1]);
            });
          else
            $("#vendor_logo h2").html("<img src='" + processed_response[0] + "' alt='Your Logo'/>");
        }
      }
      $(this).closest("form").ajaxSubmit(options);
    });

    $("form#branding_form").submit(function(){
      $("input#ajax_upload").val("false");
    });

    $('.simple_color').colorPicker();
    $('#branding_background_color').change(function(){
       $("#live_preview").css("background-color", $(this).val()); 
    });

    $('#branding_title_color').change(function(){
        $("#branding_preview #vendor_ddress").css("color", $(this).val()); 
    });

    $('#branding_header_color').change(function(){
      $("#branding_preview #invoice_header").css("background-color", $(this).val()); 
    });

    //Invoice row click anywhere
   $('tr.invoice').livequery("click", $.fn.clickableRow);
   $('tr.estimate').livequery("click", $.fn.clickableRow);
   $('tr.recurring_profile').livequery("click", $.fn.clickableRow);
 
  //set placeholders
  $("textarea[placeholder], input[placeholder]").placeholder();

  $("input#query_q").attr("disabled", "disabled")

  $("div#invoice_filter input#query_q").keyup(function(){
      Search.results(this, "invoice", ["client.name", "invoice_no", "state"]);
  });

  $("div#estimate_filter input#query_q").keyup(function(){
      Search.results(this, "estimate", ["client.name", "estimate_no", "state"]);
  });

  $("div#recurring_filter input#query_q").keyup(function(){
      Search.results(this, "recurring_profile", ["client.name", "profile_name", "frequency_term"]);
  });

  $("div#item_filter input#query_q").keyup(function(){
      Search.results(this, "item", ["name", "units", "price"]);
  });

  $("div#client_filter input#query_q").keyup(function(){
      Search.results(this, "client", ["name", "address", "email"]);
  });

  //create item form units
  $("#item_units").change(function(){
      if($(this).val() == "other"){
       $(this).attr("name", "units_other");
       $(this).after("<input type='text' name='item[units]' id='item_units_other'/>");     
      }
      else {
        $("#item_units_other").remove();
      }
  });

  //Email Template Placeholders
  $("span.placeholders a").click(function(){
      target = $(this).closest("span").next("textarea");
      $(target).replaceSelection("{{" + $(this).text() + "}}", true);    
      return false
  });

  //general delete function of rails for dynamically rendered objects
  $("a.delete").attr("rel", "nofollow");
  $('.item a.delete').livequery('click', function(){
      if(confirm("Are you sure you want to delete this item? This will not effect existing invoices."))
        $.fn.deleteAction(this);

      return false
  });

  $('.user a.delete').livequery('click', function(){
      if(confirm("Are you sure you want to delete this user? This action cannot be revert. All user data will be cleared."))
        $.fn.deleteAction(this);

      return false
  });

  $('.subscription a.delete').livequery('click', function(){
      if(confirm("Are you sure you want to disable this subscription? This action cannot be revert. All user data will be cleared."))
        $.fn.deleteAction(this);

      return false
  });

  $('.client dd a.delete').livequery('click', function(){
      if(confirm("Are you sure you want to delete this client? This will not effect existing invoices."))
        $.fn.deleteAction(this);

      return false
  });

 $('.contact a.delete').click(function(){
      if(confirm("Are you sure you want to delete this contact?"))
        $.fn.deleteAction(this);

      return false
  });

  $("#delete_invoice_link").click(function(){ 
     if(confirm("Are you sure you want to delete this invoice?"))
      $.fn.deleteAction(this);

     return false
  });
  
  $("#close_invoice_link").click(function(){ 
     if(!confirm("Are you sure you want to close this invoice?"))
      return false;
  });

  $("#close_estimate_link").click(function(){ 
     if(!confirm("Are you sure you want to close this estimate?"))
      return false;
  });

  $("#delete_estimate_link").click(function(){ 
     if(confirm("Are you sure you want to delete this estimate?"))
      $.fn.deleteAction(this);

     return false
  });

  $("#delete_client_link a.delete").click(function(){
      if(confirm("Are you sure you want to delete this client? This will not effect existing invoices."))
        $.fn.deleteAction(this);

      return false
  });

  $('.recurring_profile a.delete').livequery('click', function(){
      if(confirm("Are you sure you want to delete this profile?"))
        $.fn.deleteAction(this);

      return false
  });

  $("#sign_out_link a").click(function(){ $.fn.deleteAction(this); return false });

  //system preferences toggle
  var enableDisableSettings = function(){ 
      if($(this).attr("checked") == true){
        var settings_row = $(this).closest('div.settings_row');
        settings_row.find("input").not(".setting_enable, input[type=hidden]").attr("disabled", "");
        settings_row.find("label").css("color", "");
      }
      else {
        var settings_row = $(this).closest('div.settings_row');
        settings_row.find("input").not(".setting_enable, input[type=hidden]").attr("disabled", "disabled");
        settings_row.find("label").css("color", "#CCC");
      }
  };

  $("fieldset#settings_discounts_taxes input.setting_enable").bind("click", enableDisableSettings);
  $("fieldset#settings_discounts_taxes input.setting_enable").each(function(){ enableDisableSettings.call(this) });

  //subscription page 

  update_subscription_charges = function(){
      $.post("/subscription_profiles/calculate", $("#subscription_form").serialize(), function(data){
        $("li#immediate_price span.price").html("$" + data.immediate_charge)
        $("li#scheduled_price span.price").html("$" + data.scheduled_charge)
        $("li#scheduled_price span.periodicity").html(data.periodicity)
        $("li#scheduled_price span.next_billing_date").html(data.next_billing_date)
      }, "json");
  };

  bind_confirmation_on_unload = function(){
    if($("div.no_payment_method").length > 0)
      window.onbeforeunload = function() { return "Your upgrade process is not completed. Leaving the page without completing the process will discard those changes." };
  }

  unbind_confirmation_on_unload = function(){
    window.onbeforeunload = null;
  }

  $("a.toggle_details").click(function(){
    $(this).html() == "Show Details" ? $(this).html("Hide Details") : $(this).html("Show Details");
    $(this).parents("div.module_title").nextAll(".upgrade_details").toggle(); 
    return false    
  })

  $("#subscription_profile_billing_cycle_monthly").click(function(){
     $("h4.yearly").hide(); 
     $("h4.monthly").show(); 
     $("#subscription_profile_payment_method_paypal").attr("disabled", "disabled");
  //  update_subscription_charges()
  });

  $("#subscription_profile_billing_cycle_yearly").click(function(){
     $("h4.yearly").show(); 
     $("h4.monthly").hide(); 
     $("#subscription_profile_payment_method_paypal").attr("disabled", "");
  //   update_subscription_charges()
  });

  $("a.subscription_enable").click(function(){
     this_button = this
     $.post($(this).attr("href"), {}, function(data){

       //change current button to disable
       $(this_button).addClass("hide");
       $(this_button).next("a.subscription_disable").removeClass("hide");
       $(this_button).prevAll(".module_status_text").html("Pending");

       //activate any greyed buttons
       parent_tag = $(this_button).parent("div#subscription_1");
       if(parent_tag.length > 0){
         $("div.upgrade_buttons").each(function(i){
           if($(this).attr("id") != $(parent_tag).attr("id")){
            $(this).children("a.subscription_enable").removeClass("hide")
            $(this).children("img.subscription_grey").addClass("hide")
            $(this).children(".module_status_text").text("Inactive");
           }
         });
       }

 //      update_subscription_charges();
       bind_confirmation_on_unload();
     }, "json");

     return false
  });

  $("a.subscription_disable").click(function(){
    this_button = this
    if(confirm("You are about to disable a module which will be deactivated from your account. Features and functions associated with this module will no longer be active. You want to continue?")) {

      $.post($(this).attr("href"), {"_method": "delete"}, function(data){
       //change current button to enable
       $(this_button).addClass("hide");
       $(this_button).prev("a.subscription_enable").removeClass("hide");
       $(this_button).prevAll(".module_status_text").html("Inactive");

       //deactivate buttons
       parent_tag = $(this_button).parent("div#subscription_1");
       if(parent_tag.length > 0){
         $("div.upgrade_buttons").each(function(i){
           if($(this).attr("id") != $(parent_tag).attr("id")){
            $(this).children("a.subscription_enable").addClass("hide")
            $(this).children("a.subscription_disable").addClass("hide")
            $(this).children(".module_status_text").text("Pro Required");
           }
         });
       }
//      update_subscription_charges();
       bind_confirmation_on_unload();
     }, "json");

    }

    return false     
  });

  $("#subscription_changes_submit").click(function(){
    unbind_confirmation_on_unload();     
  })

  //payment screen - disable after click
 $("#authnet_process_card").click(function(){ $(this).attr("disabled", "disabled"); })


  //open links in new window
  $('a[rel*=external]').click(function(){
     window.open($(this).attr("href"), "_blank"); 
     return false
  });

  //open links in facebox
  $('a[rel*=facebox]').each(function(){$(this).facebox()});

  //show date picker
  $('a[rel*=facebox]').ajaxComplete(function(){
      if($("#payment_date").length > 0)
        $("#payment_date").datepicker({dateFormat: 'yy-mm-dd', showOn: 'button', duration: '', buttonImage: '/images/calendar.png', buttonImageOnly: true }).todayAsDefault();
      if($(".editable").length > 0)
        $(".editable").inlineEdit();
  });

  $("#facebox span.cancel a").livequery('click', function(){ $.facebox.close(); return false });

  //tooltips
  $('a[rel*=tip]').each(function() // Select all elements with the "tooltip" attribute
    {
      $(this).qtip({ 
        content: $(this).attr('data-tip'),
        style: { 
          name: 'cream',
          background: '#FFFFAA',
          color: '#333333',
          'font-size': 11,
          width: 200,
          tip: 'leftTop'
        }
      }); // Retrieve the tooltip attribute value from the current element
      $(this).bind("click", function(){ return false; })
    });

  //show time ago in words helper
  $('abbr[class*=timeago]').timeago();

  //editable fields
  $('.editable').inlineEdit();
});

