// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var PagerDuty = {
  Help: {
    toggleGettingStartedSection: function(speed) {
      speed = typeof(speed) != 'undefined' ? speed : 'normal';
      if ($j("div.help_toggle").hasClass("toggle_closed")) {
        $j("div.section_help").slideDown(speed);
        $j("div.help_toggle").removeClass("toggle_closed").addClass("toggle_open");
      } else {
        $j("div.section_help").slideUp(speed);
        $j("div.help_toggle").removeClass("toggle_open").addClass("toggle_closed");
      }
    }
  }
};

/* create PD only if it is not initialized */
var pd = pd || {};

pd.utils = {
  /**
   * In IE7, a bug that causes the click events on radio and checkboxes to be never fired
   * until another event occurs.
   * This function is idempotent, thus can be safely called multiple times
   */
  fixIEEventBindingIssue: function(){
    /** fix the IE7 event firing problem with radio and checkbox buttons
    * REF: http://www.opensourcery.com/blog/chad-granum/ie-onchange-events 
    * NOTE: click will not work anymore with this fix for IE
    */
    if ($j.browser.msie) {
      //unbind old events
      $j("input[type='radio']").unbind('click');
      $j("input[type='checkbox']").unbind('click');
      //bind the events
      $j("input[type='radio']").bind('click', function(){
        $j(this).trigger('change');
      });
      $j("input[type='checkbox']").bind('click', function(){
        $j(this).trigger('change');
      });
    }
  },
  
  /**
   * Convert an object into a query string
   */
  objectToQueryString: function(anObject) {
    var queryStrings = [];
    for (var name in anObject) {
      if (anObject[name]) {
        queryStrings.push(encodeURIComponent(name) + "=" + encodeURIComponent(anObject[name]));
      }
    }
    return queryStrings.join("&");
  }
};


/**
 * =========================================
 * Monitoring Services 
 * =========================================
 */ 
pd.services = {
  
  //----------------------------------------------------------------------------
  // NEW MONITORING SERVICES PAGE
  //----------------------------------------------------------------------------
  
  toggleTriggerEmailSection: function(){
    var checkedServiceType = $j("input[name='service[type]']:radio:checked");
    if(checkedServiceType.val() && checkedServiceType.val()=="GenericEmailService") {
      // integration email text field should be shown
      $j("#integration_email_container input").attr("disabled", false)
      $j("#integration_email_container:hidden").fadeIn("fast");
      this.updateEmailAddress();
    } else {
      // integration email should be hidden all the time
      $j("#integration_email_container input").attr("disabled", true)
      $j("#integration_email_container:visible").fadeOut();
    }
  },
  /**
   * Update email address based on the service name field
   */
  updateEmailAddress: function(){
    var serviceName = $j("#service_name").val();
    $j("#service_email_address").val(this.stripNonAlphanumericsAndDasherize(serviceName));
  },
  
  /**
   * Remove non-alphanumeric characters from the short description
   * @param {Object} str
   */
  stripNonAlphanumericsAndDasherize: function(str){
    if (str != null) {
      str = str.strip().toLowerCase();
      str = str.gsub(/\s/, '-');      // dasherize
      str = str.gsub(/[^\w.\-]/, ''); // remove non-email-address characters
      str = str.gsub(/-+/, '-');      // remove consecutive blocks on -
    }
    return str;
  },
  
  //----------------------------------------------------------------------------
  // EDIT MONITORING SERVICES PAGE
  //----------------------------------------------------------------------------

  triggerRuleShowHideBox: function(comboBox) {
    var textBox = $j(comboBox).parent().next().find('input');
    if (comboBox.value == "always") {
      textBox.hide();
    }
    else {
      textBox.show();
    }
  },
  emailRulesShowHide: function(comboBox) {
    var d = $j("div#email_rules");
    if (comboBox.value == "or-rules-email" || comboBox.value == "and-rules-email") {
      d.show();
    }
    else {
      d.hide();
    }
  },
  toggleTriggerDeleteLinks: function() {
    var triggers = $j(".single_rule:visible");
    var delete_links = $j(".trigger_delete_link");
    if (triggers.length > 1) {
      delete_links.show();
    }
    else {
      delete_links.hide();
    }
  },
  deleteTrigger: function(trigger) {
    var t = $j(trigger);
    t.siblings("input").val('1');
    t.parents("td.single_rule").hide();
    pd.services.toggleTriggerDeleteLinks();
  },
  
  /**
   * Show warning message when status changes from enabled to disabled
   * @param {Object} comboBox
   */
  statusChange: function(comboBox) {
    if ($j(comboBox).val() == "true") {
      $j("#disabled_warning").hide();
    } else {
      $j("#disabled_warning").show();
    }
  },

  autoResolveChanged: function() {
    var autoResolveOn = $j("#auto_resolve_timeout_enabled").attr("checked");
    $j("#auto_resolve_subform").toggleClass("disabled_frm", !autoResolveOn);
    this.toggleEnabled($j("#service_auto_resolve_timeout"), autoResolveOn);
    this.toggleEnabled($j("#service_auto_resolve_timeout_hidden"), !autoResolveOn);
  },

  ackTimeoutChanged: function() {
    var ackTimeoutOn = $j("#ack_timeout_enabled").attr("checked");
    $j("#ack_subform").toggleClass("disabled_frm", !ackTimeoutOn);
    this.toggleEnabled($j("#service_acknowledgement_timeout"), ackTimeoutOn);
    this.toggleEnabled($j("#service_acknowledgement_timeout_hidden"), !ackTimeoutOn);
  },

  toggleEnabled: function(element, enable) {
    if (enable) {
      $j(element).removeAttr("disabled");
    } else {
      $j(element).attr("disabled", true);
    }
  }
};

pd.billing = {
  toggleIconForDiscountCodeLink: function() {
    if ($j("#discount_code_container div.expandable_content:visible").length > 0) {
      $j("#discount_code_container a.expandable").addClass("expanded");
    } else {
      $j("#discount_code_container a.expandable").removeClass("expanded");
    }
  },
  addClickHandlerToDiscountCodeLink: function() {
    $j("#discount_code_container a.expandable").bind("click", function(eventObject){
      var content = $j("#discount_code_container div.expandable_content");
      if (content.is(":hidden")) {
        content.show();
        $j(eventObject.target).addClass("expanded");
      } else {
        content.hide();
        $j(eventObject.target).removeClass("expanded");
      }
      return false;
    });
  },
  validateDiscountCode: function() {
    var path = $j("#code_check_url").val();
    var fullUrl = path + "?discount_code=" + encodeURIComponent($j("#discount_code").val());
    $j.getScript(fullUrl, function(){});
  }
};

//fix IEEventBindingIssue
$j(function(){
  pd.utils.fixIEEventBindingIssue();
});
