? 541926.patch
Index: codeless_discounts_field/codeless_discounts_field.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_discounts_alt/codeless_discounts_field/codeless_discounts_field.install,v
retrieving revision 1.2
diff -u -p -r1.2 codeless_discounts_field.install
--- codeless_discounts_field/codeless_discounts_field.install	21 Feb 2009 19:28:06 -0000	1.2
+++ codeless_discounts_field/codeless_discounts_field.install	20 Aug 2009 22:09:28 -0000
@@ -1,6 +1,7 @@
 <?php
 //$Id: codeless_discounts_field.install,v 1.2 2009/02/21 19:28:06 ryangroe Exp $
 
+
 /**
  * @file
  * Install hooks for codeless_discounts_field.module.
@@ -9,19 +10,17 @@
 /**
  * Implementation of hook_install().
  */
-function codeless_discounts_field_install()
-{
-	drupal_load("module", "content");
-	content_notify("install", "codeless_discounts");
+function codeless_discounts_field_install() {
+  drupal_load("module", "content");
+  content_notify("install", "codeless_discounts");
 }
 
 /**
  * Implementation of hook_uninstall().
  */
-function codeless_discounts_field_uninstall()
-{
-	drupal_load("module", "content");
-	content_notify("uninstall", "codeless_discounts");
+function codeless_discounts_field_uninstall() {
+  drupal_load("module", "content");
+  content_notify("uninstall", "codeless_discounts");
 }
 
 /**
@@ -29,10 +28,9 @@ function codeless_discounts_field_uninst
  *
  * Notify content module when this module is disabled.
  */
-function codeless_discounts_field_enable()
-{
-	drupal_load("module", "content");
-	content_notify("enable", "codeless_discounts");
+function codeless_discounts_field_enable() {
+  drupal_load("module", "content");
+  content_notify("enable", "codeless_discounts");
 }
 
 /**
@@ -40,8 +38,8 @@ function codeless_discounts_field_enable
  *
  * Notify content module when this module is disabled.
  */
-function codeless_discounts_field_disable()
-{
-	drupal_load("module", "content");
-	content_notify("disable", "codeless_discounts");
+function codeless_discounts_field_disable() {
+  drupal_load("module", "content");
+  content_notify("disable", "codeless_discounts");
 }
+
Index: codeless_discounts_field/codeless_discounts_field.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_discounts_alt/codeless_discounts_field/codeless_discounts_field.module,v
retrieving revision 1.7
diff -u -p -r1.7 codeless_discounts_field.module
--- codeless_discounts_field/codeless_discounts_field.module	26 Apr 2009 09:21:32 -0000	1.7
+++ codeless_discounts_field/codeless_discounts_field.module	20 Aug 2009 22:09:28 -0000
@@ -1,6 +1,7 @@
 <?php
 //$Id: codeless_discounts_field.module,v 1.7 2009/04/26 09:21:32 ryangroe Exp $
 
+
 /**
  * See http://drupal.org/node/106716 for more information.
  */
@@ -8,124 +9,114 @@
 /**
  * Implementation of hook_field_info().
  */
-function codeless_discounts_field_field_info()
-{
-	return array(
-		"codeless_discounts" => array(
-			"label" => t("Codeless Discounts"),
-			"description" => t("Displays uc_discounts_alt discounts for node without codes"),
-		),
-	);
+function codeless_discounts_field_field_info() {
+  return array(
+    "codeless_discounts" => array(
+      "label" => t("Codeless Discounts"),
+      "description" => t("Displays uc_discounts_alt discounts for node without codes"),
+    ),
+  );
 }
 
 /**
  * Implementation of hook_content_is_empty().
  */
-function codeless_discounts_field_content_is_empty($item, $field)
-{
-	return FALSE;
+function codeless_discounts_field_content_is_empty($item, $field) {
+  return FALSE;
 }
 
 /**
  * Implementation of hook_widget_info().
  */
-function codeless_discounts_field_widget_info()
-{
-	return array(
-		"codeless_discounts" => array(
-			"label" => "Default Display",
-			"field types" => array("codeless_discounts"),
-			"multiple values" => CONTENT_HANDLE_CORE,
-			"callbacks" => array(
-				"default value" => CONTENT_CALLBACK_DEFAULT,
-			),
-		),
-	);
+function codeless_discounts_field_widget_info() {
+  return array(
+    "codeless_discounts" => array(
+      "label" => "Default Display",
+      "field types" => array("codeless_discounts"),
+      "multiple values" => CONTENT_HANDLE_CORE,
+      "callbacks" => array(
+        "default value" => CONTENT_CALLBACK_DEFAULT,
+      ),
+    ),
+  );
 }
 
 /**
  * Implementation of hook_widget().
  */
-function codeless_discounts_field_widget(&$form, &$form_state, $field, $items, $delta = 0)
-{
-	$element = array(
-		"#type" => $field["widget"]["type"],
-		"#default_value" => isset($items[$delta]) ? $items[$delta] : NULL,
-	);
-	return $element;
+function codeless_discounts_field_widget(&$form, &$form_state, $field, $items, $delta = 0) {
+  $element = array(
+    "#type" => $field["widget"]["type"],
+    "#default_value" => isset($items[$delta]) ? $items[$delta] : NULL,
+  );
+  return $element;
 }
 
 /**
  * Implementation of hook_field_formatter_info().
  */
-function codeless_discounts_field_field_formatter_info()
-{
-	return array(
-		"default" => array(
-			"label" => "Discount Description",
-			"field types" => array("codeless_discounts"),
-		),
-	);
+function codeless_discounts_field_field_formatter_info() {
+  return array(
+    "default" => array(
+      "label" => "Discount Description",
+      "field types" => array("codeless_discounts"),
+    ),
+  );
 }
 
 /**
  * Implementation of hook_field()
  */
-function codeless_discounts_field_field($op, &$node, $field, &$items, $teaser, $page)
-{
-	switch ($op)
-	{
-		case "sanitize":
-		case "view":
-			//If items is empty, generate value by getting discounts that apply to this product
-			if ( empty($items) )
-			{
-				$item = array();
-				$item["codeless_discounts"] = 
-					theme("codeless_discounts_field_get_codeless_discount_html_for_product", $node);
-				$items[] = $item;
-			}
-			break;
-	}
+function codeless_discounts_field_field($op, &$node, $field, &$items, $teaser, $page) {
+  switch ($op) {
+    case "sanitize":
+    case "view":
+      //If items is empty, generate value by getting discounts that apply to this product
+      if (empty($items)) {
+        $item = array();
+        $item["codeless_discounts"] = theme("codeless_discounts_field_get_codeless_discount_html_for_product", $node);
+        $items[] = $item;
+      }
+      break;
+  }
 }
 
 /**
  * Implementation of hook_theme().
  */
-function codeless_discounts_field_theme()
-{
-	return array(
-		"codeless_discounts_field_formatter_default" => array(
-			"arguments" => array("element"),
-		),
-		"codeless_discounts_field_get_codeless_discount_html_for_product" => array(
-			"arguments" => array("product_id"),
-		),
-	);
+function codeless_discounts_field_theme() {
+  return array(
+    "codeless_discounts_field_formatter_default" => array(
+      "arguments" => array("element"),
+    ),
+    "codeless_discounts_field_get_codeless_discount_html_for_product" => array(
+      "arguments" => array("product_id"),
+    ),
+  );
 }
 
 /**
  * Theme function for codeless discounts element.
  */
-function theme_codeless_discounts_field_formatter_default($element)
-{
-	return $element["#item"]["codeless_discounts"];
-}
-
-function theme_codeless_discounts_field_get_codeless_discount_html_for_product($product)
-{
-	$discounts = get_codeless_discounts_for_product($product);
-	if ( empty($discounts) )
-		return "";
-		
-	$descriptions = array();
-	foreach ($discounts as $discount)
-	{
-		$description = $discount->short_description;
-		if ($discount->has_expiration)
-			$description .= " (" . t("Expires:") . " " . date("Y-m-d H:i", $discount->expiration) . ")";
-		$descriptions[] = $description;
-	}
+function theme_codeless_discounts_field_formatter_default($element) {
+  return $element["#item"]["codeless_discounts"];
+}
 
-	return join("<br/>", $descriptions);
+function theme_codeless_discounts_field_get_codeless_discount_html_for_product($product) {
+  $discounts = get_codeless_discounts_for_product($product);
+  if (empty($discounts)) {
+    return "";
+  }
+
+  $descriptions = array();
+  foreach ($discounts as $discount) {
+    $description = $discount->short_description;
+    if ($discount->has_expiration) $description .= " (". t("Expires:") ." ". date("Y-m-d H:i", $discount->expiration) {
+      .")";
+    }
+    $descriptions[] = $description;
+  }
+
+  return join("<br/>", $descriptions);
 }
+
Index: product_price_alterer_field/discounted_price_handler.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_discounts_alt/product_price_alterer_field/discounted_price_handler.inc,v
retrieving revision 1.1
diff -u -p -r1.1 discounted_price_handler.inc
--- product_price_alterer_field/discounted_price_handler.inc	9 May 2009 01:31:03 -0000	1.1
+++ product_price_alterer_field/discounted_price_handler.inc	20 Aug 2009 22:09:28 -0000
@@ -1,35 +1,35 @@
 <?php
 //$Id: discounted_price_handler.inc,v 1.1 2009/05/09 01:31:03 ryangroe Exp $
 
+
 /**
  * Renders a discounted price field.
  *
  * @ingroup views_field_handlers
  */
-class discounted_price_handler extends views_handler_field_numeric
-{
-	function construct()
-	{
-		parent::construct();
-		$this->content_field = content_fields($this->definition['content_field_name']);
-	}
-
-	function render($values)
-	{
-		$node = node_load($values->nid);
-
-		$discounted_price = theme("get_discounted_price", $node);
-		if ( is_null($discounted_price) )
-			return NULL;
-
-		$output = theme( "product_discounted_price", $node, uc_currency_format($discounted_price) );
+class discounted_price_handler extends views_handler_field_numeric {
+  function construct() {
+    parent::construct();
+    $this->content_field = content_fields($this->definition['content_field_name']);
+  }
+
+  function render($values) {
+    $node = node_load($values->nid);
+
+    $discounted_price = theme("get_discounted_price", $node);
+    if (is_null($discounted_price)) {
+      return NULL;
+    }
+
+    $output = theme("product_discounted_price", $node, uc_currency_format($discounted_price));
 
-		//Add css to page
-		theme("add_product_price_altering_css", $node);
+    //Add css to page
+    theme("add_product_price_altering_css", $node);
 
-		//Add javascript to page
-		theme("add_product_price_altering_javascript", $node);
+    //Add javascript to page
+    theme("add_product_price_altering_javascript", $node);
 
-		return check_plain($output);
-	}
+    return check_plain($output);
+  }
 }
+
Index: product_price_alterer_field/product_price_alterer_field.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_discounts_alt/product_price_alterer_field/product_price_alterer_field.install,v
retrieving revision 1.1
diff -u -p -r1.1 product_price_alterer_field.install
--- product_price_alterer_field/product_price_alterer_field.install	20 Apr 2009 07:23:46 -0000	1.1
+++ product_price_alterer_field/product_price_alterer_field.install	20 Aug 2009 22:09:28 -0000
@@ -1,6 +1,7 @@
 <?php
 //$Id: product_price_alterer_field.install,v 1.1 2009/04/20 07:23:46 ryangroe Exp $
 
+
 /**
  * @file
  * Install hooks for product_price_alterer_field.module.
@@ -9,19 +10,17 @@
 /**
  * Implementation of hook_install().
  */
-function product_price_alterer_field_install()
-{
-	drupal_load("module", "content");
-	content_notify("install", "product_price_alterer");
+function product_price_alterer_field_install() {
+  drupal_load("module", "content");
+  content_notify("install", "product_price_alterer");
 }
 
 /**
  * Implementation of hook_uninstall().
  */
-function product_price_alterer_field_uninstall()
-{
-	drupal_load("module", "content");
-	content_notify("uninstall", "product_price_alterer");
+function product_price_alterer_field_uninstall() {
+  drupal_load("module", "content");
+  content_notify("uninstall", "product_price_alterer");
 }
 
 /**
@@ -29,10 +28,9 @@ function product_price_alterer_field_uni
  *
  * Notify content module when this module is disabled.
  */
-function product_price_alterer_field_enable()
-{
-	drupal_load("module", "content");
-	content_notify("enable", "product_price_alterer");
+function product_price_alterer_field_enable() {
+  drupal_load("module", "content");
+  content_notify("enable", "product_price_alterer");
 }
 
 /**
@@ -40,8 +38,8 @@ function product_price_alterer_field_ena
  *
  * Notify content module when this module is disabled.
  */
-function product_price_alterer_field_disable()
-{
-	drupal_load("module", "content");
-	content_notify("disable", "product_price_alterer");
+function product_price_alterer_field_disable() {
+  drupal_load("module", "content");
+  content_notify("disable", "product_price_alterer");
 }
+
Index: product_price_alterer_field/product_price_alterer_field.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_discounts_alt/product_price_alterer_field/product_price_alterer_field.module,v
retrieving revision 1.15
diff -u -p -r1.15 product_price_alterer_field.module
--- product_price_alterer_field/product_price_alterer_field.module	2 Jun 2009 05:35:24 -0000	1.15
+++ product_price_alterer_field/product_price_alterer_field.module	20 Aug 2009 22:09:28 -0000
@@ -1,190 +1,173 @@
 <?php
 //$Id: product_price_alterer_field.module,v 1.15 2009/06/02 05:35:24 ryangroe Exp $
 
+
 /**
  * See http://drupal.org/node/106716 for more information.
  */
 
-
 /**
  * Implementation of hook_field_info().
  */
-function product_price_alterer_field_field_info()
-{
-	return array(
-		"discounted_price" => array(
-			"label" => t("Discounted Price"),
-			"description" => t("Alters price for products where uc_discounts_alt discounts apply when added with a quantity of one or less"),
-		),
-	);
+function product_price_alterer_field_field_info() {
+  return array(
+    "discounted_price" => array(
+      "label" => t("Discounted Price"),
+      "description" => t("Alters price for products where uc_discounts_alt discounts apply when added with a quantity of one or less"),
+    ),
+  );
 }
 
 /**
  * Implementation of hook_content_is_empty().
  */
-function product_price_alterer_field_content_is_empty($item, $field)
-{
-	return FALSE;
+function product_price_alterer_field_content_is_empty($item, $field) {
+  return FALSE;
 }
 
 /**
  * Implementation of hook_widget_info().
  */
-function product_price_alterer_field_widget_info()
-{
-	return array(
-		"discounted_price" => array(
-			"label" => "Default Display",
-			"field types" => array("discounted_price"),
-			"multiple values" => CONTENT_HANDLE_CORE,
-			"callbacks" => array(
-				"default value" => CONTENT_CALLBACK_DEFAULT,
-			),
-		),
-	);
+function product_price_alterer_field_widget_info() {
+  return array(
+    "discounted_price" => array(
+      "label" => "Default Display",
+      "field types" => array("discounted_price"),
+      "multiple values" => CONTENT_HANDLE_CORE,
+      "callbacks" => array(
+        "default value" => CONTENT_CALLBACK_DEFAULT,
+      ),
+    ),
+  );
 }
 
 /**
  * Implementation of hook_widget().
  */
-function product_price_alterer_field_widget(&$form, &$form_state, $field, $items, $delta = 0)
-{
-	$element = array(
-		"#type" => $field["widget"]["type"],
-		"#default_value" => isset($items[$delta]) ? $items[$delta] : NULL,
-	);
-	return $element;
+function product_price_alterer_field_widget(&$form, &$form_state, $field, $items, $delta = 0) {
+  $element = array(
+    "#type" => $field["widget"]["type"],
+    "#default_value" => isset($items[$delta]) ? $items[$delta] : NULL,
+  );
+  return $element;
 }
 
 /**
  * Implementation of hook_field_formatter_info().
  */
-function product_price_alterer_field_field_formatter_info()
-{
-	return array(
-		"default" => array(
-			"label" => "Discounted Price",
-			"field types" => array("discounted_price"),
-		),
-	);
+function product_price_alterer_field_field_formatter_info() {
+  return array(
+    "default" => array(
+      "label" => "Discounted Price",
+      "field types" => array("discounted_price"),
+    ),
+  );
 }
 
 /**
  * Theme function for 'default' text field formatter.
  */
-function theme_product_price_alterer_field_formatter_default($element)
-{
-	return $element["#item"]["discounted_price"];
+function theme_product_price_alterer_field_formatter_default($element) {
+  return $element["#item"]["discounted_price"];
 }
 
 /**
  * Implementation of hook_field()
  */
-function product_price_alterer_field_field($op, &$node, $field, &$items, $teaser, $page)
-{
-	switch ($op)
-	{
-		case "sanitize":
-		case "view":
-			//If items is empty, generate value by getting discounts that apply to this product
-			if ( empty($items) )
-			{
-				$discounted_price = theme("get_discounted_price", $node);
-				if ( !is_null($discounted_price) )
-				{
-					//Add field for discounted price
-					$item = array();
-					$item["discounted_price"] = theme( "product_discounted_price", $node, uc_currency_format($discounted_price) );
-					$items[] = $item;
-
-					//Add css to page
-					theme("add_product_price_altering_css", $node);
-
-					//Add javascript to page
-					theme("add_product_price_altering_javascript", $node);
-				}
-			}
-			break;
-	}
+function product_price_alterer_field_field($op, &$node, $field, &$items, $teaser, $page) {
+  switch ($op) {
+    case "sanitize":
+    case "view":
+      //If items is empty, generate value by getting discounts that apply to this product
+      if (empty($items)) {
+        $discounted_price = theme("get_discounted_price", $node);
+        if (!is_null($discounted_price)) {
+          //Add field for discounted price
+          $item = array();
+          $item["discounted_price"] = theme("product_discounted_price", $node, uc_currency_format($discounted_price));
+          $items[] = $item;
+
+          //Add css to page
+          theme("add_product_price_altering_css", $node);
+
+          //Add javascript to page
+          theme("add_product_price_altering_javascript", $node);
+        }
+      }
+      break;
+  }
 }
 
 /**
  * Implementation of hook_theme().
  */
-function product_price_alterer_field_theme()
-{
-	return array(
-		"product_price_alterer_field_formatter_default" => array(
-			"arguments" => array("element" => NULL),
-		),
-		"get_discounted_price" => array(
-			"arguments" => array("product"),
-		),
-		"product_discounted_price" => array(
-			"arguments" => array("product", "discounted_price"),
-		),
-		"add_product_price_altering_css" => array(
-			"arguments" => array("product"),
-		),
-		"add_product_price_altering_javascript" => array(
-			"arguments" => array("product"),
-		),
-	);
+function product_price_alterer_field_theme() {
+  return array(
+    "product_price_alterer_field_formatter_default" => array(
+      "arguments" => array("element" => NULL),
+    ),
+    "get_discounted_price" => array(
+      "arguments" => array("product"),
+    ),
+    "product_discounted_price" => array(
+      "arguments" => array("product", "discounted_price"),
+    ),
+    "add_product_price_altering_css" => array(
+      "arguments" => array("product"),
+    ),
+    "add_product_price_altering_javascript" => array(
+      "arguments" => array("product"),
+    ),
+  );
 }
 
 /**
  * Theme function for producing product discounted price html.
  */
-function theme_get_discounted_price($product)
-{
-	//Determine discounts that apply to product when ordering a quantity of 1 or less
-	$discounts = get_codeless_discounts_for_product_and_quantity($product, 1);
-	if ( empty($discounts) )
-		return NULL;
-
-	//Sum discount amounts
-	$total_discount_amount = 0;
-	foreach ($discounts as $discount)
-		$total_discount_amount += $discount->amount;
-	return $product->sell_price - $total_discount_amount;
+function theme_get_discounted_price($product) {
+  //Determine discounts that apply to product when ordering a quantity of 1 or less
+  $discounts = get_codeless_discounts_for_product_and_quantity($product, 1);
+  if (empty($discounts)) {
+    return NULL;
+  }
+
+  //Sum discount amounts
+  $total_discount_amount = 0;
+  foreach ($discounts as $discount) $total_discount_amount += $discount->amount;
+  return $product->sell_price - $total_discount_amount;
 }
 
 /**
  * Theme function for producing product discounted price html.
  * Returns discounted price for product (based on passed discounts).
  */
-function theme_product_discounted_price($product, $discounted_price_string)
-{
-	return $discounted_price_string;
+function theme_product_discounted_price($product, $discounted_price_string) {
+  return $discounted_price_string;
 }
 
 /**
  * Theme function for writing css to product page.
  */
-function theme_add_product_price_altering_css($product)
-{
-	global $product_price_alterer_field_css_added;
-	if ( empty($product_price_alterer_field_css_added) )
-	{
-		$product_price_alterer_field_css_added = TRUE;
-
-		drupal_add_css(drupal_get_path("module", "product_price_alterer_field") 
-			. "/product_price_alterer_field.css");
-	}
+function theme_add_product_price_altering_css($product) {
+  global $product_price_alterer_field_css_added;
+  if (empty($product_price_alterer_field_css_added)) {
+    $product_price_alterer_field_css_added = TRUE;
+
+    drupal_add_css(drupal_get_path("module", "product_price_alterer_field") ."/product_price_alterer_field.css"
+    );
+  }
 }
 
 /**
  * Theme function for writing javascript to product page.
  */
-function theme_add_product_price_altering_javascript($product)
-{
-	global $product_price_alterer_field_javascript_added;
-	if ( empty($product_price_alterer_field_javascript_added) )
-	{
-		$product_price_alterer_field_javascript_added = TRUE;
+function theme_add_product_price_altering_javascript($product) {
+  global $product_price_alterer_field_javascript_added;
+  if (empty($product_price_alterer_field_javascript_added)) {
+    $product_price_alterer_field_javascript_added = TRUE;
 
-		//Alter price using javascript
-		drupal_add_js("$(document).ready(function()
+    //Alter price using javascript
+    drupal_add_js("$(document).ready(function()
 			{
 				$(\".views-field-discounted-price\").each(function()
 					{
@@ -212,45 +195,44 @@ function theme_add_product_price_alterin
 							.after(	$( \".field-type-discounted-price:first\", self.parent() )	);
 					});
 			});", "inline");
-	}
+  }
 }
 
 /**
  * Implementation of hook_views_data()
  * Register all of the basic handlers views uses.
  */
-function product_price_alterer_field_views_data()
-{
-	$data["uc_products"]["discounted_price"] = array(
-		"title" => t("Discounted price"),
-		"help" => t("Price after discounts (if any exist)."),
-		"real field" => "sell_price",
-		"argument" => array(
-			"handler" => "views_handler_argument_numeric"
-		),
-		"field" => array(
-			"handler" => "discounted_price_handler",
-			"click sortable" => FALSE,
-		),
-	);
+function product_price_alterer_field_views_data() {
+  $data["uc_products"]["discounted_price"] = array(
+    "title" => t("Discounted price"),
+    "help" => t("Price after discounts (if any exist)."),
+    "real field" => "sell_price",
+    "argument" => array(
+      "handler" => "views_handler_argument_numeric",
+    ),
+    "field" => array(
+      "handler" => "discounted_price_handler",
+      "click sortable" => FALSE,
+    ),
+  );
 
-	return $data;
+  return $data;
 }
 
 /**
  * Implementation of hook_views_handlers()
  * Register all of the basic handlers views uses.
  */
-function product_price_alterer_field_views_handlers()
-{
-	return array(
-		"info" => array(
-			"path" => drupal_get_path("module", "product_price_alterer_field"),
-		),
-		"handlers" => array(
-			"discounted_price_handler" => array(
-				"parent" => "views_handler_field_numeric",
-			),
-		),
-	);
+function product_price_alterer_field_views_handlers() {
+  return array(
+    "info" => array(
+      "path" => drupal_get_path("module", "product_price_alterer_field"),
+    ),
+    "handlers" => array(
+      "discounted_price_handler" => array(
+        "parent" => "views_handler_field_numeric",
+      ),
+    ),
+  );
 }
+
Index: uc_discounts/uc_discounts.admin.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_discounts_alt/uc_discounts/uc_discounts.admin.inc,v
retrieving revision 1.9
diff -u -p -r1.9 uc_discounts.admin.inc
--- uc_discounts/uc_discounts.admin.inc	26 May 2009 01:45:13 -0000	1.9
+++ uc_discounts/uc_discounts.admin.inc	20 Aug 2009 22:09:29 -0000
@@ -1,62 +1,63 @@
 <?php
 //$Id: uc_discounts.admin.inc,v 1.9 2009/05/26 01:45:13 ryangroe Exp $
 
+
 /**
  * @file
  * Discounts administration menu items.
  */
 
-
 /**
  * Display a list of discounts.
  */
-function uc_discounts_admin_settings()
-{
-	$header = array(
-		array("data" => t("Name"), "field" => "name"),
-		array("data" => t("Short Description"), "field" => "short_description"),
-		array("data" => t("Qualifying Type"), "field" => "qualifying_type"),
-		array("data" => t("Discount Type"), "field" => "discount_type"),
-		array("data" => t("Weight"), "field" => "weight", "sort" => "asc"),
-		array("data" => t("Operations"), "colspan" => 4),
-	);
-
-	$query = "SELECT * FROM {uc_discounts}";
-	$tablesort = tablesort_sql($header);
-	$result = pager_query($query . $tablesort, 50);
-
-	$rows = array();
-	while ( $discount = db_fetch_object($result) )
-	{
-		$total_use_count = ( is_numeric($discount->total_use_count) ) ? $discount->total_use_count : 0;
-		$total_times_applied = ( is_numeric($discount->total_times_applied) ) ? $discount->total_times_applied : 0;
-
-		$rows[] = array("data" =>
-			//Cell data
-			array(
-				$discount->name, 
-				$discount->short_description, 
-				qualifying_type_name($discount->qualifying_type), 
-				discount_type_name($discount->discount_type), 
-				$discount->weight,
-				l( t("view usage"), "admin/reports/uc_discounts/discount/" . $discount->discount_id), 
-				l( t("edit"), "admin/store/settings/uc_discounts/edit/" . $discount->discount_id), 
-				l(t("copy"), "admin/store/settings/uc_discounts/copy/" . $discount->discount_id), 
-				l(t("delete"), "admin/store/settings/uc_discounts/delete/" . $discount->discount_id),
-			),
-		);
-	}
-
-	if ( empty($rows) )
-		$rows[] = array( array("data" => t("No discounts."), "colspan" => 9) );
+function uc_discounts_admin_settings() {
+  $header = array(
+    array("data" => t("Name"), "field" => "name"),
+    array("data" => t("Short Description"), "field" => "short_description"),
+    array("data" => t("Qualifying Type"), "field" => "qualifying_type"),
+    array("data" => t("Discount Type"), "field" => "discount_type"),
+    array("data" => t("Weight"), "field" => "weight", "sort" => "asc"),
+    array("data" => t("Operations"), "colspan" => 4),
+  );
+
+  $query     = "SELECT * FROM {uc_discounts}";
+  $tablesort = tablesort_sql($header);
+  $result    = pager_query($query . $tablesort, 50);
+
+  $rows = array();
+  while ($discount = db_fetch_object($result)) {
+    $total_use_count = (is_numeric($discount->total_use_count)) ? $discount->total_use_count : 0;
+    $total_times_applied = (is_numeric($discount->total_times_applied)) ? $discount->total_times_applied : 0;
+
+    $rows[] = array("data" =>
+      //Cell data
+      array(
+        $discount->name,
+        $discount->short_description,
+        qualifying_type_name($discount->qualifying_type),
+        discount_type_name($discount->discount_type),
+        $discount->weight,
+        l(t("view usage"), "admin/reports/uc_discounts/discount/". $discount->discount_id),
+        l(t("edit"), "admin/store/settings/uc_discounts/edit/". $discount->discount_id),
+        l(t("copy"), "admin/store/settings/uc_discounts/copy/". $discount->discount_id),
+        l(t("delete"), "admin/store/settings/uc_discounts/delete/". $discount->discount_id),
+      ),
+    );
+  }
+
+  if (empty($rows)) {
+
+    $rows[] = array(array("data" => t("No discounts."), "colspan" => 9));
+
+  }
 
-	$output .= theme( "table", $header, $rows, array("id" => "uc_discounts_table") );
-	$output .= theme("pager", NULL, 50, 0);
+  $output .= theme("table", $header, $rows, array("id" => "uc_discounts_table"));
+  $output .= theme("pager", NULL, 50, 0);
 
-	$output .= "<br/>";
-	$output .= l(t("Create a new discount."), "admin/store/settings/uc_discounts/edit");
+  $output .= "<br/>";
+  $output .= l(t("Create a new discount."), "admin/store/settings/uc_discounts/edit");
 
-	return $output;
+  return $output;
 }
 
 /**
@@ -65,790 +66,750 @@ function uc_discounts_admin_settings()
  * @ingroup forms
  * @see uc_discounts_form_submit()
  */
-function uc_discounts_form($form_state, $discount_id = 0)
-{
-	$form = array();
-	$form_submitted = $form_state["submitted"];
-	$is_edit = $discount_id != 0;
-	$seed = rand(1, 1000000);
-
-	if ( !$form_submitted && $is_edit)
-		$form_state["values"] = db_fetch_array( db_query("SELECT * FROM {uc_discounts} WHERE discount_id=%d", $discount_id) );
-
-	$form["discount_id"] = array("#type" => "hidden", "#value" => $form_state["values"]["discount_id"]);
-
-	$form["name"] = array(
-		"#type" => "textfield",
-		"#title" => t("Name"),
-		"#description" => t("Shown in admin reports and logs."),
-		"#default_value" => $form_state["values"]["name"],
-		"#size" => 50,
-		"#required" => TRUE,
-	);
-
-	$form["short_description"] = array(
-		"#type" => "textfield",
-		"#title" => t("Short Description"),
-		"#description" => t("Description displayed to user during checkout and in order review."),
-		"#default_value" => $form_state["values"]["short_description"],
-		"#size" => 75,
-		"#required" => TRUE,
-	);
-
-	$form["description"] = array(
-		"#type" => "textfield",
-		"#title" => t("Description"),
-		"#description" => t("Internal description for discount administrators."),
-		"#default_value" => $form_state["values"]["description"],
-		"#size" => 75,
-	);
-
-	$form["qualifying_type"] = array(
-		"#type" => "select",
-		"#title" => t("Qualifying type"),
-		"#description" => t("The amount used to determine if a cart qualifies for this discount."),
-		"#options" => qualifying_type_options(),
-		"#default_value" => $form_state["values"]["qualifying_type"],
-	);
-
-	$form["qualifying_amount"] = array(
-		"#type" => "textfield",
-		"#title" => t("Qualifying amount"),
-		"#description" => t("The amount required to qualify for the discount.	E.g. 50 (for $50), 5 (for 5 items).  Remember for a discount like 'buy 4 get 1 free' the qualifying amount is '5'."),
-		"#default_value" => $form_state["values"]["qualifying_amount"],
-		"#size" => 15,
-		"#required" => TRUE,
-	);
-
-
-	$has_qualifying_amount_max = isset($form_state["values"]["has_qualifying_amount_max"]) ? $form_state["values"]["has_qualifying_amount_max"] : HAS_QUALIFYING_AMOUNT_MAX_DEFAULT;
-	$display_string = ($has_qualifying_amount_max) ? "" : " style='display:none'";
-
-	$qualifying_amount_max_container_id = "qualifying-amount-max-container-" . $seed;
-	$qualifying_amount_max_prefix = sprintf("<div id='%s' onclick='if ( jQuery(\"#%s input[type=\\\"checkbox\\\"]\").attr(\"checked\") )"
-		. "{ jQuery(\"#%s .qualifying-amount-max-container\").slideDown(); }"
-		. "else { jQuery(\"#%s .qualifying-amount-max-container\").slideUp(); }'>", 
-		$qualifying_amount_max_container_id, $qualifying_amount_max_container_id, 
-		$qualifying_amount_max_container_id, $qualifying_amount_max_container_id, 
-		$qualifying_amount_max_container_id, $qualifying_amount_max_container_id);
-
-	$form["qualifying_amount_max_header"] = array(
-		"#type" => "hidden",
-		"#prefix" => $qualifying_amount_max_prefix,
-	);
-
-	$form["has_qualifying_amount_max"] = array(
-		"#type" => "checkbox",
-		"#title" => t("Has max qualifying amount."),
-		"#description" => t("Whether or not discount contains maximum qualifying amount."),
-		"#default_value" => $has_qualifying_amount_max,
-	);
-
-	//Get current discount qualifying_amount_max
-	$qualifying_amount_max = $form_state["values"]["role_ids"];
-
-	//Create qualifying_amount_max form element
-	$form["qualifying_amount_max"] = array(
-		"#type" => "textfield",
-		"#title" => t("Maximum qualifying amount"),
-		"#description" => t("Maximum amount to NOT exceed to qualify for the discount.  E.g. 50 (for $50), 5 (for 5 items)."),
-		"#default_value" => $form_state["values"]["qualifying_amount_max"],
-		"#size" => 15,
-		"#required" => FALSE,
-		"#prefix" => sprintf("<div class='qualifying-amount-max-container'%s>", $display_string),
-		"#suffix" => "</div>",
-	);
-
-	$form["qualifying_amount_max_footer"] = array(
-		"#type" => "hidden",
-		"#suffix" => "</div>",
-	);
-
-
-	$form["discount_type"] = array(
-		"#type" => "select",
-		"#title" => t("Discount type"),
-		"#description" => t("Type of discount to apply."),
-		"#options" => discount_type_options(), 
-		"#default_value" => $form_state["values"]["discount_type"],
-	);
-
-	$form["discount_amount"] = array(
-		"#type" => "textfield",
-		"#title" => t("Discount amount"),
-		"#description" => t("The amount of discount.	E.g. 50 (for $50), 5 (for 5 items), or 0.05 (for 5%)"),
-		"#default_value" => $form_state["values"]["discount_amount"],
-		"#size" => 15,
-		"#required" => TRUE,
-	);
-
-	$requires_code = isset($form_state["values"]["requires_code"]) ? $form_state["values"]["requires_code"] : REQUIRES_CODE_DEFAULT;
-	$display_string = ($requires_code) ? "" : " style='display:none'";
-
-	$codes_container_id = "codes-container-" . $seed;
-	$codes_prefix = sprintf("<div id='%s' onclick='if ( jQuery(\"#%s input[type=\\\"checkbox\\\"]\").attr(\"checked\") )"
-		. "{ jQuery(\"#%s .codes-container\").slideDown(); }"
-		. "else { jQuery(\"#%s .codes-container\").slideUp(); }'>", 
-		$codes_container_id, $codes_container_id, $codes_container_id, $codes_container_id, $codes_container_id, $codes_container_id);
-
-	$form["codes_header"] = array(
-		"#type" => "hidden",
-		"#prefix" => $codes_prefix,
-	);
-
-	$form["requires_code"] = array(
-		"#type" => "checkbox",
-		"#title" => t("Require(s) code to activate discount."),
-		"#default_value" => $requires_code,
-	);
-
-	//Determine codes default value
-	$codes_string = NULL;
-	if ( isset($form_state["values"]["codes"]) )
-		$codes_string = $form_state["values"]["codes"];
-	else
-	{
-		$codes = array();
-		if ($is_edit)
-			$codes = get_codes_for_discount($discount_id);
-		$codes_string = create_codes_string($codes);
-	}
-
-	$form["codes"] = array(
-		"#type" => "textarea",
-		"#title" => t("Discount codes")
-			. sprintf("<span title='" . t("This field is required.") . "' class='form-required'>*</span>"),
-		"#description" => t("Enter discount codes in box above, one code per line.  Spaces are permitted but may confuse consumers. Note codes will be trimmed."),
-		"#default_value" => $codes_string,
-		"#rows" => 5,
-		"#prefix" => sprintf("<div class='codes-container'%s>", $display_string) . "<div class='discount-codes-wrapper'>",
-		"#suffix" => "</div></div>",
-	);
-
-	$form["codes_footer"] = array(
-		"#type" => "hidden",
-		"#suffix" => "</div>",
-	);
-
-	$filter_type = isset($form_state["values"]["filter_type"]) ? $form_state["values"]["filter_type"] : FILTER_TYPE_DEFAULT;
-	$products_display_string = ($filter_type == FILTER_TYPE_PRODUCTS) ? "" : " style='display:none'";
-	$terms_display_string = ($filter_type == FILTER_TYPE_TERMS) ? "" : " style='display:none'";
-	$skus_display_string = ($filter_type == FILTER_TYPE_SKUS) ? "" : " style='display:none'";
-
-	$filter_type_container_id = "filter-type-container-" . $seed;
-	$filter_type_prefix = sprintf(
-		"<div id='%s' onclick='value = jQuery(\"#%s select\").val();"
-		. "if (value == %d) { jQuery(\"#%s .products-container\").slideDown(); jQuery(\"#%s .terms-container\").slideUp(); jQuery(\"#%s .skus-container\").slideUp(); }"
-		. "if (value == %d) { jQuery(\"#%s .products-container\").slideUp(); jQuery(\"#%s .terms-container\").slideDown(); jQuery(\"#%s .skus-container\").slideUp(); }"
-		. "if (value == %d) { jQuery(\"#%s .products-container\").slideUp(); jQuery(\"#%s .terms-container\").slideUp(); jQuery(\"#%s .skus-container\").slideDown(); }'>",
-		$filter_type_container_id, $filter_type_container_id, 
-		FILTER_TYPE_PRODUCTS, $filter_type_container_id, $filter_type_container_id, $filter_type_container_id, 
-		FILTER_TYPE_TERMS,  $filter_type_container_id, $filter_type_container_id, $filter_type_container_id, 
-		FILTER_TYPE_SKUS,  $filter_type_container_id, $filter_type_container_id, $filter_type_container_id);
-
-	$form["filter_type_header"] = array(
-		"#type" => "hidden",
-		"#prefix" => $filter_type_prefix,
-	);
-
-	//Create filter_type form element
-	$options = array();
-	$options[FILTER_TYPE_PRODUCTS] = t("Filter By Products");
-	$options[FILTER_TYPE_TERMS] = t("Filter By Terms");
-	$options[FILTER_TYPE_SKUS] = t("Filter By SKUs");
-	$form["filter_type"] = array(
-		"#type" => "select",
-		"#title" => t("Filter Type"),
-		"#description" => t("Determine whether to filter by products, terms or SKUs."),
-		"#options" => $options,
-		"#default_value" => $filter_type,
-		"#required" => TRUE,
-	);
-
-	//Get current discount products
-	$product_ids = null;
-	if ( isset($form_state["values"]["product_ids"]) )
-		$product_ids = $form_state["values"]["product_ids"];
-	elseif ($is_edit)
-		$product_ids = get_product_ids_for_discount($discount_id, FALSE);
-
-	//Create products form element
-	$options = array();
-	$result = db_query("SELECT n.nid as nid, n.title as title, p.model as model"
-		. " FROM {uc_products} p INNER JOIN {node} n ON p.nid=n.nid ORDER BY title");
-	$options[ALL_PRODUCTS] = t("<All Products>");
-	while ( $row = db_fetch_object($result) )
-		$options[$row->nid] = $row->title . " (" . $row->model . ")";
-	$form["product_ids"] = array(
-		"#type" => "select",
-		"#title" => t("Products")
-			. sprintf("<span title='" . t("This field is required.") . "' class='form-required'>*</span>"),
-		"#description" => t("Select all products this discount applies to or &lt;All Products&gt; to apply to all products."),
-		"#options" => $options,
-		"#default_value" => $product_ids,
-		"#multiple" => TRUE,
-		"#prefix" => sprintf("<div class='products-container'%s>", $products_display_string),
-		"#suffix" => "</div>",
-	);
-
-	//Get current discount terms
-	$term_ids = null;
-	if ( isset($form_state["values"]["term_ids"]) )
-		$term_ids = $form_state["values"]["term_ids"];
-	elseif ($is_edit)
-		$term_ids = get_term_ids_for_discount($discount_id, FALSE);
-
-	//Create terms form element
-	$options = array();
-	$result = db_query("SELECT tid, name FROM {term_data} ORDER BY weight");
-	$options[ALL_TERMS] = t("<All Terms>");
-	while ( $row = db_fetch_object($result) )
-		$options[$row->tid] = $row->name;
-	$form["term_ids"] = array(
-		"#type" => "select",
-		"#title" => t("Terms")
-			. sprintf("<span title='" . t("This field is required.") . "' class='form-required'>*</span>"),
-		"#description" => t("Select all terms this discount applies to or &lt;All Terms&gt; to apply to all terms.  Selections are <b>not</b> recursive."),
-		"#options" => $options,
-		"#default_value" => $term_ids,
-		"#multiple" => TRUE,
-		"#prefix" => sprintf("<div class='terms-container'%s>", $terms_display_string),
-		"#suffix" => "</div>",
-	);
-
-	//Get current discount SKUs
-	$skus = null;
-	if ( isset($form_state["values"]["skus"]) )
-		$skus = $form_state["values"]["skus"];
-	elseif ($is_edit)
-		$skus = get_skus_for_discount($discount_id, FALSE);
-
-	//Create SKUs form element
-	$options = array();
-	$result = db_query("SELECT p.model, n.title FROM {uc_products} p, {node} n WHERE p.nid=n.nid ORDER BY p.model");
-	$options[ALL_SKUS] = t("<All SKUs>");
-	while ( $row = db_fetch_object($result) )
-		$options[$row->model] = $row->model . " (" . $row->title . ")";
-	$form["skus"] = array(
-		"#type" => "select",
-		"#title" => t("SKUs")
-			. sprintf("<span title='" . t("This field is required.") . "' class='form-required'>*</span>"),
-		"#description" => t("Select all SKUs this discount applies to or &lt;All SKUs&gt; to apply to all SKUs.  Selections are <b>not</b> recursive."),
-		"#options" => $options,
-		"#default_value" => $skus,
-		"#multiple" => TRUE,
-		"#prefix" => sprintf("<div class='skus-container'%s>", $skus_display_string),
-		"#suffix" => "</div>",
-	);
-
-	$form["filter_type_footer"] = array(
-		"#type" => "hidden",
-		"#suffix" => "</div>",
-	);
-
-	$has_role_filter = isset($form_state["values"]["has_role_filter"]) ? $form_state["values"]["has_role_filter"] : HAS_ROLE_FILTER_DEFAULT;
-	$display_string = ($has_role_filter) ? "" : " style='display:none'";
-
-	$roles_container_id = "roles-container-" . $seed;
-	$roles_prefix = sprintf("<div id='%s' onclick='if ( jQuery(\"#%s input[type=\\\"checkbox\\\"]\").attr(\"checked\") )"
-		. "{ jQuery(\"#%s .roles-container\").slideDown(); }"
-		. "else { jQuery(\"#%s .roles-container\").slideUp(); }'>", 
-		$roles_container_id, $roles_container_id, $roles_container_id, $roles_container_id, $roles_container_id, $roles_container_id);
-
-	$form["roles_header"] = array(
-		"#type" => "hidden",
-		"#prefix" => $roles_prefix,
-	);
-
-	$form["has_role_filter"] = array(
-		"#type" => "checkbox",
-		"#title" => t("Filter based on roles."),
-		"#default_value" => $has_role_filter,
-	);
-
-	//Get current discount roles
-	$role_ids = null;
-	if ( isset($form_state["values"]["role_ids"]) )
-		$role_ids = $form_state["values"]["role_ids"];
-	elseif ($is_edit)
-		$role_ids = get_role_ids_for_discount($discount_id, FALSE);
-
-	//Create roles form element
-	$options = array();
-	//$result = db_query("SELECT rid, name FROM {role} WHERE rid<>%d AND rid<>%d ORDER BY rid", DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID);
-	$result = db_query("SELECT rid, name FROM {role} ORDER BY rid");
-	$options[ALL_ROLES] = t("<All Roles>");
-	while ( $row = db_fetch_object($result) )
-		$options[$row->rid] = $row->name;
-	$form["role_ids"] = array(
-		"#type" => "select",
-		"#title" => t("Roles")
-			. sprintf("<span title='" . t("This field is required.") . "' class='form-required'>*</span>"),
-		"#description" => t("Select all roles this discount applies to or &lt;All Roles&gt; to apply to all roles."),
-		"#options" => $options,
-		"#default_value" => $role_ids,
-		"#multiple" => TRUE,
-		"#prefix" => sprintf("<div class='roles-container'%s>", $display_string),
-		"#suffix" => "</div>",
-	);
-
-	$form["roles_footer"] = array(
-		"#type" => "hidden",
-		"#suffix" => "</div>",
-	);
-
-	$form["requires_single_product_to_qualify"] = array(
-		"#type" => "checkbox",
-		"#title" => t("Require single product to qualify."),
-		"#description" => t("Requires a single product to meet the qualifying requirements to receive discount.	Otherwise qualifying requirements may be met by the combination of selected products."),
-		"#default_value" => isset($form_state["values"]["requires_single_product_to_qualify"]) ? $form_state["values"]["requires_single_product_to_qualify"] : REQUIRES_SINGLE_PRODUCT_TO_QUALIFY_DEFAULT,
-	);
-
-	$form["max_times_applied"] = array(
-		"#type" => "textfield",
-		"#title" => t("Maximum times applied"),
-		"#description" => t("Number of times this discount can be applied to a single cart (0 for unlimited).  Does not apply to 'Percent off' discounts."),
-		"#default_value" => isset($form_state["values"]["max_times_applied"]) 
-			? $form_state["values"]["max_times_applied"] : MAX_TIMES_APPLIED_DEFAULT,
-		"#size" => 7,
-		"#required" => TRUE,
-	);
-
-	$form["can_be_combined_with_other_discounts"] = array(
-		"#type" => "checkbox",
-		"#title" => t("Can be combined with other discounts"),
-		"#description" => t("Whether or not this discount will be applied if other discounts are."),
-		"#default_value" => isset($form_state["values"]["can_be_combined_with_other_discounts"]) 
-			? $form_state["values"]["can_be_combined_with_other_discounts"] : CAN_BE_COMBINED_WITH_OTHER_DISCOUNTS_DEFAULT,
-	);
-
-	$form["max_uses"] = array(
-		"#type" => "textfield",
-		"#title" => t("Max uses"),
-		"#description" => t("Number of times this discount can be applied (0 for unlimited)."),
-		"#default_value" => isset($form_state["values"]["max_uses"]) 
-			? $form_state["values"]["max_uses"] : MAX_USES_DEFAULT,
-		"#size" => 7,
-		"#required" => TRUE,
-	);
-
-	$form["max_uses_per_user"] = array(
-		"#type" => "textfield",
-		"#title" => t("Max uses per user"),
-		"#description" => t("Number of times this discount can be applied to a particular user (0 for unlimited)."),
-		"#default_value" => isset($form_state["values"]["max_uses_per_user"]) 
-			? $form_state["values"]["max_uses_per_user"] : MAX_USES_PER_USER_DEFAULT,
-		"#size" => 7,
-		"#required" => TRUE,
-	);
-
-	$form["max_uses_per_code"] = array(
-		"#type" => "textfield",
-		"#title" => t("Max uses per code"),
-		"#description" => t("Number of times this discount can be applied to a particular code (0 for unlimited).  Note: if 'Max uses' (if set) still applies as overall maximum number of uses for this discount."),
-		"#default_value" => isset($form_state["values"]["max_uses_per_code"]) 
-			? $form_state["values"]["max_uses_per_code"] : MAX_USES_PER_CODE_DEFAULT,
-		"#size" => 7,
-		"#required" => TRUE,
-	);
-
-	$has_expiration = isset($form_state["values"]["has_expiration"]) ? $form_state["values"]["has_expiration"] : HAS_EXPIRATION_DEFAULT;
-	$display_string = ($has_expiration) ? "" : " style='display:none'";
-
-	$expiration_container_id = "expiration-container-" . $seed;
-	$expiration_prefix = sprintf("<div id='%s' onclick='if ( jQuery(\"#%s input[type=\\\"checkbox\\\"]\").attr(\"checked\") )"
-		. "{ jQuery(\"#%s .expiration-container\").slideDown(); }"
-		. "else { jQuery(\"#%s .expiration-container\").slideUp(); }'>", 
-		$expiration_container_id, $expiration_container_id, $expiration_container_id, $expiration_container_id, $expiration_container_id, $expiration_container_id);
-
-	$form["expiration_header"] = array(
-		"#type" => "hidden",
-		"#prefix" => $expiration_prefix,
-	);
-
-	$form["has_expiration"] = array(
-		"#type" => "checkbox",
-		"#title" => t("Discount expires"),
-		"#description" => t("Whether or not this discount will be applied if other discounts are."),
-		"#default_value" => $has_expiration,
-	);
-
-	$expiration = isset($form_state["values"]["expiration"]) 
-		? $form_state["values"]["expiration"] : time();
-	$form["expiration"] = array(
-		"#type" => "date_popup",
-		"#date_type" => "DATE_UNIX",
-		"#title" => t("Discount expiration")
-			. sprintf("<span title='" . t("This field is required.") . "' class='form-required'>*</span>"),
-		"#description" => t("Date and time when the discount expires."),
-		"#default_value" => date("Y-m-d H:i:s", $expiration),
-		"#prefix" => sprintf("<div class='expiration-container'%s>", $display_string),
-		"#suffix" => "</div>",
-	);
-
-	$form["expiration_footer"] = array(
-		"#type" => "hidden",
-		"#suffix" => "</div>",
-	);
-
-	$is_published = isset($form_state["values"]["is_published"]) 
-		? $form_state["values"]["is_published"] : IS_PUBLISHED_DEFAULT;
-	$form["is_published"] = array(
-		"#type" => "checkbox",
-		"#title" => t("Is published"),
-		"#description" => t("Convenience flag to state whether code is published on site or not."),
-		"#default_value" => $is_published,
-	);
-
-	//Add custom weight range [-50, 50]
-	$options = array();
-	for ($i = -50; $i <= 50; $i++)
-		$options[$i] = $i;
-	$form["weight"] = array(
-		"#type" => "select",
-		"#title" => t("Weight"),
-		"#description" => t("Lighter discounts are applied to an order first. This value is unimportant if there are no discounts on discount line items."),
-		"#options" => $options,
-		"#default_value" => isset($form_state["values"]["weight"]) ? $form_state["values"]["weight"] : 0,
-	);
+function uc_discounts_form($form_state, $discount_id = 0) {
+  $form           = array();
+  $form_submitted = $form_state["submitted"];
+  $is_edit        = $discount_id != 0;
+  $seed           = rand(1, 1000000);
+
+  if (!$form_submitted && $is_edit) {
+
+    $form_state["values"] = db_fetch_array(db_query("SELECT * FROM {uc_discounts} WHERE discount_id=%d", $discount_id));
+
+  }
+
+  $form["discount_id"] = array("#type" => "hidden", "#value" => $form_state["values"]["discount_id"]);
+
+  $form["name"] = array(
+    "#type" => "textfield",
+    "#title" => t("Name"),
+    "#description" => t("Shown in admin reports and logs."),
+    "#default_value" => $form_state["values"]["name"],
+    "#size" => 50,
+    "#required" => TRUE,
+  );
+
+  $form["short_description"] = array(
+    "#type" => "textfield",
+    "#title" => t("Short Description"),
+    "#description" => t("Description displayed to user during checkout and in order review."),
+    "#default_value" => $form_state["values"]["short_description"],
+    "#size" => 75,
+    "#required" => TRUE,
+  );
+
+  $form["description"] = array(
+    "#type" => "textfield",
+    "#title" => t("Description"),
+    "#description" => t("Internal description for discount administrators."),
+    "#default_value" => $form_state["values"]["description"],
+    "#size" => 75,
+  );
+
+  $form["qualifying_type"] = array(
+    "#type" => "select",
+    "#title" => t("Qualifying type"),
+    "#description" => t("The amount used to determine if a cart qualifies for this discount."),
+    "#options" => qualifying_type_options(),
+    "#default_value" => $form_state["values"]["qualifying_type"],
+  );
+
+  $form["qualifying_amount"] = array(
+    "#type" => "textfield",
+    "#title" => t("Qualifying amount"),
+    "#description" => t("The amount required to qualify for the discount.	E.g. 50 (for $50), 5 (for 5 items).  Remember for a discount like 'buy 4 get 1 free' the qualifying amount is '5'."),
+    "#default_value" => $form_state["values"]["qualifying_amount"],
+    "#size" => 15,
+    "#required" => TRUE,
+  );
+
+
+  $has_qualifying_amount_max = isset($form_state["values"]["has_qualifying_amount_max"]) ? $form_state["values"]["has_qualifying_amount_max"] : HAS_QUALIFYING_AMOUNT_MAX_DEFAULT;
+  $display_string = ($has_qualifying_amount_max) ? "" : " style='display:none'";
+
+  $qualifying_amount_max_container_id = "qualifying-amount-max-container-". $seed;
+  $qualifying_amount_max_prefix = sprintf("<div id='%s' onclick='if ( jQuery(\"#%s input[type=\\\"checkbox\\\"]\").attr(\"checked\") {  )" . "{ jQuery(\"#%s .qualifying-amount-max-container\").slideDown(); }" . "else { jQuery(\"#%s .qualifying-amount-max-container\").slideUp();} }'>",
+    $qualifying_amount_max_container_id, $qualifying_amount_max_container_id,
+    $qualifying_amount_max_container_id, $qualifying_amount_max_container_id,
+    $qualifying_amount_max_container_id, $qualifying_amount_max_container_id
+  );
+
+  $form["qualifying_amount_max_header"] = array(
+    "#type" => "hidden",
+    "#prefix" => $qualifying_amount_max_prefix,
+  );
+
+  $form["has_qualifying_amount_max"] = array(
+    "#type" => "checkbox",
+    "#title" => t("Has max qualifying amount."),
+    "#description" => t("Whether or not discount contains maximum qualifying amount."),
+    "#default_value" => $has_qualifying_amount_max,
+  );
+
+  //Get current discount qualifying_amount_max
+  $qualifying_amount_max = $form_state["values"]["role_ids"];
+
+  //Create qualifying_amount_max form element
+  $form["qualifying_amount_max"] = array(
+    "#type" => "textfield",
+    "#title" => t("Maximum qualifying amount"),
+    "#description" => t("Maximum amount to NOT exceed to qualify for the discount.  E.g. 50 (for $50), 5 (for 5 items)."),
+    "#default_value" => $form_state["values"]["qualifying_amount_max"],
+    "#size" => 15,
+    "#required" => FALSE,
+    "#prefix" => sprintf("<div class='qualifying-amount-max-container'%s>", $display_string),
+    "#suffix" => "</div>",
+  );
+
+  $form["qualifying_amount_max_footer"] = array(
+    "#type" => "hidden",
+    "#suffix" => "</div>",
+  );
+
+
+  $form["discount_type"] = array(
+    "#type" => "select",
+    "#title" => t("Discount type"),
+    "#description" => t("Type of discount to apply."),
+    "#options" => discount_type_options(),
+    "#default_value" => $form_state["values"]["discount_type"],
+  );
+
+  $form["discount_amount"] = array(
+    "#type" => "textfield",
+    "#title" => t("Discount amount"),
+    "#description" => t("The amount of discount.	E.g. 50 (for $50), 5 (for 5 items), or 0.05 (for 5%)"),
+    "#default_value" => $form_state["values"]["discount_amount"],
+    "#size" => 15,
+    "#required" => TRUE,
+  );
+
+  $requires_code = isset($form_state["values"]["requires_code"]) ? $form_state["values"]["requires_code"] : REQUIRES_CODE_DEFAULT;
+  $display_string = ($requires_code) ? "" : " style='display:none'";
+
+  $codes_container_id = "codes-container-". $seed;
+  $codes_prefix = sprintf("<div id='%s' onclick='if ( jQuery(\"#%s input[type=\\\"checkbox\\\"]\").attr(\"checked\") {  )" . "{ jQuery(\"#%s .codes-container\").slideDown(); }" . "else { jQuery(\"#%s .codes-container\").slideUp();} }'>",
+    $codes_container_id, $codes_container_id, $codes_container_id, $codes_container_id, $codes_container_id, $codes_container_id
+  );
+
+  $form["codes_header"] = array(
+    "#type" => "hidden",
+    "#prefix" => $codes_prefix,
+  );
+
+  $form["requires_code"] = array(
+    "#type" => "checkbox",
+    "#title" => t("Require(s) code to activate discount."),
+    "#default_value" => $requires_code,
+  );
+
+  //Determine codes default value
+  $codes_string = NULL;
+  if (isset($form_state["values"]["codes"])) {
+    $codes_string = $form_state["values"]["codes"];
+  }
+  else {
+    $codes = array();
+    if ($is_edit) {
+      $codes = get_codes_for_discount($discount_id);
+    }
+    $codes_string = create_codes_string($codes);
+  }
+
+  $form["codes"] = array(
+    "#type" => "textarea",
+    "#title" => t("Discount codes") . sprintf("<span title='". t("This field is required.") ."' class='form-required'>*</span>"),
+    "#description" => t("Enter discount codes in box above, one code per line.  Spaces are permitted but may confuse consumers. Note codes will be trimmed."),
+    "#default_value" => $codes_string,
+    "#rows" => 5,
+    "#prefix" => sprintf("<div class='codes-container'%s>", $display_string) ."<div class='discount-codes-wrapper'>",
+    "#suffix" => "</div></div>",
+  );
+
+  $form["codes_footer"] = array(
+    "#type" => "hidden",
+    "#suffix" => "</div>",
+  );
+
+  $filter_type = isset($form_state["values"]["filter_type"]) ? $form_state["values"]["filter_type"] : FILTER_TYPE_DEFAULT;
+  $products_display_string = ($filter_type == FILTER_TYPE_PRODUCTS) ? "" : " style='display:none'";
+  $terms_display_string = ($filter_type == FILTER_TYPE_TERMS) ? "" : " style='display:none'";
+  $skus_display_string = ($filter_type == FILTER_TYPE_SKUS) ? "" : " style='display:none'";
+
+  $filter_type_container_id = "filter-type-container-". $seed;
+  $filter_type_prefix = sprintf(
+    "<div id='%s' onclick='value = jQuery(\"#%s select\").val();" . "if (value == %d) { jQuery(\"#%s .products-container\").slideDown(); jQuery(\"#%s .terms-container\").slideUp(); jQuery(\"#%s .skus-container\").slideUp(); }" . "if (value == %d) { jQuery(\"#%s .products-container\").slideUp(); jQuery(\"#%s .terms-container\").slideDown(); jQuery(\"#%s .skus-container\").slideUp(); }" . "if (value == %d) { jQuery(\"#%s .products-container\").slideUp(); jQuery(\"#%s .terms-container\").slideUp(); jQuery(\"#%s .skus-container\").slideDown(); }'>",
+    $filter_type_container_id, $filter_type_container_id,
+    FILTER_TYPE_PRODUCTS, $filter_type_container_id, $filter_type_container_id, $filter_type_container_id,
+    FILTER_TYPE_TERMS, $filter_type_container_id, $filter_type_container_id, $filter_type_container_id,
+    FILTER_TYPE_SKUS, $filter_type_container_id, $filter_type_container_id, $filter_type_container_id
+  );
+
+  $form["filter_type_header"] = array(
+    "#type" => "hidden",
+    "#prefix" => $filter_type_prefix,
+  );
+
+  //Create filter_type form element
+  $options = array();
+  $options[FILTER_TYPE_PRODUCTS] = t("Filter By Products");
+  $options[FILTER_TYPE_TERMS] = t("Filter By Terms");
+  $options[FILTER_TYPE_SKUS] = t("Filter By SKUs");
+  $form["filter_type"] = array(
+    "#type" => "select",
+    "#title" => t("Filter Type"),
+    "#description" => t("Determine whether to filter by products, terms or SKUs."),
+    "#options" => $options,
+    "#default_value" => $filter_type,
+    "#required" => TRUE,
+  );
+
+  //Get current discount products
+  $product_ids = null;
+  if (isset($form_state["values"]["product_ids"])) {
+    $product_ids = $form_state["values"]["product_ids"];
+  }
+  elseif ($is_edit) {  $product_ids = get_product_ids_for_discount($discount_id, FALSE);}
+
+  //Create products form element
+  $options = array();
+  $result = db_query("SELECT n.nid as nid, n.title as title, p.model as model" . " FROM {uc_products} p INNER JOIN {node} n ON p.nid=n.nid ORDER BY title"
+  );
+  $options[ALL_PRODUCTS] = t("<All Products>");
+  while ($row = db_fetch_object($result)) $options[$row->nid] = $row->title ." (". $row->model .")";
+  $form["product_ids"] = array(
+    "#type" => "select",
+    "#title" => t("Products") . sprintf("<span title='". t("This field is required.") ."' class='form-required'>*</span>"),
+    "#description" => t("Select all products this discount applies to or &lt;All Products&gt; to apply to all products."),
+    "#options" => $options,
+    "#default_value" => $product_ids,
+    "#multiple" => TRUE,
+    "#prefix" => sprintf("<div class='products-container'%s>", $products_display_string),
+    "#suffix" => "</div>",
+  );
+
+  //Get current discount terms
+  $term_ids = null;
+  if (isset($form_state["values"]["term_ids"])) {
+    $term_ids = $form_state["values"]["term_ids"];
+  }
+  elseif ($is_edit) {  $term_ids = get_term_ids_for_discount($discount_id, FALSE);}
+
+  //Create terms form element
+  $options            = array();
+  $result             = db_query("SELECT tid, name FROM {term_data} ORDER BY weight");
+  $options[ALL_TERMS] = t("<All Terms>");
+  while ($row = db_fetch_object($result)) $options[$row->tid] = $row->name;
+  $form["term_ids"] = array(
+    "#type" => "select",
+    "#title" => t("Terms") . sprintf("<span title='". t("This field is required.") ."' class='form-required'>*</span>"),
+    "#description" => t("Select all terms this discount applies to or &lt;All Terms&gt; to apply to all terms.  Selections are <b>not</b> recursive."),
+    "#options" => $options,
+    "#default_value" => $term_ids,
+    "#multiple" => TRUE,
+    "#prefix" => sprintf("<div class='terms-container'%s>", $terms_display_string),
+    "#suffix" => "</div>",
+  );
+
+  //Get current discount SKUs
+  $skus = null;
+  if (isset($form_state["values"]["skus"])) {
+    $skus = $form_state["values"]["skus"];
+  }
+  elseif ($is_edit) {  $skus = get_skus_for_discount($discount_id, FALSE);}
+
+  //Create SKUs form element
+  $options           = array();
+  $result            = db_query("SELECT p.model, n.title FROM {uc_products} p, {node} n WHERE p.nid=n.nid ORDER BY p.model");
+  $options[ALL_SKUS] = t("<All SKUs>");
+  while ($row = db_fetch_object($result)) $options[$row->model] = $row->model ." (". $row->title .")";
+  $form["skus"] = array(
+    "#type" => "select",
+    "#title" => t("SKUs") . sprintf("<span title='". t("This field is required.") ."' class='form-required'>*</span>"),
+    "#description" => t("Select all SKUs this discount applies to or &lt;All SKUs&gt; to apply to all SKUs.  Selections are <b>not</b> recursive."),
+    "#options" => $options,
+    "#default_value" => $skus,
+    "#multiple" => TRUE,
+    "#prefix" => sprintf("<div class='skus-container'%s>", $skus_display_string),
+    "#suffix" => "</div>",
+  );
+
+  $form["filter_type_footer"] = array(
+    "#type" => "hidden",
+    "#suffix" => "</div>",
+  );
+
+  $has_role_filter = isset($form_state["values"]["has_role_filter"]) ? $form_state["values"]["has_role_filter"] : HAS_ROLE_FILTER_DEFAULT;
+  $display_string = ($has_role_filter) ? "" : " style='display:none'";
+
+  $roles_container_id = "roles-container-". $seed;
+  $roles_prefix = sprintf("<div id='%s' onclick='if ( jQuery(\"#%s input[type=\\\"checkbox\\\"]\").attr(\"checked\") {  )" . "{ jQuery(\"#%s .roles-container\").slideDown(); }" . "else { jQuery(\"#%s .roles-container\").slideUp();} }'>",
+    $roles_container_id, $roles_container_id, $roles_container_id, $roles_container_id, $roles_container_id, $roles_container_id
+  );
+
+  $form["roles_header"] = array(
+    "#type" => "hidden",
+    "#prefix" => $roles_prefix,
+  );
+
+  $form["has_role_filter"] = array(
+    "#type" => "checkbox",
+    "#title" => t("Filter based on roles."),
+    "#default_value" => $has_role_filter,
+  );
+
+  //Get current discount roles
+  $role_ids = null;
+  if (isset($form_state["values"]["role_ids"])) {
+    $role_ids = $form_state["values"]["role_ids"];
+  }
+  elseif ($is_edit) {  $role_ids = get_role_ids_for_discount($discount_id, FALSE);}
+
+  //Create roles form element
+  $options = array();
+  //$result = db_query("SELECT rid, name FROM {role} WHERE rid<>%d AND rid<>%d ORDER BY rid", DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID);
+  $result = db_query("SELECT rid, name FROM {role} ORDER BY rid");
+  $options[ALL_ROLES] = t("<All Roles>");
+  while ($row = db_fetch_object($result)) $options[$row->rid] = $row->name;
+  $form["role_ids"] = array(
+    "#type" => "select",
+    "#title" => t("Roles") . sprintf("<span title='". t("This field is required.") ."' class='form-required'>*</span>"),
+    "#description" => t("Select all roles this discount applies to or &lt;All Roles&gt; to apply to all roles."),
+    "#options" => $options,
+    "#default_value" => $role_ids,
+    "#multiple" => TRUE,
+    "#prefix" => sprintf("<div class='roles-container'%s>", $display_string),
+    "#suffix" => "</div>",
+  );
+
+  $form["roles_footer"] = array(
+    "#type" => "hidden",
+    "#suffix" => "</div>",
+  );
+
+  $form["requires_single_product_to_qualify"] = array(
+    "#type" => "checkbox",
+    "#title" => t("Require single product to qualify."),
+    "#description" => t("Requires a single product to meet the qualifying requirements to receive discount.	Otherwise qualifying requirements may be met by the combination of selected products."),
+    "#default_value" => isset($form_state["values"]["requires_single_product_to_qualify"]) ? $form_state["values"]["requires_single_product_to_qualify"] : REQUIRES_SINGLE_PRODUCT_TO_QUALIFY_DEFAULT,
+  );
+
+  $form["max_times_applied"] = array(
+    "#type" => "textfield",
+    "#title" => t("Maximum times applied"),
+    "#description" => t("Number of times this discount can be applied to a single cart (0 for unlimited).  Does not apply to 'Percent off' discounts."),
+    "#default_value" => isset($form_state["values"]["max_times_applied"])
+     ? $form_state["values"]["max_times_applied"] : MAX_TIMES_APPLIED_DEFAULT,
+    "#size" => 7,
+    "#required" => TRUE,
+  );
+
+  $form["can_be_combined_with_other_discounts"] = array(
+    "#type" => "checkbox",
+    "#title" => t("Can be combined with other discounts"),
+    "#description" => t("Whether or not this discount will be applied if other discounts are."),
+    "#default_value" => isset($form_state["values"]["can_be_combined_with_other_discounts"])
+     ? $form_state["values"]["can_be_combined_with_other_discounts"] : CAN_BE_COMBINED_WITH_OTHER_DISCOUNTS_DEFAULT,
+  );
+
+  $form["max_uses"] = array(
+    "#type" => "textfield",
+    "#title" => t("Max uses"),
+    "#description" => t("Number of times this discount can be applied (0 for unlimited)."),
+    "#default_value" => isset($form_state["values"]["max_uses"])
+     ? $form_state["values"]["max_uses"] : MAX_USES_DEFAULT,
+    "#size" => 7,
+    "#required" => TRUE,
+  );
+
+  $form["max_uses_per_user"] = array(
+    "#type" => "textfield",
+    "#title" => t("Max uses per user"),
+    "#description" => t("Number of times this discount can be applied to a particular user (0 for unlimited)."),
+    "#default_value" => isset($form_state["values"]["max_uses_per_user"])
+     ? $form_state["values"]["max_uses_per_user"] : MAX_USES_PER_USER_DEFAULT,
+    "#size" => 7,
+    "#required" => TRUE,
+  );
+
+  $form["max_uses_per_code"] = array(
+    "#type" => "textfield",
+    "#title" => t("Max uses per code"),
+    "#description" => t("Number of times this discount can be applied to a particular code (0 for unlimited).  Note: if 'Max uses' (if set) still applies as overall maximum number of uses for this discount."),
+    "#default_value" => isset($form_state["values"]["max_uses_per_code"])
+     ? $form_state["values"]["max_uses_per_code"] : MAX_USES_PER_CODE_DEFAULT,
+    "#size" => 7,
+    "#required" => TRUE,
+  );
+
+  $has_expiration = isset($form_state["values"]["has_expiration"]) ? $form_state["values"]["has_expiration"] : HAS_EXPIRATION_DEFAULT;
+  $display_string = ($has_expiration) ? "" : " style='display:none'";
+
+  $expiration_container_id = "expiration-container-". $seed;
+  $expiration_prefix = sprintf("<div id='%s' onclick='if ( jQuery(\"#%s input[type=\\\"checkbox\\\"]\").attr(\"checked\") {  )" . "{ jQuery(\"#%s .expiration-container\").slideDown(); }" . "else { jQuery(\"#%s .expiration-container\").slideUp();} }'>",
+    $expiration_container_id, $expiration_container_id, $expiration_container_id, $expiration_container_id, $expiration_container_id, $expiration_container_id
+  );
+
+  $form["expiration_header"] = array(
+    "#type" => "hidden",
+    "#prefix" => $expiration_prefix,
+  );
+
+  $form["has_expiration"] = array(
+    "#type" => "checkbox",
+    "#title" => t("Discount expires"),
+    "#description" => t("Whether or not this discount will be applied if other discounts are."),
+    "#default_value" => $has_expiration,
+  );
+
+  $expiration = isset($form_state["values"]["expiration"]) ? $form_state["values"]["expiration"] : time();
+  $form["expiration"] = array(
+    "#type" => "date_popup",
+    "#date_type" => "DATE_UNIX",
+    "#title" => t("Discount expiration") . sprintf("<span title='". t("This field is required.") ."' class='form-required'>*</span>"),
+    "#description" => t("Date and time when the discount expires."),
+    "#default_value" => date("Y-m-d H:i:s", $expiration),
+    "#prefix" => sprintf("<div class='expiration-container'%s>", $display_string),
+    "#suffix" => "</div>",
+  );
+
+  $form["expiration_footer"] = array(
+    "#type" => "hidden",
+    "#suffix" => "</div>",
+  );
+
+  $is_published = isset($form_state["values"]["is_published"]) ? $form_state["values"]["is_published"] : IS_PUBLISHED_DEFAULT;
+  $form["is_published"] = array(
+    "#type" => "checkbox",
+    "#title" => t("Is published"),
+    "#description" => t("Convenience flag to state whether code is published on site or not."),
+    "#default_value" => $is_published,
+  );
+
+  //Add custom weight range [-50, 50]
+  $options = array();
+  for ($i = -50; $i <= 50; $i++) $options[$i] = $i;
+  $form["weight"] = array(
+    "#type" => "select",
+    "#title" => t("Weight"),
+    "#description" => t("Lighter discounts are applied to an order first. This value is unimportant if there are no discounts on discount line items."),
+    "#options" => $options,
+    "#default_value" => isset($form_state["values"]["weight"]) ? $form_state["values"]["weight"] : 0,
+  );
 
-	$form["submit"] = array( "#type" => "submit", "#value" => t("Submit") );
+  $form["submit"] = array("#type" => "submit", "#value" => t("Submit"));
 
-	return $form;
+  return $form;
 }
 
 /**
  * Validate handler for uc_discounts_form().
  */
-function uc_discounts_form_validate($form, &$form_state)
-{
-	$values = $form_state["values"];
-	$has_errors = FALSE;
-
-	if ( $values["requires_code"] && empty($values["codes"]) )
-	{
-	    form_set_error( "codes", t("Discounts codes are required because 'Require(s) code' is checked") );
-	    $has_errors = TRUE;
-	}
-
-
-	//Check qualifying_amount_max (if necessary)
-	if ($values["has_qualifying_amount_max"])
-	{
-		if (  ( $index = strpos($values["qualifying_amount_max"], "%") ) !== FALSE  )
-			$value = substr($values["qualifying_amount_max"], 0, $index);
-		else
-			$value = $values["qualifying_amount_max"];
-
-		if ( !is_numeric($value) )
-		{
-			form_set_error( "qualifying_amount_max", t("Max qualifying amount is required because 'Has max qualifying amount' is checked.") );
-			$has_errors = TRUE;
-		}
-	}
-
-
-	//Check discount_amount
-
-	if (  ( $index = strpos($values["discount_amount"], "%") ) !== FALSE  )
-		$value = substr($values["discount_amount"], 0, $index);
-	else
-		$value = $values["discount_amount"];
-
-	if ( !is_numeric($value) )
-	{
-		form_set_error( "discount_amount", t("Discount amount must be integer, decimal or percentage.") );
-		$has_errors = TRUE;
-	}
-
-
-	if ($values["filter_type"] == FILTER_TYPE_PRODUCTS)
-	{
-		if ( empty($values["product_ids"]) )
-		{
-			form_set_error( "product_ids", t("Products are required because of 'Filter Type' value") );
-			$has_errors = TRUE;
-		}
-	}
-	elseif ($values["filter_type"] == FILTER_TYPE_TERMS)
-	{
-		if ( empty($values["term_ids"]) )
-		{
-			form_set_error( "term_ids", t("Terms are required because of 'Filter Type' value") );
-			$has_errors = TRUE;
-		}
-	}
-	elseif ($values["filter_type"] == FILTER_TYPE_SKUS)
-	{
-		if ( empty($values["skus"]) )
-		{
-			form_set_error( "skus", t("SKUs are required because of 'Filter Type' value") );
-			$has_errors = TRUE;
-		}
-	}
-	else
-	{
-		form_set_error( "filter_type", t("Invalid filter type value") );
-		$has_errors = TRUE;
-	}
-
-	if ( $values["has_role_filter"] && empty($values["role_ids"]) )
-	{
-	    form_set_error( "roles", t("Roles are required because 'Filter based on roles' is checked") );
-	    $has_errors = TRUE;
-	}
-	
-	if ( $values["has_expiration"] && !date_is_valid($values["expiration"]) )
-	{
-		form_set_error( "expiration", t("Expiration are required because 'Discount expires' is checked") );
-	    $has_errors = TRUE;
-	}
-	
-	//Form requires rebuilding form so codes and expiration blocks will display correctly
-	if ($has_errors)
-		$form_state["rebuild"] = TRUE;
+function uc_discounts_form_validate($form, &$form_state) {
+  $values = $form_state["values"];
+  $has_errors = FALSE;
+
+  if ($values["requires_code"] && empty($values["codes"])) {
+    form_set_error("codes", t("Discounts codes are required because 'Require(s) code' is checked"));
+    $has_errors = TRUE;
+  }
+
+
+  //Check qualifying_amount_max (if necessary)
+  if ($values["has_qualifying_amount_max"]) {
+    if (($index = strpos($values["qualifying_amount_max"], "%")) !== FALSE) {
+      $value = substr($values["qualifying_amount_max"], 0, $index);
+    }
+    else $value = $values["qualifying_amount_max"];
+
+    if (!is_numeric($value)) {
+      form_set_error("qualifying_amount_max", t("Max qualifying amount is required because 'Has max qualifying amount' is checked."));
+      $has_errors = TRUE;
+    }
+  }
+
+
+  //Check discount_amount
+
+  if (($index = strpos($values["discount_amount"], "%")) !== FALSE) {
+
+    $value = substr($values["discount_amount"], 0, $index);
+
+  }
+  else $value = $values["discount_amount"];
+
+  if (!is_numeric($value)) {
+    form_set_error("discount_amount", t("Discount amount must be integer, decimal or percentage."));
+    $has_errors = TRUE;
+  }
+
+
+  if ($values["filter_type"] == FILTER_TYPE_PRODUCTS) {
+    if (empty($values["product_ids"])) {
+      form_set_error("product_ids", t("Products are required because of 'Filter Type' value"));
+      $has_errors = TRUE;
+    }
+  }
+  elseif ($values["filter_type"] == FILTER_TYPE_TERMS) {
+    if (empty($values["term_ids"])) {
+      form_set_error("term_ids", t("Terms are required because of 'Filter Type' value"));
+      $has_errors = TRUE;
+    }
+  }
+  elseif ($values["filter_type"] == FILTER_TYPE_SKUS) {
+    if (empty($values["skus"])) {
+      form_set_error("skus", t("SKUs are required because of 'Filter Type' value"));
+      $has_errors = TRUE;
+    }
+  }
+  else {
+    form_set_error("filter_type", t("Invalid filter type value"));
+    $has_errors = TRUE;
+  }
+
+  if ($values["has_role_filter"] && empty($values["role_ids"])) {
+    form_set_error("roles", t("Roles are required because 'Filter based on roles' is checked"));
+    $has_errors = TRUE;
+  }
+
+  if ($values["has_expiration"] && !date_is_valid($values["expiration"])) {
+    form_set_error("expiration", t("Expiration are required because 'Discount expires' is checked"));
+    $has_errors = TRUE;
+  }
+
+  //Form requires rebuilding form so codes and expiration blocks will display correctly
+  if ($has_errors) {
+    $form_state["rebuild"] = TRUE;
+  }
 }
 
 /**
  * Submit handler for uc_discounts_form().
  */
-function uc_discounts_form_submit($form, &$form_state)
-{
-	$op = isset($form_state["values"]["op"]) ? $form_state["values"]["op"] : "";
-	if ( $op == t("Submit") )
-	{
-		$codes = explode("\n", $form_state["values"]["codes"]);
-
-		$product_ids = ($form_state["values"]["filter_type"] == FILTER_TYPE_PRODUCTS) 
-			? $form_state["values"]["product_ids"] : array();
-
-		//If products container "all products", insert only all products row (product_id=<ALL_PRODUCTS>)
-		if ( in_array(ALL_PRODUCTS, $product_ids) )
-			$product_ids = array(ALL_PRODUCTS);
-
-		$term_ids = ($form_state["values"]["filter_type"] == FILTER_TYPE_TERMS) 
-			? $form_state["values"]["term_ids"] : array();
-
-		//If terms container "all terms", insert only all terms row (term_id=<ALL_TERMS>)
-		if ( in_array(ALL_TERMS, $term_ids) )
-			$term_ids = array(ALL_TERMS);
-
-		$skus = ($form_state["values"]["filter_type"] == FILTER_TYPE_SKUS) 
-			? $form_state["values"]["skus"] : array();
-
-		//If skus container "all SKUs", insert only all SKUs row (sku=<ALL_SKUS>)
-		if ( in_array(ALL_SKUS, $skus) )
-			$skus = array(ALL_SKUS);
-
-		$role_ids = ($form_state["values"]["has_role_filter"]) 
-			? $form_state["values"]["role_ids"] : array();
-
-		//If roles container "all roles", insert only all roles row (role_id=<ALL_ROLES>)
-		if ( in_array(ALL_ROLES, $role_ids) )
-			$role_ids = array(ALL_ROLES);
-		
-		//Set expiration to a valid value because it is not nullable
-		if ( isset($form_state["values"]["expiration"]) )
-			$expiration = date_convert(date_make_date($form_state["values"]["expiration"]), DATE_OBJECT, DATE_UNIX);
-		else
-			$expiration = 0;
-
-		//Set discount_amount
-		if (  ( $index = strpos($form_state["values"]["discount_amount"], "%") ) !== FALSE  )
-			$discount_amount = floatval( substr($form_state["values"]["discount_amount"], 0, $index) ) / 100;
-		else
-			$discount_amount = floatval($form_state["values"]["discount_amount"]);
-
-		if ( empty($form_state["values"]["discount_id"]) )
-		{
-			//Insert base discount
-			$discount_id = uc_discounts_insert($form_state["values"]["name"], 
-				$form_state["values"]["short_description"], 
-				$form_state["values"]["description"], 
-				$form_state["values"]["qualifying_type"], 
-				$form_state["values"]["qualifying_amount"],
-				$form_state["values"]["has_qualifying_amount_max"],
-				$form_state["values"]["qualifying_amount_max"],
-				$form_state["values"]["discount_type"],
-				$discount_amount,
-				$form_state["values"]["requires_code"],
-				$form_state["values"]["filter_type"],
-				$form_state["values"]["has_role_filter"],
-				$form_state["values"]["requires_single_product_to_qualify"],
-				$form_state["values"]["max_times_applied"],
-				$form_state["values"]["can_be_combined_with_other_discounts"],
-				$form_state["values"]["max_uses"],
-				$form_state["values"]["max_uses_per_user"],
-				$form_state["values"]["max_uses_per_code"],
-				$form_state["values"]["has_expiration"],
-				$expiration,
-				$form_state["values"]["is_published"],
-				$form_state["values"]["weight"]);
-
-			db_last_insert_id("uc_discounts", "discount_id");
-		}
-		else
-		{
-			$discount_id = $form_state["values"]["discount_id"];
-
-			//Update base discount
-			uc_discounts_update($discount_id,
-				$form_state["values"]["name"], 
-				$form_state["values"]["short_description"], 
-				$form_state["values"]["description"], 
-				$form_state["values"]["qualifying_type"], 
-				$form_state["values"]["qualifying_amount"],
-				$form_state["values"]["has_qualifying_amount_max"],
-				$form_state["values"]["qualifying_amount_max"],
-				$form_state["values"]["discount_type"],
-				$discount_amount,
-				$form_state["values"]["requires_code"],
-				$form_state["values"]["filter_type"],
-				$form_state["values"]["has_role_filter"],
-				$form_state["values"]["requires_single_product_to_qualify"],
-				$form_state["values"]["max_times_applied"],
-				$form_state["values"]["can_be_combined_with_other_discounts"],
-				$form_state["values"]["max_uses"],
-				$form_state["values"]["max_uses_per_user"],
-				$form_state["values"]["max_uses_per_code"],
-				$form_state["values"]["has_expiration"],
-				$expiration,
-				$form_state["values"]["is_published"],
-				$form_state["values"]["weight"]);
-			
-			//Delete existing database codes
-			uc_discounts_codes_delete($discount_id);
-
-			//Delete existing database products
-			uc_discounts_products_delete($discount_id);
-
-			//Delete existing database terms
-			uc_discounts_terms_delete($discount_id);
-
-			//Delete existing database SKUs
-			uc_discounts_skus_delete($discount_id);
-
-			//Delete existing database roles
-			uc_discounts_roles_delete($discount_id);
-		}
-
-		//Insert codes (if necessary)
-		if ($form_state["values"]["requires_code"])
-		{
-			foreach ($codes as $code)
-			{
-				$code = trim($code);
-				if ( empty($code) )
-					continue;
-				uc_discounts_codes_insert($discount_id, $code);
-			}
-		}
-
-		//Insert products (if necessary)
-		if ($form_state["values"]["filter_type"] == FILTER_TYPE_PRODUCTS)
-		{
-			foreach ($product_ids as $product_id)
-			{
-				if ( empty($product_id) )
-					continue;
-				uc_discounts_products_insert($discount_id, $product_id);
-			}
-		}
-		//Insert terms (if necessary)
-		elseif ($form_state["values"]["filter_type"] == FILTER_TYPE_TERMS)
-		{
-			foreach ($term_ids as $term_id)
-			{
-				if ( empty($term_id) )
-					continue;
-				uc_discounts_terms_insert($discount_id, $term_id);
-			}
-		}
-		//Insert SKUs (if necessary)
-		elseif ($form_state["values"]["filter_type"] == FILTER_TYPE_SKUS)
-		{
-			foreach ($skus as $sku)
-			{
-				//Empty SKU is ALL_SKUS
-				uc_discounts_skus_insert($discount_id, $sku);
-			}
-		}
-
-		//Insert roles
-		if ($form_state["values"]["has_role_filter"])
-		{
-			foreach ($role_ids as $role_id)
-			{
-				if ( empty($role_id) )
-					continue;
-				uc_discounts_roles_insert($discount_id, $role_id);
-			}
-		}
+function uc_discounts_form_submit($form, &$form_state) {
+  $op = isset($form_state["values"]["op"]) ? $form_state["values"]["op"] : "";
+  if ($op == t("Submit")) {
+    $codes = explode("\n", $form_state["values"]["codes"]);
+
+    $product_ids = ($form_state["values"]["filter_type"] == FILTER_TYPE_PRODUCTS) ? $form_state["values"]["product_ids"] : array();
+
+    //If products container "all products", insert only all products row (product_id=<ALL_PRODUCTS>)
+    if (in_array(ALL_PRODUCTS, $product_ids)) {
+      $product_ids = array(ALL_PRODUCTS);
+    }
+
+    $term_ids = ($form_state["values"]["filter_type"] == FILTER_TYPE_TERMS) ? $form_state["values"]["term_ids"] : array();
+
+    //If terms container "all terms", insert only all terms row (term_id=<ALL_TERMS>)
+    if (in_array(ALL_TERMS, $term_ids)) {
+      $term_ids = array(ALL_TERMS);
+    }
+
+    $skus = ($form_state["values"]["filter_type"] == FILTER_TYPE_SKUS) ? $form_state["values"]["skus"] : array();
+
+    //If skus container "all SKUs", insert only all SKUs row (sku=<ALL_SKUS>)
+    if (in_array(ALL_SKUS, $skus)) {
+      $skus = array(ALL_SKUS);
+    }
+
+    $role_ids = ($form_state["values"]["has_role_filter"]) ? $form_state["values"]["role_ids"] : array();
+
+    //If roles container "all roles", insert only all roles row (role_id=<ALL_ROLES>)
+    if (in_array(ALL_ROLES, $role_ids)) {
+      $role_ids = array(ALL_ROLES);
+    }
+
+    //Set expiration to a valid value because it is not nullable
+    if (isset($form_state["values"]["expiration"])) {
+      $expiration = date_convert(date_make_date($form_state["values"]["expiration"]), DATE_OBJECT, DATE_UNIX);
+    }
+    else $expiration = 0;
+
+    //Set discount_amount
+    if (($index = strpos($form_state["values"]["discount_amount"], "%")) !== FALSE) $discount_amount = floatval(substr($form_state["values"]["discount_amount"], 0, $index)) {
+      / 100;
+    }
+    else $discount_amount = floatval($form_state["values"]["discount_amount"]);
+
+    if (empty($form_state["values"]["discount_id"])) {
+      //Insert base discount
+      $discount_id = uc_discounts_insert($form_state["values"]["name"],
+        $form_state["values"]["short_description"],
+        $form_state["values"]["description"],
+        $form_state["values"]["qualifying_type"],
+        $form_state["values"]["qualifying_amount"],
+        $form_state["values"]["has_qualifying_amount_max"],
+        $form_state["values"]["qualifying_amount_max"],
+        $form_state["values"]["discount_type"],
+        $discount_amount,
+        $form_state["values"]["requires_code"],
+        $form_state["values"]["filter_type"],
+        $form_state["values"]["has_role_filter"],
+        $form_state["values"]["requires_single_product_to_qualify"],
+        $form_state["values"]["max_times_applied"],
+        $form_state["values"]["can_be_combined_with_other_discounts"],
+        $form_state["values"]["max_uses"],
+        $form_state["values"]["max_uses_per_user"],
+        $form_state["values"]["max_uses_per_code"],
+        $form_state["values"]["has_expiration"],
+        $expiration,
+        $form_state["values"]["is_published"],
+        $form_state["values"]["weight"]
+      );
+
+      db_last_insert_id("uc_discounts", "discount_id");
+    }
+    else {
+      $discount_id = $form_state["values"]["discount_id"];
+
+      //Update base discount
+      uc_discounts_update($discount_id,
+        $form_state["values"]["name"],
+        $form_state["values"]["short_description"],
+        $form_state["values"]["description"],
+        $form_state["values"]["qualifying_type"],
+        $form_state["values"]["qualifying_amount"],
+        $form_state["values"]["has_qualifying_amount_max"],
+        $form_state["values"]["qualifying_amount_max"],
+        $form_state["values"]["discount_type"],
+        $discount_amount,
+        $form_state["values"]["requires_code"],
+        $form_state["values"]["filter_type"],
+        $form_state["values"]["has_role_filter"],
+        $form_state["values"]["requires_single_product_to_qualify"],
+        $form_state["values"]["max_times_applied"],
+        $form_state["values"]["can_be_combined_with_other_discounts"],
+        $form_state["values"]["max_uses"],
+        $form_state["values"]["max_uses_per_user"],
+        $form_state["values"]["max_uses_per_code"],
+        $form_state["values"]["has_expiration"],
+        $expiration,
+        $form_state["values"]["is_published"],
+        $form_state["values"]["weight"]
+      );
+
+      //Delete existing database codes
+      uc_discounts_codes_delete($discount_id);
+
+      //Delete existing database products
+      uc_discounts_products_delete($discount_id);
+
+      //Delete existing database terms
+      uc_discounts_terms_delete($discount_id);
+
+      //Delete existing database SKUs
+      uc_discounts_skus_delete($discount_id);
+
+      //Delete existing database roles
+      uc_discounts_roles_delete($discount_id);
+    }
+
+    //Insert codes (if necessary)
+    if ($form_state["values"]["requires_code"]) {
+      foreach ($codes as $code) {
+        $code = trim($code);
+        if (empty($code)) {
+          continue;
+        }
+        uc_discounts_codes_insert($discount_id, $code);
+      }
+    }
+
+    //Insert products (if necessary)
+    if ($form_state["values"]["filter_type"] == FILTER_TYPE_PRODUCTS) {
+      foreach ($product_ids as $product_id) {
+        if (empty($product_id)) {
+          continue;
+        }
+        uc_discounts_products_insert($discount_id, $product_id);
+      }
+    }
+    //Insert terms (if necessary)
+    elseif ($form_state["values"]["filter_type"] == FILTER_TYPE_TERMS) {
+      foreach ($term_ids as $term_id) {
+        if (empty($term_id)) {
+          continue;
+        }
+        uc_discounts_terms_insert($discount_id, $term_id);
+      }
+    }
+    //Insert SKUs (if necessary)
+    elseif ($form_state["values"]["filter_type"] == FILTER_TYPE_SKUS) {
+      foreach ($skus as $sku) {
+        //Empty SKU is ALL_SKUS
+        uc_discounts_skus_insert($discount_id, $sku);
+      }
+    }
+
+    //Insert roles
+    if ($form_state["values"]["has_role_filter"]) {
+      foreach ($role_ids as $role_id) {
+        if (empty($role_id)) {
+          continue;
+        }
+        uc_discounts_roles_insert($discount_id, $role_id);
+      }
+    }
 
-		drupal_set_message(  t("%name settings have been saved.", array( "%name" => $form_state["values"]["name"]) )  );
-	}
+    drupal_set_message(t("%name settings have been saved.", array("%name" => $form_state["values"]["name"])));
+  }
 
-	$form_state["redirect"] = "admin/store/settings/uc_discounts";
+  $form_state["redirect"] = "admin/store/settings/uc_discounts";
 }
 
 /**
  * Copy a discount.
  */
-function uc_discounts_copy($original_discount_id)
-{
-//Should be transactional
-	$discount = db_fetch_object( db_query("SELECT * FROM {uc_discounts} WHERE discount_id=%d", $original_discount_id) );
-
-	$discount_id = uc_discounts_insert(
-		t( "Copy of @discount", array( "@discount" => $discount->name ) ), 
-		$discount->short_description, 
-		$discount->description, 
-		$discount->qualifying_type, 
-		$discount->qualifying_amount,
-		$discount->has_qualifying_amount_max,
-		$discount->qualifying_amount_max,
-		$discount->discount_type,
-		$discount->discount_amount,
-		$discount->requires_code,
-		$discount->filter_type,
-		$discount->has_role_filter,
-		$discount->requires_single_product_to_qualify,
-		$discount->max_times_applied,
-		$discount->can_be_combined_with_other_discounts,
-		$discount->max_uses,
-		$discount->max_uses_per_user,
-		$discount->max_uses_per_code,
-		$discount->has_expiration,
-		$discount->expiration,
-		$discount->is_published,
-		$discount->weight);
-
-	//Copy discount's codes
-	$codes = get_codes_for_discount($original_discount_id);
-	foreach ($codes as $code)
-		uc_discounts_codes_insert($discount_id, $code);
-
-	//Copy discount's products
-	$product_ids = get_product_ids_for_discount($original_discount_id);
-	foreach ($product_ids as $product_id)
-		uc_discounts_products_insert($discount_id, $product_id);
-
-	//Copy discount's terms
-	$term_ids = get_term_ids_for_discount($original_discount_id);
-	foreach ($term_ids as $term_id)
-		uc_discounts_terms_insert($discount_id, $term_id);
-
-	//Copy discount's SKUs
-	$skus = get_skus_for_discount($original_discount_id);
-	foreach ($skus as $sku)
-		uc_discounts_skus_insert($discount_id, $sku);
-
-	//Copy discount's roles
-	$role_ids = get_role_ids_for_discount($original_discount_id);
-	foreach ($role_ids as $role_id)
-		uc_discounts_roles_insert($discount_id, $role_id);
+function uc_discounts_copy($original_discount_id) {
+  //Should be transactional
+  $discount = db_fetch_object(db_query("SELECT * FROM {uc_discounts} WHERE discount_id=%d", $original_discount_id));
+
+  $discount_id = uc_discounts_insert(
+    t("Copy of @discount", array("@discount" => $discount->name)),
+    $discount->short_description,
+    $discount->description,
+    $discount->qualifying_type,
+    $discount->qualifying_amount,
+    $discount->has_qualifying_amount_max,
+    $discount->qualifying_amount_max,
+    $discount->discount_type,
+    $discount->discount_amount,
+    $discount->requires_code,
+    $discount->filter_type,
+    $discount->has_role_filter,
+    $discount->requires_single_product_to_qualify,
+    $discount->max_times_applied,
+    $discount->can_be_combined_with_other_discounts,
+    $discount->max_uses,
+    $discount->max_uses_per_user,
+    $discount->max_uses_per_code,
+    $discount->has_expiration,
+    $discount->expiration,
+    $discount->is_published,
+    $discount->weight
+  );
+
+  //Copy discount's codes
+  $codes = get_codes_for_discount($original_discount_id);
+  foreach ($codes as $code) uc_discounts_codes_insert($discount_id, $code);
+
+  //Copy discount's products
+  $product_ids = get_product_ids_for_discount($original_discount_id);
+  foreach ($product_ids as $product_id) uc_discounts_products_insert($discount_id, $product_id);
+
+  //Copy discount's terms
+  $term_ids = get_term_ids_for_discount($original_discount_id);
+  foreach ($term_ids as $term_id) uc_discounts_terms_insert($discount_id, $term_id);
+
+  //Copy discount's SKUs
+  $skus = get_skus_for_discount($original_discount_id);
+  foreach ($skus as $sku) uc_discounts_skus_insert($discount_id, $sku);
+
+  //Copy discount's roles
+  $role_ids = get_role_ids_for_discount($original_discount_id);
+  foreach ($role_ids as $role_id) uc_discounts_roles_insert($discount_id, $role_id);
 
-	drupal_goto("admin/store/settings/uc_discounts");
+  drupal_goto("admin/store/settings/uc_discounts");
 }
 
 /**
@@ -857,177 +818,168 @@ function uc_discounts_copy($original_dis
  * @ingroup forms
  * @see uc_discounts_delete_submit()
  */
-function uc_discounts_delete($form_state, $discount_id = 0)
-{
-	if ($discount_id != 0)
-	{
-		$discount = db_fetch_object( db_query("SELECT * FROM {uc_discounts} WHERE discount_id=%d", $discount_id) );
-		$form = array( "discount_id" => array("#type" => "value", "#value" => $discount_id) );
-		$output = confirm_form( $form, t("Delete @row?", array( "@row" => $discount->name) ), 
-			"admin/store/settings/uc_discounts", "", t("Continue"), t("Cancel") );
-		return $output;
-	}
-	else
-		drupal_goto("admin/store/settings/uc_discounts");
+function uc_discounts_delete($form_state, $discount_id = 0) {
+  if ($discount_id != 0) {
+    $discount = db_fetch_object(db_query("SELECT * FROM {uc_discounts} WHERE discount_id=%d", $discount_id));
+    $form     = array("discount_id" => array("#type" => "value", "#value" => $discount_id));
+    $output   = confirm_form($form, t("Delete @row?", array("@row" => $discount->name)),
+      "admin/store/settings/uc_discounts", "", t("Continue"), t("Cancel")
+    );
+    return $output;
+  }
+  else drupal_goto("admin/store/settings/uc_discounts");
 }
 
 /**
  * Submit handler for uc_discounts_delete().
  */
-function uc_discounts_delete_submit($form, &$form_state)
-{
-	if ($form_state["values"]["confirm"])
-	{
-		$discount_id = $form_state["values"]["discount_id"];
-		uc_discounts_delete_all($discount_id);
-	}
+function uc_discounts_delete_submit($form, &$form_state) {
+  if ($form_state["values"]["confirm"]) {
+    $discount_id = $form_state["values"]["discount_id"];
+    uc_discounts_delete_all($discount_id);
+  }
 
-	drupal_set_message( t("Discount deleted.") );
+  drupal_set_message(t("Discount deleted."));
 
-	$form_state["redirect"] = "admin/store/settings/uc_discounts";
+  $form_state["redirect"] = "admin/store/settings/uc_discounts";
 }
 
 /**
  * Generate report for all discounts.
  */
-function uc_discounts_report()
-{
-	$header = array(
-		array("data" => t("Name"), "field" => "d.name"),
-		array("data" => t("Short Description"), "field" => "d.short_description"),
-		array("data" => t("Qualifying Type"), "field" => "d.qualifying_type"),
-		array("data" => t("Discount Type"), "field" => "d.discount_type"),
-		array("data" => t("Weight"), "field" => "d.weight", "sort" => "asc"),
-		array("data" => t("Uses"), "field" => "use_count"),
-		array("data" => t("Times Applied"), "field" => "total_times_applied"),
-		array("data" => t("Total Amount"), "field" => "total_amount"),
-		array("data" => t("Operations"), "colspan" => 3),
-	);
-
-	$query = "SELECT d.*, COUNT(du.discount_use_id) total_use_count, SUM(du.times_applied) total_times_applied"
-		. ", SUM(du.amount) total_amount FROM {uc_discounts} d"
-		. " LEFT JOIN {uc_discounts_uses} du ON d.discount_id=du.discount_id"
-		. " GROUP BY d.discount_id";
-	$tablesort = tablesort_sql($header);
-	$result = pager_query($query . $tablesort, 50);
-
-	$rows = array();
-	while ( $discount = db_fetch_object($result) )
-	{
-		$total_use_count = ( is_numeric($discount->total_use_count) ) ? $discount->total_use_count : 0;
-		$total_times_applied = ( is_numeric($discount->total_times_applied) ) ? $discount->total_times_applied : 0;
-
-		$rows[] = array("data" =>
-			//Cell data
-			array(
-				$discount->name, 
-				$discount->short_description, 
-				qualifying_type_name($discount->qualifying_type), 
-				discount_type_name($discount->discount_type), 
-				$discount->weight,
-				$total_use_count,
-				$total_times_applied,
-				uc_currency_format($discount->total_amount),
-				l( t("view usage"), "admin/reports/uc_discounts/discount/" . $discount->discount_id), 
-				l( t("edit"), "admin/store/settings/uc_discounts/edit/" . $discount->discount_id), 
-				l(t("delete"), "admin/store/settings/uc_discounts/delete/" . $discount->discount_id),
-			),
-		);
-	}
+function uc_discounts_report() {
+  $header = array(
+    array("data" => t("Name"), "field" => "d.name"),
+    array("data" => t("Short Description"), "field" => "d.short_description"),
+    array("data" => t("Qualifying Type"), "field" => "d.qualifying_type"),
+    array("data" => t("Discount Type"), "field" => "d.discount_type"),
+    array("data" => t("Weight"), "field" => "d.weight", "sort" => "asc"),
+    array("data" => t("Uses"), "field" => "use_count"),
+    array("data" => t("Times Applied"), "field" => "total_times_applied"),
+    array("data" => t("Total Amount"), "field" => "total_amount"),
+    array("data" => t("Operations"), "colspan" => 3),
+  );
+
+  $query     = "SELECT d.*, COUNT(du.discount_use_id) total_use_count, SUM(du.times_applied) total_times_applied" . ", SUM(du.amount) total_amount FROM {uc_discounts} d" . " LEFT JOIN {uc_discounts_uses} du ON d.discount_id=du.discount_id" . " GROUP BY d.discount_id";
+  $tablesort = tablesort_sql($header);
+  $result    = pager_query($query . $tablesort, 50);
+
+  $rows = array();
+  while ($discount = db_fetch_object($result)) {
+    $total_use_count = (is_numeric($discount->total_use_count)) ? $discount->total_use_count : 0;
+    $total_times_applied = (is_numeric($discount->total_times_applied)) ? $discount->total_times_applied : 0;
+
+    $rows[] = array("data" =>
+      //Cell data
+      array(
+        $discount->name,
+        $discount->short_description,
+        qualifying_type_name($discount->qualifying_type),
+        discount_type_name($discount->discount_type),
+        $discount->weight,
+        $total_use_count,
+        $total_times_applied,
+        uc_currency_format($discount->total_amount),
+        l(t("view usage"), "admin/reports/uc_discounts/discount/". $discount->discount_id),
+        l(t("edit"), "admin/store/settings/uc_discounts/edit/". $discount->discount_id),
+        l(t("delete"), "admin/store/settings/uc_discounts/delete/". $discount->discount_id),
+      ),
+    );
+  }
+
+  if (empty($rows)) {
 
-	if ( empty($rows) )
-		$rows[] = array( array("data" => t("No discount data available."), "colspan" => 11) );
+    $rows[] = array(array("data" => t("No discount data available."), "colspan" => 11));
 
-	$output .= theme( "table", $header, $rows, array("id" => "uc_discounts_report") );
-	$output .= theme("pager", NULL, 50, 0);
+  }
 
-	return $output;
+  $output .= theme("table", $header, $rows, array("id" => "uc_discounts_report"));
+  $output .= theme("pager", NULL, 50, 0);
+
+  return $output;
 }
 
 /**
  * Generate report for discount.
  */
-function uc_discounts_report_for_discount($discount_id)
-{
-	//Add link to all discount data
-	$output = l(t("Report for all discounts."), "admin/reports/uc_discounts/all");
-	
-	$output .= "<br/><br/>";
-
-
-	//Add table for discount's data
-
-	$header = array(
-		t("Name"),
-		t("Uses"),
-		t("Times Applied"),
-		t("Total Amount"),
-		array("data" => t("Operations"), "colspan" => 3)
-	);
-
-	$query = "SELECT d.*, COUNT(du.discount_use_id) total_use_count, SUM(du.times_applied) total_times_applied"
-		. ", SUM(du.amount) total_amount FROM {uc_discounts} d"
-		. " LEFT JOIN {uc_discounts_uses} du ON d.discount_id=du.discount_id"
-		. " WHERE d.discount_id=%d"
-		. " GROUP BY d.discount_id";
-	$discount = db_fetch_object( db_query($query, $discount_id) );
-	$total_use_count = ( is_numeric($discount->total_use_count) ) ? $discount->total_use_count : 0;
-	$total_times_applied = ( is_numeric($discount->total_times_applied) ) ? $discount->total_times_applied : 0;
-	$discounts[] = array(
-		$discount->name, 
-		$total_use_count,
-		$total_times_applied,
-		uc_currency_format($discount->total_amount),
-		l( t("edit"), "admin/store/settings/uc_discounts/edit/" . $discount->discount_id), 
-		l(t("copy"), "admin/store/settings/uc_discounts/copy/" . $discount->discount_id), 
-		l(t("delete"), "admin/store/settings/uc_discounts/delete/" . $discount->discount_id),
-	);
-	$output .= theme("table", $header, $discounts);
-
-	$output .= "<br/><br/>";
-
-	
-	//Add table of discount's usage data
-
-	$header = array(
-		array("data" => t("User"), "field" => "user_id"),
-		array("data" => t("Order"), "field" => "order_id"),
-		array("data" => t("Code"), "field" => "code"),
-		array("data" => t("Times Applied"), "field" => "times_applied"),
-		array("data" => t("Amount"), "field" => "amount"),
-		array("data" => t("Date"), "field" => "insert_timestamp", "sort" => "asc"),
-	);
-
-	$query = sprintf("SELECT du.*, u.uid user_id, u.name username, u.mail email FROM {uc_discounts_uses} du"
-		. " LEFT JOIN {users} u ON du.user_id=u.uid"
-		. " WHERE discount_id=%d", $discount_id);
-	$tablesort = tablesort_sql($header);
-	$result = pager_query($query . $tablesort, 50);
-
-	$rows = array();
-	while ( $use = db_fetch_object($result) )
-	{
-		$user_description = ($use->user_id != 0) ? $use->username . " (" . $use->email . ")" : t("Anonymous");
-
-		$rows[] = array("data" =>
-			//Cell data
-			array(
-				$user_description, 
-				$use->order_id, 
-				( !empty($use->code) ) ? $use->code : check_plain("<" . t("no code") . ">"),
-				$use->times_applied,
-				uc_currency_format($use->amount),
-				date("Y-m-d H:i:s", $use->insert_timestamp),
-			),
-		);
-	}
+function uc_discounts_report_for_discount($discount_id) {
+  //Add link to all discount data
+  $output = l(t("Report for all discounts."), "admin/reports/uc_discounts/all");
+
+  $output .= "<br/><br/>";
+
+
+  //Add table for discount's data
+
+  $header = array(
+    t("Name"),
+    t("Uses"),
+    t("Times Applied"),
+    t("Total Amount"),
+    array("data" => t("Operations"), "colspan" => 3),
+  );
+
+  $query               = "SELECT d.*, COUNT(du.discount_use_id) total_use_count, SUM(du.times_applied) total_times_applied" . ", SUM(du.amount) total_amount FROM {uc_discounts} d" . " LEFT JOIN {uc_discounts_uses} du ON d.discount_id=du.discount_id" . " WHERE d.discount_id=%d" . " GROUP BY d.discount_id";
+  $discount            = db_fetch_object(db_query($query, $discount_id));
+  $total_use_count     = (is_numeric($discount->total_use_count)) ? $discount->total_use_count : 0;
+  $total_times_applied = (is_numeric($discount->total_times_applied)) ? $discount->total_times_applied : 0;
+  $discounts[]         = array(
+    $discount->name,
+    $total_use_count,
+    $total_times_applied,
+    uc_currency_format($discount->total_amount),
+    l(t("edit"), "admin/store/settings/uc_discounts/edit/". $discount->discount_id),
+    l(t("copy"), "admin/store/settings/uc_discounts/copy/". $discount->discount_id),
+    l(t("delete"), "admin/store/settings/uc_discounts/delete/". $discount->discount_id),
+  );
+  $output .= theme("table", $header, $discounts);
+
+  $output .= "<br/><br/>";
+
+
+  //Add table of discount's usage data
+
+  $header = array(
+    array("data" => t("User"), "field" => "user_id"),
+    array("data" => t("Order"), "field" => "order_id"),
+    array("data" => t("Code"), "field" => "code"),
+    array("data" => t("Times Applied"), "field" => "times_applied"),
+    array("data" => t("Amount"), "field" => "amount"),
+    array("data" => t("Date"), "field" => "insert_timestamp", "sort" => "asc"),
+  );
+
+  $query = sprintf("SELECT du.*, u.uid user_id, u.name username, u.mail email FROM {uc_discounts_uses} du" . " LEFT JOIN {users} u ON du.user_id=u.uid" . " WHERE discount_id=%d", $discount_id
+  );
+  $tablesort = tablesort_sql($header);
+  $result = pager_query($query . $tablesort, 50);
+
+  $rows = array();
+  while ($use = db_fetch_object($result)) {
+    $user_description = ($use->user_id != 0) ? $use->username ." (". $use->email .")" : t("Anonymous");
+
+    $rows[] = array("data" =>
+      //Cell data
+      array(
+        $user_description,
+        $use->order_id,
+        (!empty($use->code)) ? $use->code : check_plain("<". t("no code") .">"),
+        $use->times_applied,
+        uc_currency_format($use->amount),
+        date("Y-m-d H:i:s", $use->insert_timestamp),
+      ),
+    );
+  }
+
+  if (empty($rows)) {
+
+    $rows[] = array(array("data" => t("No discount data available."), "colspan" => 11));
 
-	if ( empty($rows) )
-		$rows[] = array( array("data" => t("No discount data available."), "colspan" => 11) );
+  }
 
-	$output .= theme( "table", $header, $rows, array("id" => "uc_discounts_report") );
-	$output .= theme("pager", NULL, 50, 0);
+  $output .= theme("table", $header, $rows, array("id" => "uc_discounts_report"));
+  $output .= theme("pager", NULL, 50, 0);
 
 
-	return $output;
+  return $output;
 }
+
Index: uc_discounts/uc_discounts.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_discounts_alt/uc_discounts/uc_discounts.install,v
retrieving revision 1.8
diff -u -p -r1.8 uc_discounts.install
--- uc_discounts/uc_discounts.install	27 May 2009 03:57:34 -0000	1.8
+++ uc_discounts/uc_discounts.install	20 Aug 2009 22:09:29 -0000
@@ -1,501 +1,489 @@
 <?php
 //$Id: uc_discounts.install,v 1.8 2009/05/27 03:57:34 ryangroe Exp $
 
+
 /**
  * @file
  * Install hooks for uc_discounts.module.
  */
+function uc_discounts_schema() {
+  $schema = array();
 
-function uc_discounts_schema()
-{
-	$schema = array();
-
-	$schema["uc_discounts"] = array(
-		"fields" => array(
-			"discount_id" => array(
-				"type" => "serial",
-				"not null" => TRUE,
-			),
-			"name" => array(
-				"type" => "varchar",
-				"length" => 255,
-				"not null" => TRUE,
-				"default" => "",
-			),
-			"short_description" => array(
-				"type" => "varchar",
-				"length" => 100,
-				"not null" => TRUE,
-				"default" => "",
-			),
-			"description" => array(
-				"type" => "varchar",
-				"length" => 1000,
-				"not null" => TRUE,
-				"default" => "",
-			),
-			"qualifying_type" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-			),
-			"qualifying_amount" => array(
-				"type" => "float",
-				"not null" => TRUE,
-				"default" => 0.0,
-				"description" => t("Minimum quantity or price required to qualify for this discount."),
-			),
-			"has_qualifying_amount_max" => array(
-				"type" => "int",
-				"size" => "tiny",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("Whether or not this discount has a max qualifying amount."),
-			),
-			"qualifying_amount_max" => array(
-				"type" => "float",
-				"not null" => TRUE,
-				"default" => 0.0,
-				"description" => t("Maximum quantity or price required to qualify for this discount."),
-			),
-			"discount_type" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-			),
-			"discount_amount" => array(
-				"type" => "float",
-				"not null" => TRUE,
-				"default" => 0.0,
-				"description" => t("Amount to discount (i.e. 1 free item, 25%, or $2.00)"),
-			),
-			"requires_code" => array(
-				"type" => "int",
-				"size" => "tiny",
-				"not null" => TRUE,
-				"default" => 1,
-				"description" => t("Requires code to activate discount."),
-			),
-			"filter_type" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 1,
-				"description" => t("What type of object to filter on."),
-			),
-			"has_role_filter" => array(
-				"type" => "int",
-				"size" => "tiny",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("Whether or not this discount filters based on role."),
-			),
-			"requires_single_product_to_qualify" => array(
-				"type" => "int",
-				"size" => "tiny",
-				"not null" => TRUE,
-				"default" => 1,
-				"description" => t("Requires qualifying amount to come from a single product."),
-			),
-			"max_times_applied" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 1,
-				"description" => t("Number of times this discount can be applied to a single cart (0 for unlimited)."),
-			),
-			"can_be_combined_with_other_discounts" => array(
-				"type" => "int",
-				"size" => "tiny",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("Whether or not this discount will be applied if other discounts are."),
-			),
-			"max_uses" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("Number of times this discount can be applied (0 for no limit)."),
-			),
-			"max_uses_per_user" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 1,
-				"description" => t("Number of times this discount can be applied to a particular user (0 for unlimited)."),
-			),
-			"max_uses_per_code" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("Number of times this discount can be applied for a particular code (0 for unlimited)."),
-			),
-			"has_expiration" => array(
-				"type" => "int",
-				"size" => "tiny",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("Whether or not discount has an expiration."),
-			),
-			"expiration" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("The exipration date and time as a unix timestamp."),
-			),
-			"is_published" => array(
-				"type" => "int",
-				"size" => "tiny",
-				"not null" => FALSE,
-				"default" => 0,
-				"description" => t("Convenience flag to state whether code is published on site or not."),
-			),
-			"weight" => array(
-				"type" => "int",
-				"size" => "tiny",
-				"not null" => TRUE,
-				"default" => 0,
-			),
-			"insert_timestamp" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("The insert date and time as a unix timestamp."),
-			),
-		),
-		"primary key" => array("discount_id"),
-	);
-
-	return $schema;
-}
-
-function uc_discounts_codes_schema()
-{
-	$schema = array();
-
-	$schema["uc_discounts_codes"] = array(
-		"fields" => array(
-			"discount_code_id" => array(
-				"type" => "serial",
-				"not null" => TRUE,
-			),
-			"discount_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("The {uc_discounts}.discount_id of the discount."),
-			),
-			"code" => array(
-				"type" => "varchar",
-				"length" => 100,
-				"not null" => TRUE,
-				"default" => "",
-			),
-		),
-		"primary key" => array("discount_code_id"),
-	);
-
-	return $schema;
-}
-
-function uc_discounts_products_schema()
-{
-	$schema = array();
-
-	$schema["uc_discounts_products"] = array(
-		"fields" => array(
-			"discount_product_id" => array(
-				"type" => "serial",
-				"not null" => TRUE,
-			),
-			"discount_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"description" => t("The {uc_discounts}.discount_id of the discount."),
-			),
-			"product_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"description" => t("The {uc_products}.nid of the product being discounted."),
-			),
-		),
-		"primary key" => array("discount_product_id"),
-	);
-
-	return $schema;
-}
-
-function uc_discounts_terms_schema()
-{
-	$schema = array();
-
-	$schema["uc_discounts_terms"] = array(
-		"fields" => array(
-			"discount_term_id" => array(
-				"type" => "serial",
-				"not null" => TRUE,
-			),
-			"discount_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"description" => t("The {uc_discounts}.discount_id of the discount."),
-			),
-			"term_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"description" => t("The {term}.tid of the term being discounted."),
-			),
-		),
-		"primary key" => array("discount_term_id"),
-	);
-
-	return $schema;
-}
-
-function uc_discounts_skus_schema()
-{
-	$schema = array();
-
-	$schema["uc_discounts_skus"] = array(
-		"fields" => array(
-			"discount_sku_id" => array(
-				"type" => "serial",
-				"not null" => TRUE,
-			),
-			"discount_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"description" => t("The {uc_discounts}.discount_id of the discount."),
-			),
-			"sku" => array(
-				"type" => "varchar",
-				"length" => 255,
-				"not null" => TRUE,
-				"description" => t("The {uc_products}.model of the product being discounted."),
-			),
-		),
-		"primary key" => array("discount_sku_id"),
-	);
-
-	return $schema;
-}
-
-function uc_discounts_roles_schema()
-{
-	$schema = array();
-
-	$schema["uc_discounts_roles"] = array(
-		"fields" => array(
-			"discount_role_id" => array(
-				"type" => "serial",
-				"not null" => TRUE,
-			),
-			"discount_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"description" => t("The {uc_discounts}.discount_id of the discount."),
-			),
-			"role_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"description" => t("The {role}.rid of the role required."),
-			),
-		),
-		"primary key" => array("discount_role_id"),
-	);
-
-	return $schema;
-}
-
-function uc_discounts_uses_schema()
-{
-	$schema = array();
-
-	$schema["uc_discounts_uses"] = array(
-		"fields" => array(
-			"discount_use_id" => array(
-				"type" => "serial",
-				"not null" => TRUE,
-			),
-			"discount_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("The {uc_discounts}.discount_id of the discount."),
-			),
-			"user_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("The {users}.uid of the user who used the discount or (0 if anonymous)."),
-			),
-			"order_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("The {uc_orders}.order_id of the user's order."),
-			),
-			"code" => array(
-				"type" => "varchar",
-				"length" => 100,
-				"not null" => TRUE,
-				"default" => "",
-				"description" => t("Code used for discount."),
-			),
-			"times_applied" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 1,
-				"description" => t("Number of times this discount was applied."),
-			),
-			"amount" => array(
-				"type" => "float",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("Total amount of discount."),
-			),
-			"insert_timestamp" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"default" => 0,
-				"description" => t("The insert date and time as a unix timestamp.")
-			),
-		),
-		"primary key" => array("discount_use_id"),
-	);
-
-	return $schema;
-}
-
-function uc_discounts_order_codes_schema()
-{
-	$schema = array();
-
-	$schema["uc_discounts_order_codes"] = array(
-		"fields" => array(
-			"order_id" => array(
-				"type" => "int",
-				"not null" => TRUE,
-				"description" => t("The {uc_orders}.order_id of the user's order."),
-			),
-			"codes" => array(
-				"type" => "text",
-				"not null" => TRUE,
-				"description" => t("Newline delimited codes string for order."),
-			),
-		),
-	);
+  $schema["uc_discounts"] = array(
+    "fields" => array(
+      "discount_id" => array(
+        "type" => "serial",
+        "not null" => TRUE,
+      ),
+      "name" => array(
+        "type" => "varchar",
+        "length" => 255,
+        "not null" => TRUE,
+        "default" => "",
+      ),
+      "short_description" => array(
+        "type" => "varchar",
+        "length" => 100,
+        "not null" => TRUE,
+        "default" => "",
+      ),
+      "description" => array(
+        "type" => "varchar",
+        "length" => 1000,
+        "not null" => TRUE,
+        "default" => "",
+      ),
+      "qualifying_type" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+      ),
+      "qualifying_amount" => array(
+        "type" => "float",
+        "not null" => TRUE,
+        "default" => 0.0,
+        "description" => t("Minimum quantity or price required to qualify for this discount."),
+      ),
+      "has_qualifying_amount_max" => array(
+        "type" => "int",
+        "size" => "tiny",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("Whether or not this discount has a max qualifying amount."),
+      ),
+      "qualifying_amount_max" => array(
+        "type" => "float",
+        "not null" => TRUE,
+        "default" => 0.0,
+        "description" => t("Maximum quantity or price required to qualify for this discount."),
+      ),
+      "discount_type" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+      ),
+      "discount_amount" => array(
+        "type" => "float",
+        "not null" => TRUE,
+        "default" => 0.0,
+        "description" => t("Amount to discount (i.e. 1 free item, 25%, or $2.00)"),
+      ),
+      "requires_code" => array(
+        "type" => "int",
+        "size" => "tiny",
+        "not null" => TRUE,
+        "default" => 1,
+        "description" => t("Requires code to activate discount."),
+      ),
+      "filter_type" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 1,
+        "description" => t("What type of object to filter on."),
+      ),
+      "has_role_filter" => array(
+        "type" => "int",
+        "size" => "tiny",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("Whether or not this discount filters based on role."),
+      ),
+      "requires_single_product_to_qualify" => array(
+        "type" => "int",
+        "size" => "tiny",
+        "not null" => TRUE,
+        "default" => 1,
+        "description" => t("Requires qualifying amount to come from a single product."),
+      ),
+      "max_times_applied" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 1,
+        "description" => t("Number of times this discount can be applied to a single cart (0 for unlimited)."),
+      ),
+      "can_be_combined_with_other_discounts" => array(
+        "type" => "int",
+        "size" => "tiny",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("Whether or not this discount will be applied if other discounts are."),
+      ),
+      "max_uses" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("Number of times this discount can be applied (0 for no limit)."),
+      ),
+      "max_uses_per_user" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 1,
+        "description" => t("Number of times this discount can be applied to a particular user (0 for unlimited)."),
+      ),
+      "max_uses_per_code" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("Number of times this discount can be applied for a particular code (0 for unlimited)."),
+      ),
+      "has_expiration" => array(
+        "type" => "int",
+        "size" => "tiny",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("Whether or not discount has an expiration."),
+      ),
+      "expiration" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("The exipration date and time as a unix timestamp."),
+      ),
+      "is_published" => array(
+        "type" => "int",
+        "size" => "tiny",
+        "not null" => FALSE,
+        "default" => 0,
+        "description" => t("Convenience flag to state whether code is published on site or not."),
+      ),
+      "weight" => array(
+        "type" => "int",
+        "size" => "tiny",
+        "not null" => TRUE,
+        "default" => 0,
+      ),
+      "insert_timestamp" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("The insert date and time as a unix timestamp."),
+      ),
+    ),
+    "primary key" => array("discount_id"),
+  );
+
+  return $schema;
+}
+
+function uc_discounts_codes_schema() {
+  $schema = array();
+
+  $schema["uc_discounts_codes"] = array(
+    "fields" => array(
+      "discount_code_id" => array(
+        "type" => "serial",
+        "not null" => TRUE,
+      ),
+      "discount_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("The {uc_discounts}.discount_id of the discount."),
+      ),
+      "code" => array(
+        "type" => "varchar",
+        "length" => 100,
+        "not null" => TRUE,
+        "default" => "",
+      ),
+    ),
+    "primary key" => array("discount_code_id"),
+  );
+
+  return $schema;
+}
+
+function uc_discounts_products_schema() {
+  $schema = array();
+
+  $schema["uc_discounts_products"] = array(
+    "fields" => array(
+      "discount_product_id" => array(
+        "type" => "serial",
+        "not null" => TRUE,
+      ),
+      "discount_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "description" => t("The {uc_discounts}.discount_id of the discount."),
+      ),
+      "product_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "description" => t("The {uc_products}.nid of the product being discounted."),
+      ),
+    ),
+    "primary key" => array("discount_product_id"),
+  );
+
+  return $schema;
+}
+
+function uc_discounts_terms_schema() {
+  $schema = array();
+
+  $schema["uc_discounts_terms"] = array(
+    "fields" => array(
+      "discount_term_id" => array(
+        "type" => "serial",
+        "not null" => TRUE,
+      ),
+      "discount_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "description" => t("The {uc_discounts}.discount_id of the discount."),
+      ),
+      "term_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "description" => t("The {term}.tid of the term being discounted."),
+      ),
+    ),
+    "primary key" => array("discount_term_id"),
+  );
+
+  return $schema;
+}
+
+function uc_discounts_skus_schema() {
+  $schema = array();
+
+  $schema["uc_discounts_skus"] = array(
+    "fields" => array(
+      "discount_sku_id" => array(
+        "type" => "serial",
+        "not null" => TRUE,
+      ),
+      "discount_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "description" => t("The {uc_discounts}.discount_id of the discount."),
+      ),
+      "sku" => array(
+        "type" => "varchar",
+        "length" => 255,
+        "not null" => TRUE,
+        "description" => t("The {uc_products}.model of the product being discounted."),
+      ),
+    ),
+    "primary key" => array("discount_sku_id"),
+  );
+
+  return $schema;
+}
+
+function uc_discounts_roles_schema() {
+  $schema = array();
+
+  $schema["uc_discounts_roles"] = array(
+    "fields" => array(
+      "discount_role_id" => array(
+        "type" => "serial",
+        "not null" => TRUE,
+      ),
+      "discount_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "description" => t("The {uc_discounts}.discount_id of the discount."),
+      ),
+      "role_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "description" => t("The {role}.rid of the role required."),
+      ),
+    ),
+    "primary key" => array("discount_role_id"),
+  );
+
+  return $schema;
+}
+
+function uc_discounts_uses_schema() {
+  $schema = array();
+
+  $schema["uc_discounts_uses"] = array(
+    "fields" => array(
+      "discount_use_id" => array(
+        "type" => "serial",
+        "not null" => TRUE,
+      ),
+      "discount_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("The {uc_discounts}.discount_id of the discount."),
+      ),
+      "user_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("The {users}.uid of the user who used the discount or (0 if anonymous)."),
+      ),
+      "order_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("The {uc_orders}.order_id of the user's order."),
+      ),
+      "code" => array(
+        "type" => "varchar",
+        "length" => 100,
+        "not null" => TRUE,
+        "default" => "",
+        "description" => t("Code used for discount."),
+      ),
+      "times_applied" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 1,
+        "description" => t("Number of times this discount was applied."),
+      ),
+      "amount" => array(
+        "type" => "float",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("Total amount of discount."),
+      ),
+      "insert_timestamp" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "default" => 0,
+        "description" => t("The insert date and time as a unix timestamp."),
+      ),
+    ),
+    "primary key" => array("discount_use_id"),
+  );
+
+  return $schema;
+}
+
+function uc_discounts_order_codes_schema() {
+  $schema = array();
+
+  $schema["uc_discounts_order_codes"] = array(
+    "fields" => array(
+      "order_id" => array(
+        "type" => "int",
+        "not null" => TRUE,
+        "description" => t("The {uc_orders}.order_id of the user's order."),
+      ),
+      "codes" => array(
+        "type" => "text",
+        "not null" => TRUE,
+        "description" => t("Newline delimited codes string for order."),
+      ),
+    ),
+  );
 
-	return $schema;
+  return $schema;
 }
 
 /**
  * Implementation of hook_install().
  */
-function uc_discounts_install()
-{
-	drupal_install_schema("uc_discounts");
-	drupal_install_schema("uc_discounts_codes");
-	drupal_install_schema("uc_discounts_products");
-	drupal_install_schema("uc_discounts_terms");
-	drupal_install_schema("uc_discounts_skus");
-	drupal_install_schema("uc_discounts_roles");
-	drupal_install_schema("uc_discounts_uses");
-	drupal_install_schema("uc_discounts_order_codes");
-	
-	//Weight must be less than uc_payment's
-	db_query("UPDATE {system} SET weight=-10 WHERE name='uc_discounts'");
+function uc_discounts_install() {
+  drupal_install_schema("uc_discounts");
+  drupal_install_schema("uc_discounts_codes");
+  drupal_install_schema("uc_discounts_products");
+  drupal_install_schema("uc_discounts_terms");
+  drupal_install_schema("uc_discounts_skus");
+  drupal_install_schema("uc_discounts_roles");
+  drupal_install_schema("uc_discounts_uses");
+  drupal_install_schema("uc_discounts_order_codes");
+
+  //Weight must be less than uc_payment's
+  db_query("UPDATE {system} SET weight=-10 WHERE name='uc_discounts'");
 }
 
 /**
  * Implementation of hook_uninstall().
  */
-function uc_discounts_uninstall()
-{
-	drupal_uninstall_schema("uc_discounts_order_codes");
-	drupal_uninstall_schema("uc_discounts_uses");
-	drupal_uninstall_schema("uc_discounts_products");
-	drupal_uninstall_schema("uc_discounts_terms");
-	drupal_uninstall_schema("uc_discounts_skus");
-	drupal_uninstall_schema("uc_discounts_roles");
-	drupal_uninstall_schema("uc_discounts_codes");
-	drupal_uninstall_schema("uc_discounts");
+function uc_discounts_uninstall() {
+  drupal_uninstall_schema("uc_discounts_order_codes");
+  drupal_uninstall_schema("uc_discounts_uses");
+  drupal_uninstall_schema("uc_discounts_products");
+  drupal_uninstall_schema("uc_discounts_terms");
+  drupal_uninstall_schema("uc_discounts_skus");
+  drupal_uninstall_schema("uc_discounts_roles");
+  drupal_uninstall_schema("uc_discounts_codes");
+  drupal_uninstall_schema("uc_discounts");
 }
 
 
 //Add {uc_discounts_roles} table
-function uc_discounts_update_1()
-{
-	$queries = array();
-
-	$schema = uc_discounts_roles_schema();
-	db_create_table($queries, "uc_discounts_roles", $schema["uc_discounts_roles"]);
-
-	switch ($GLOBALS["db_type"])
-	{
-		case "mysql":
-		case "mysqli":
-			$queries[] = update_sql("ALTER TABLE {uc_discounts} ADD has_role_filter tinyint NOT NULL default 0 AFTER filter_type");
-			break;
-
-		case "pgsql":
-			db_add_column( $queries, "uc_discounts", "has_role_filter", "tinyint", 
-				array("size" => "tiny", "not null" => TRUE, "default" => 0) );
-			break;
-	}
+function uc_discounts_update_1() {
+  $queries = array();
+
+  $schema = uc_discounts_roles_schema();
+  db_create_table($queries, "uc_discounts_roles", $schema["uc_discounts_roles"]);
+
+  switch ($GLOBALS["db_type"]) {
+    case "mysql":
+    case "mysqli":
+      $queries[] = update_sql("ALTER TABLE {uc_discounts} ADD has_role_filter tinyint NOT NULL default 0 AFTER filter_type");
+      break;
+
+    case "pgsql":
+      db_add_column($queries, "uc_discounts", "has_role_filter", "tinyint",
+        array("size" => "tiny", "not null" => TRUE, "default" => 0)
+      );
+      break;
+  }
 
-	return $queries;
+  return $queries;
 }
 
 //Add has_qualifying_amount_max and qualifying_amount_max columns to uc_discounts table
-function uc_discounts_update_2()
-{
-	$queries = array();
-
-	switch ($GLOBALS["db_type"])
-	{
-		case "mysql":
-		case "mysqli":
-			$queries[] = update_sql("ALTER TABLE {uc_discounts} ADD has_qualifying_amount_max tinyint NOT NULL default 0 AFTER qualifying_amount");
-			$queries[] = update_sql("ALTER TABLE {uc_discounts} ADD qualifying_amount_max float NOT NULL default 0 AFTER has_qualifying_amount_max");
-
-			//Fixes update bug that existed in uc_discounts_update_1 (but is fixed now)
-			$queries[] = update_sql("ALTER TABLE {uc_discounts} MODIFY has_role_filter tinyint NOT NULL");
-			break;
-
-		case "pgsql":
-			db_add_column( $queries, "uc_discounts", "has_qualifying_amount_max", "tinyint", 
-				array("not null" => TRUE, "default" => 0) );
-			db_add_column( $queries, "uc_discounts", "qualifying_amount_max", "float", 
-				array("not null" => TRUE, "default" => 0) );
-			break;
-	}
+function uc_discounts_update_2() {
+  $queries = array();
 
-	return $queries;
+  switch ($GLOBALS["db_type"]) {
+    case "mysql":
+    case "mysqli":
+      $queries[] = update_sql("ALTER TABLE {uc_discounts} ADD has_qualifying_amount_max tinyint NOT NULL default 0 AFTER qualifying_amount");
+      $queries[] = update_sql("ALTER TABLE {uc_discounts} ADD qualifying_amount_max float NOT NULL default 0 AFTER has_qualifying_amount_max");
+
+      //Fixes update bug that existed in uc_discounts_update_1 (but is fixed now)
+      $queries[] = update_sql("ALTER TABLE {uc_discounts} MODIFY has_role_filter tinyint NOT NULL");
+      break;
+
+    case "pgsql":
+      db_add_column($queries, "uc_discounts", "has_qualifying_amount_max", "tinyint",
+        array("not null" => TRUE, "default" => 0)
+      );
+      db_add_column($queries, "uc_discounts", "qualifying_amount_max", "float",
+        array("not null" => TRUE, "default" => 0)
+      );
+      break;
+  }
+
+  return $queries;
 }
 
 //Add max_uses_per_code column to uc_discounts table
-function uc_discounts_update_3()
-{
-	$queries = array();
-
-	switch ($GLOBALS["db_type"])
-	{
-		case "mysql":
-		case "mysqli":
-			$queries[] = update_sql("ALTER TABLE {uc_discounts} ADD max_uses_per_code int NOT NULL default 0 AFTER max_uses_per_user");
-			break;
-
-		case "pgsql":
-			db_add_column( $queries, "uc_discounts", "max_uses_per_code", "int", 
-				array("not null" => TRUE, "default" => 0) );
-			break;
-	}
+function uc_discounts_update_3() {
+  $queries = array();
+
+  switch ($GLOBALS["db_type"]) {
+    case "mysql":
+    case "mysqli":
+      $queries[] = update_sql("ALTER TABLE {uc_discounts} ADD max_uses_per_code int NOT NULL default 0 AFTER max_uses_per_user");
+      break;
+
+    case "pgsql":
+      db_add_column($queries, "uc_discounts", "max_uses_per_code", "int",
+        array("not null" => TRUE, "default" => 0)
+      );
+      break;
+  }
 
-	return $queries;
+  return $queries;
 }
 
 //Add uc_discounts_skus table
-function uc_discounts_update_4()
-{
-	$schema = uc_discounts_skus_schema();
-	db_create_table($queries, "uc_discounts_skus", $schema["uc_discounts_skus"]);
-	return $queries;
+function uc_discounts_update_4() {
+  $schema = uc_discounts_skus_schema();
+  db_create_table($queries, "uc_discounts_skus", $schema["uc_discounts_skus"]);
+  return $queries;
 }
+
Index: uc_discounts/uc_discounts.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_discounts_alt/uc_discounts/uc_discounts.module,v
retrieving revision 1.26
diff -u -p -r1.26 uc_discounts.module
--- uc_discounts/uc_discounts.module	26 May 2009 01:45:13 -0000	1.26
+++ uc_discounts/uc_discounts.module	20 Aug 2009 22:09:30 -0000
@@ -1,6 +1,7 @@
 <?php
 //$Id: uc_discounts.module,v 1.26 2009/05/26 01:45:13 ryangroe Exp $
 
+
 /**
  * @file
  * Discounts module for Ubercart 2.0+.
@@ -39,7 +40,8 @@ define("HAS_EXPIRATION_DEFAULT", FALSE);
 define("IS_PUBLISHED_DEFAULT", FALSE);
 
 define("LINE_ITEM_KEY_NAME", "uc_discounts");
-define("LINE_ITEM_WEIGHT", 1); //(1 to follow subtotal)
+// (1 to follow subtotal)
+define("LINE_ITEM_WEIGHT", 1);
 define("CALCULATE_DISCOUNT_RESPONSE_LINE_ITEMS_KEY", "line_items");
 define("CALCULATE_DISCOUNT_RESPONSE_ERRORS_KEY", "errors");
 define("CALCULATE_DISCOUNT_RESPONSE_MESSAGES_KEY", "messages");
@@ -52,86 +54,81 @@ define("CALCULATE_DISCOUNT_RESPONSE_MESS
 /**
  * Implementation of hook_init().
  */
-function uc_discounts_init()
-{
-	drupal_add_css(drupal_get_path("module", "uc_discounts") . "/uc_discounts.css");
+function uc_discounts_init() {
+  drupal_add_css(drupal_get_path("module", "uc_discounts") ."/uc_discounts.css");
 }
 
-function uc_discounts_help($path, $arg)
-{
-	switch ($path)
-	{
-		case "admin/store/settings/uc_discounts":
-			return t("Add and review discounts");
-	}
-	return $output;
+function uc_discounts_help($path, $arg) {
+  switch ($path) {
+    case "admin/store/settings/uc_discounts":
+      return t("Add and review discounts");
+  }
+  return $output;
 }
 
 /**
  * Implementation of hook_perm().
  */
-function uc_discounts_perm()
-{
-	return array("configure discounts");
+function uc_discounts_perm() {
+  return array("configure discounts");
 }
 
 /**
  * Implementation of hook_menu().
  */
-function uc_discounts_menu()
-{
-	$items = array();
-
-	$items["admin/store/settings/uc_discounts"] = array(
-		"title" => "Discount settings",
-		"description" => "Configure discount settings.",
-		"page callback" => "uc_discounts_admin_settings",
-		"access arguments" => array("configure discounts"),
-		"file" => "uc_discounts.admin.inc",
-	);
-	$items["admin/store/settings/uc_discounts/edit"] = array(
-		"title" => "Edit discount rule",
-		"page callback" => "drupal_get_form",
-		"page arguments" => array("uc_discounts_form"),
-		"access arguments" => array("configure discounts"),
-		"type" => MENU_CALLBACK,
-		"file" => "uc_discounts.admin.inc",
-	);
-	$items["admin/store/settings/uc_discounts/copy"] = array(
-		"page callback" => "uc_discounts_copy",
-		"access arguments" => array("configure discounts"),
-		"type" => MENU_CALLBACK,
-		"file" => "uc_discounts.admin.inc",
-	);
-	$items["admin/store/settings/uc_discounts/delete"] = array(
-		"title" => "Delete discount rule",
-		"page callback" => "drupal_get_form",
-		"page arguments" => array("uc_discounts_delete"),
-		"access arguments" => array("configure discounts"),
-		"type" => MENU_CALLBACK,
-		"file" => "uc_discounts.admin.inc",
-	);
-	$items["cart/checkout/uc_discounts/calculate"] = array(
-		"page callback" => "uc_discounts_js_calculate",
-		"access arguments" => array("access content"),
-		"type" => MENU_CALLBACK,
-	);
-	$items["admin/reports/uc_discounts/all"] = array(
-		"title" => "Ubercart discounts usage data",
-		"description" => "View usage data for each Ubercart discount.",
-		"page callback" => "uc_discounts_report",
-		"access arguments" => array("access site reports"),
-		"file" => "uc_discounts.admin.inc",
-	);
-	$items["admin/reports/uc_discounts/discount"] = array(
-		"title" => "Ubercart discount usage data",
-		"page callback" => "uc_discounts_report_for_discount",
-		"access arguments" => array("access site reports"),
-	    "type" => MENU_CALLBACK,
-		"file" => "uc_discounts.admin.inc",
-	);
+function uc_discounts_menu() {
+  $items = array();
+
+  $items["admin/store/settings/uc_discounts"] = array(
+    "title" => "Discount settings",
+    "description" => "Configure discount settings.",
+    "page callback" => "uc_discounts_admin_settings",
+    "access arguments" => array("configure discounts"),
+    "file" => "uc_discounts.admin.inc",
+  );
+  $items["admin/store/settings/uc_discounts/edit"] = array(
+    "title" => "Edit discount rule",
+    "page callback" => "drupal_get_form",
+    "page arguments" => array("uc_discounts_form"),
+    "access arguments" => array("configure discounts"),
+    "type" => MENU_CALLBACK,
+    "file" => "uc_discounts.admin.inc",
+  );
+  $items["admin/store/settings/uc_discounts/copy"] = array(
+    "page callback" => "uc_discounts_copy",
+    "access arguments" => array("configure discounts"),
+    "type" => MENU_CALLBACK,
+    "file" => "uc_discounts.admin.inc",
+  );
+  $items["admin/store/settings/uc_discounts/delete"] = array(
+    "title" => "Delete discount rule",
+    "page callback" => "drupal_get_form",
+    "page arguments" => array("uc_discounts_delete"),
+    "access arguments" => array("configure discounts"),
+    "type" => MENU_CALLBACK,
+    "file" => "uc_discounts.admin.inc",
+  );
+  $items["cart/checkout/uc_discounts/calculate"] = array(
+    "page callback" => "uc_discounts_js_calculate",
+    "access arguments" => array("access content"),
+    "type" => MENU_CALLBACK,
+  );
+  $items["admin/reports/uc_discounts/all"] = array(
+    "title" => "Ubercart discounts usage data",
+    "description" => "View usage data for each Ubercart discount.",
+    "page callback" => "uc_discounts_report",
+    "access arguments" => array("access site reports"),
+    "file" => "uc_discounts.admin.inc",
+  );
+  $items["admin/reports/uc_discounts/discount"] = array(
+    "title" => "Ubercart discount usage data",
+    "page callback" => "uc_discounts_report_for_discount",
+    "access arguments" => array("access site reports"),
+    "type" => MENU_CALLBACK,
+    "file" => "uc_discounts.admin.inc",
+  );
 
-	return $items;
+  return $items;
 }
 
 /**
@@ -139,215 +136,201 @@ function uc_discounts_menu()
  *
  * Manages order->uc_discounts_codes (array of code) and order->discounts (array of uses)
  */
-function uc_discounts_order($op, &$arg1, $arg2)
-{
-	switch ($op)
-	{
-		case "load":
-			//Get order's codes from database
-			$codes_string = uc_discounts_order_codes_get($arg1->order_id);
-			$arg1->uc_discounts_codes = get_codes($codes_string);
-			break;
-
-		case "save":
-			//If discount line items need updating
-			if ($arg1->uc_discounts_line_items_need_updating)
-			{
-				//Delete existing order codes
-				uc_discounts_order_codes_delete($arg1->order_id);
-
-				//Save order's codes as string
-				$codes_string = create_codes_string($arg1->uc_discounts_codes);
-				uc_discounts_order_codes_insert($arg1->order_id, $codes_string);
-
-				//Get order line items
-				if ( is_array($arg1->line_items) )
-					$existing_line_items = $arg1->line_items;
-				else
-					$existing_line_items = uc_order_load_line_items($arg1->order_id, TRUE);
-
-				//Use new_order_line_items to populate $arg1->line_items by:
-				//	Storing all non-discounts line items
-				//	Storing new discount line items
-				$new_order_line_items = array();
-
-				//Delete existing discount line items
-				foreach ($existing_line_items as $line_item)
-				{
-					if ($line_item["type"] == LINE_ITEM_KEY_NAME)
-						uc_order_delete_line_item($line_item["line_item_id"]);
-					//Otherwise store non-discount line item
-					else
-						$new_order_line_items[] = $line_item;
-				}
-
-				//Add discount line items
-				foreach ($arg1->uc_discounts_line_items as $line_item)
-				{
-					uc_order_line_item_add($arg1->order_id, $line_item["type"], $line_item["title"], 
-						$line_item["amount"], $line_item["weight"]);
-					$new_order_line_items[] = $line_item;
-				}
-
-				//Update order line items (see new_order_line_items notes above)
-				$arg1->line_items = $new_order_line_items;
-
-				//Force tax recalculation (currently unused but may be required if line item weights change)
-				//module_invoke("uc_taxes", "order", "save", $arg1, "");
-
-				$arg1->uc_discounts_line_items_need_updating = FALSE;
-			}
-
-			break;
-
-		case "update":
-			//If status changes to "cancelled", delete order uses
-			if ($arg2 == "cancelled")
-				uc_discounts_uses_delete_for_order($arg1->order_id);
-			break;
-
-		case "submit":
-			//Ensure stored discounts are accurate (recalculate and match new amounts against stored amounts)
-
-			//Store existing discount amounts			
-			$existing_discount_amounts = array();
-			foreach (get_existing_discount_line_items($arg1) as $line_item)
-				$existing_discount_amounts[] = uc_currency_format($line_item["amount"]);
-
-
-			//Regenerate discount amounts			
-
-			$errors = array();
-			$warnings = array();
-			$messages = array();
-			$discounts = get_discounts_for_order($arg1, $errors, $warnings, $messages);
-
-			//If there were errors, print and return FALSE
-			if ( !empty($errors) )
-			{
-				foreach ($errors as $error)
-					drupal_set_message($error, "error");
-				return array(  array( 'pass' => FALSE, 
-					'message' => t('Discounts have changed.  Please review your cart and continue checkout.') )  );
-			}
-
-			//Add discount line items to order
-			add_discount_line_items_to_order($arg1, $discounts);
-
-			$new_discount_amounts = array();
-			foreach ($arg1->uc_discounts_line_items as $line_item)
-				$new_discount_amounts[] = uc_currency_format($line_item["amount"]);
-
-			$discount_intersection = array_intersect($existing_discount_amounts, $new_discount_amounts);
-			if ( count($discount_intersection) != count($existing_discount_amounts) )
-			{
-				//Save new discount line items
-				$arg1->uc_discounts_line_items_need_updating = TRUE;
-				uc_discounts_order("save", $arg1, NULL);
-				
-				return array(  array( 'pass' => FALSE, 
-					'message' => t('Discounts have changed.  Please review your cart and continue checkout.') )  );
-			}
-
-			//Delete existing uses for order
-			uc_discounts_uses_delete_for_order($arg1->order_id);
-
-			//Insert uses (for best results use discounts returned by call to get_discounts_for_order)
-			foreach ($discounts as $discount)
-			{
-				$code = ( !empty($discount->code) ) ? $discount->code : "";
-				$times_applied = ( is_numeric($discount->times_applied) ) ? $discount->times_applied : 1;
-				$amount = ( is_numeric($discount->amount) ) ? $discount->amount : 0;
-
-				uc_discounts_uses_insert($discount->discount_id, $arg1->uid, 
-					$arg1->order_id, $code, $times_applied, $amount);
-			}
-
-			//Add discount messages to order			
-			uc_order_log_changes($arg1->order_id, $messages);
-
-			break;
-
-		case "delete":
-			//Delete existing order codes
-			uc_discounts_order_codes_delete($arg1->order_id);
-//TO DO: determine if uses should be deleted or put global setting in for user to decide
-			break;
-	}
+function uc_discounts_order($op, &$arg1, $arg2) {
+  switch ($op) {
+    case "load":
+      //Get order's codes from database
+      $codes_string = uc_discounts_order_codes_get($arg1->order_id);
+      $arg1->uc_discounts_codes = get_codes($codes_string);
+      break;
+
+    case "save":
+      //If discount line items need updating
+      if ($arg1->uc_discounts_line_items_need_updating) {
+        //Delete existing order codes
+        uc_discounts_order_codes_delete($arg1->order_id);
+
+        //Save order's codes as string
+        $codes_string = create_codes_string($arg1->uc_discounts_codes);
+        uc_discounts_order_codes_insert($arg1->order_id, $codes_string);
+
+        //Get order line items
+        if (is_array($arg1->line_items)) {
+          $existing_line_items = $arg1->line_items;
+        }
+        else $existing_line_items = uc_order_load_line_items($arg1->order_id, TRUE);
+
+        //Use new_order_line_items to populate $arg1->line_items by:
+        //	Storing all non-discounts line items
+        //	Storing new discount line items
+        $new_order_line_items = array();
+
+        //Delete existing discount line items
+        foreach ($existing_line_items as $line_item) {
+          if ($line_item["type"] == LINE_ITEM_KEY_NAME) {
+            uc_order_delete_line_item($line_item["line_item_id"]);
+          }
+          //Otherwise store non-discount line item
+          else $new_order_line_items[] = $line_item;
+        }
+
+        //Add discount line items
+        foreach ($arg1->uc_discounts_line_items as $line_item) {
+          uc_order_line_item_add($arg1->order_id, $line_item["type"], $line_item["title"],
+            $line_item["amount"], $line_item["weight"]
+          );
+          $new_order_line_items[] = $line_item;
+        }
+
+        //Update order line items (see new_order_line_items notes above)
+        $arg1->line_items = $new_order_line_items;
+
+        //Force tax recalculation (currently unused but may be required if line item weights change)
+        //module_invoke("uc_taxes", "order", "save", $arg1, "");
+
+        $arg1->uc_discounts_line_items_need_updating = FALSE;
+      }
+      break;
+
+    case "update":
+      //If status changes to "cancelled", delete order uses
+      if ($arg2 == "cancelled") {
+        uc_discounts_uses_delete_for_order($arg1->order_id);
+      }
+      break;
+
+    case "submit":
+      //Ensure stored discounts are accurate (recalculate and match new amounts against stored amounts)
+
+      //Store existing discount amounts
+      $existing_discount_amounts = array();
+      foreach (get_existing_discount_line_items($arg1) as $line_item) $existing_discount_amounts[] = uc_currency_format($line_item["amount"]);
+
+
+      //Regenerate discount amounts
+
+      $errors    = array();
+      $warnings  = array();
+      $messages  = array();
+      $discounts = get_discounts_for_order($arg1, $errors, $warnings, $messages);
+
+      //If there were errors, print and return FALSE
+      if (!empty($errors)) {
+        foreach ($errors as $error) drupal_set_message($error, "error");
+        return array(array('pass' => FALSE,
+            'message' => t('Discounts have changed.  Please review your cart and continue checkout.'),
+          ));
+      }
+
+      //Add discount line items to order
+      add_discount_line_items_to_order($arg1, $discounts);
+
+      $new_discount_amounts = array();
+      foreach ($arg1->uc_discounts_line_items as $line_item) $new_discount_amounts[] = uc_currency_format($line_item["amount"]);
+
+      $discount_intersection = array_intersect($existing_discount_amounts, $new_discount_amounts);
+      if (count($discount_intersection) != count($existing_discount_amounts)) {
+        //Save new discount line items
+        $arg1->uc_discounts_line_items_need_updating = TRUE;
+        uc_discounts_order("save", $arg1, NULL);
+
+        return array(array('pass' => FALSE,
+            'message' => t('Discounts have changed.  Please review your cart and continue checkout.'),
+          ));
+      }
+
+      //Delete existing uses for order
+      uc_discounts_uses_delete_for_order($arg1->order_id);
+
+      //Insert uses (for best results use discounts returned by call to get_discounts_for_order)
+      foreach ($discounts as $discount) {
+        $code          = (!empty($discount->code)) ? $discount->code : "";
+        $times_applied = (is_numeric($discount->times_applied)) ? $discount->times_applied : 1;
+        $amount        = (is_numeric($discount->amount)) ? $discount->amount : 0;
+
+        uc_discounts_uses_insert($discount->discount_id, $arg1->uid,
+          $arg1->order_id, $code, $times_applied, $amount
+        );
+      }
+
+      //Add discount messages to order
+      uc_order_log_changes($arg1->order_id, $messages);
+      break;
+
+    case "delete":
+      //Delete existing order codes
+      uc_discounts_order_codes_delete($arg1->order_id);
+      //TO DO: determine if uses should be deleted or put global setting in for user to decide
+      break;
+  }
 }
 
 /**
  * Implementation of Ubercart's hook_line_item().
  */
-function uc_discounts_line_item()
-{
-	$line_items[] = array(
-		"id" => LINE_ITEM_KEY_NAME,
-		"title" => t("Discount"),
-		"weight" => LINE_ITEM_WEIGHT,
-		"stored" => TRUE,
-		"calculated" => TRUE, //Added to total
-		"display_only" => FALSE,
-	);
-	return $line_items;
+function uc_discounts_line_item() {
+  $line_items[] = array(
+    "id" => LINE_ITEM_KEY_NAME,
+    "title" => t("Discount"),
+    "weight" => LINE_ITEM_WEIGHT,
+    "stored" => TRUE,
+    // Added to total
+    "calculated" => TRUE,
+    "display_only" => FALSE,
+  );
+  return $line_items;
 }
 
 /**
  * Implementation of hook_cart_pane().
  */
-function uc_discounts_cart_pane($items)
-{
-	global $user;
-
-	//Create phony order object to call to get_discounts_for_order
-	$order = new stdClass();
-	$order->uid = $user->uid;
-	$order->products = $items;
-	
-	$errors = array();
-	$warnings = array();
-	$messages = array();
-	$discounts = get_discounts_for_order($order, $errors, $warnings, $messages);
-
-	//If there are no discounts, do not alter cart
-	if (count($discounts) == 0)
-		return array();
-
-	//Calculate subtotal with discounts
-	$subtotal = 0;
-	foreach ($items as $item)
-		$subtotal += $item->price * $item->qty;
-	$total_discount_amount = 0;
-	foreach ($discounts as $discount)
-		$total_discount_amount += $discount->amount;
-	$subtotal_including_discounts = $subtotal - $total_discount_amount;
-
-	//Add total discount message
-	$messages[] = "<strong>" . t("Total discount") . ":</strong>&nbsp;"
-		. uc_currency_format($total_discount_amount);
-
-	//Add new subtotal message
-	$messages[] = "<strong>" . t("Subtotal including discounts") . ":</strong>&nbsp;"
-		. uc_currency_format($subtotal_including_discounts);
-
-	//Start row index at item count + 2 (1 for subtotal row in cart form, 1 more for our first row)
-	$i = count($items) + 2;
-
-	//Create table to hold discount messages
-	$body = "<div class='uc-discounts-cart-pane-container'><table class='uc-discounts-cart-pane-table'>";
-	foreach ($messages as $message)
-	{
-		$evenOddClass = ( ($i % 2) == 0 ) ? "even" : "odd";
-		$body .= sprintf("<tr class='%s'><td class='%s'>", $evenOddClass, "uc-discounts-cart-pane-table-cell") 
-			. $message . "</td></tr>";
-		$i += 1;
-	}
+function uc_discounts_cart_pane($items) {
+  global $user;
+
+  //Create phony order object to call to get_discounts_for_order
+  $order           = new stdClass();
+  $order->uid      = $user->uid;
+  $order->products = $items;
+
+  $errors    = array();
+  $warnings  = array();
+  $messages  = array();
+  $discounts = get_discounts_for_order($order, $errors, $warnings, $messages);
+
+  //If there are no discounts, do not alter cart
+  if (count($discounts) == 0) {
+    return array();
+  }
+
+  //Calculate subtotal with discounts
+  $subtotal = 0;
+  foreach ($items as $item) $subtotal += $item->price * $item->qty;
+  $total_discount_amount = 0;
+  foreach ($discounts as $discount) $total_discount_amount += $discount->amount;
+  $subtotal_including_discounts = $subtotal - $total_discount_amount;
+
+  //Add total discount message
+  $messages[] = "<strong>". t("Total discount") .":</strong>&nbsp;". uc_currency_format($total_discount_amount);
+
+  //Add new subtotal message
+  $messages[] = "<strong>". t("Subtotal including discounts") .":</strong>&nbsp;". uc_currency_format($subtotal_including_discounts);
+
+  //Start row index at item count + 2 (1 for subtotal row in cart form, 1 more for our first row)
+  $i = count($items) + 2;
+
+  //Create table to hold discount messages
+  $body = "<div class='uc-discounts-cart-pane-container'><table class='uc-discounts-cart-pane-table'>";
+  foreach ($messages as $message) {
+    $evenOddClass = (($i % 2) == 0) ? "even" : "odd";
+    $body .= sprintf("<tr class='%s'><td class='%s'>", $evenOddClass, "uc-discounts-cart-pane-table-cell") . $message ."</td></tr>";
+    $i += 1;
+  }
 
-	//Close table
-	$body .= "</table></div>";
+  //Close table
+  $body .= "</table></div>";
 
-	//Write table using javascript between items and cart form buttons
-	drupal_add_js(sprintf("$(document).ready(function()
+  //Write table using javascript between items and cart form buttons
+  drupal_add_js(sprintf("$(document).ready(function()
 		{
 			$(\"#cart-form-buttons\").before(\"%s\");
 		});", $body), "inline");
@@ -356,16 +339,15 @@ function uc_discounts_cart_pane($items)
 /**
  * Implementation of hook_checkout_pane().
  */
-function uc_discounts_checkout_pane()
-{
-	$panes[] = array(
-		"id" => "uc_discounts",
-		"callback" => "uc_checkout_pane_discounts",
-		'process' => TRUE,
-		"title" => t("Enter discount codes"),
-		"weight" => 5,
-	);
-	return $panes;
+function uc_discounts_checkout_pane() {
+  $panes[] = array(
+    "id" => "uc_discounts",
+    "callback" => "uc_checkout_pane_discounts",
+    'process' => TRUE,
+    "title" => t("Enter discount codes"),
+    "weight" => 5,
+  );
+  return $panes;
 }
 
 /**
@@ -373,92 +355,90 @@ function uc_discounts_checkout_pane()
  *
  * More information at http://www.ubercart.org/docs/developer/245/checkout
  */
-function uc_checkout_pane_discounts($op, &$arg1, $arg2)
-{
-	global $user;
-
-	switch ($op)
-	{
-		case "view":
-			//Add form to checkout pane
-
-			$description = t("Enter discount codes in the box below (one per line).");
-
-			//If viewing an existing order, load order's codes
-			if ( !empty($arg1->order_id) )
-				$codes_string = uc_discounts_order_codes_get($arg1->order_id);
-
-			$contents["uc-discounts-codes"] = array(
-				"#type" => "textarea",
-				"#default_value" => $codes_string,
-				"#rows" => 5,
-				"#prefix" => "<div class='discount-codes-wrapper'>",
-				"#suffix" => "</div>",
-			);
-
-			$contents["uc-discounts-placeholder"] = array(
-				"#type" => "hidden",
-				"#prefix" => "<div class='uc-discounts-messages-container'>",
-				"#suffix" => "</div>",
-			);
-
-			$contents["uc-discounts-button"] = array(
-				"#type" => "button",
-				"#value" => t("Click to calculate discounts"),
-			);
-
-			drupal_add_js(array(
-				"uc_discounts" => array(
-					"line_item_key_name" => LINE_ITEM_KEY_NAME,
-					"line_item_weight" => LINE_ITEM_WEIGHT,
-					"total_discount_text" => t("Total discount"),
-					"calculate_discount_response_line_items_key" => CALCULATE_DISCOUNT_RESPONSE_LINE_ITEMS_KEY,
-					"calculate_discount_response_errors_key" => CALCULATE_DISCOUNT_RESPONSE_ERRORS_KEY,
-					"calculate_discount_response_messages_key" => CALCULATE_DISCOUNT_RESPONSE_MESSAGES_KEY,
-					"progress_msg" => t("Calculating discounts..."),
-					"no_codes_entered" => t("Please enter at least one code"),
-					"no_applicable_discounts" => t("No applicable discounts"),
-					"err_msg" => t(  "There were problems determining if any discounts apply.  Please try again shortly.\nIf this does not resolve the issue, please call @phone to complete your order.", 
-							array( "@phone" => variable_get("uc_store_phone", NULL) )  ),
-					"response_parse_err_msg" => t("Unable to parse response text: "),
-				)
-			), "setting");
-
-			drupal_add_js("$(document).ready(function() { uc_discountsOnLoad(); });", "inline");
-			drupal_add_js("misc/progress.js");
-			drupal_add_js(drupal_get_path("module", "uc_discounts") . "/uc_discounts.js");
-
-			return array("description" => $description, "contents" => $contents);
-
-		case "process":
-//TO DO: only update codes if codes_string ($arg2["uc-discounts-codes"]) has changed
-
-			//Save form values from checkout pane in order ($arg1)
-			$arg1->uc_discounts_codes = get_codes($arg2["uc-discounts-codes"]);
-
-			$has_code_errors = FALSE;
-
-			$errors = array();
-			$warnings = array();
-			$discounts = get_discounts_for_order($arg1, $errors, $warnings);
-
-			foreach ($errors as $error)
-				drupal_set_message($error, "error");
-			foreach ($warnings as $warning)
-				drupal_set_message(t("Warning:") . $warning, "error");
-			
-			//If there were errors, return FALSE
-			if ( !empty($errors) )
-				return FALSE;
-
-			//Add discount line items to order
-			add_discount_line_items_to_order($arg1, $discounts);
-
-			//Mark order as needing discount line items updated
-			$arg1->uc_discounts_line_items_need_updating = TRUE;
+function uc_checkout_pane_discounts($op, &$arg1, $arg2) {
+  global $user;
 
-			break;
-	}
+  switch ($op) {
+    case "view":
+      //Add form to checkout pane
+
+      $description = t("Enter discount codes in the box below (one per line).");
+
+      //If viewing an existing order, load order's codes
+      if (!empty($arg1->order_id)) {
+        $codes_string = uc_discounts_order_codes_get($arg1->order_id);
+      }
+
+      $contents["uc-discounts-codes"] = array(
+        "#type" => "textarea",
+        "#default_value" => $codes_string,
+        "#rows" => 5,
+        "#prefix" => "<div class='discount-codes-wrapper'>",
+        "#suffix" => "</div>",
+      );
+
+      $contents["uc-discounts-placeholder"] = array(
+        "#type" => "hidden",
+        "#prefix" => "<div class='uc-discounts-messages-container'>",
+        "#suffix" => "</div>",
+      );
+
+      $contents["uc-discounts-button"] = array(
+        "#type" => "button",
+        "#value" => t("Click to calculate discounts"),
+      );
+
+      drupal_add_js(array(
+          "uc_discounts" => array(
+            "line_item_key_name" => LINE_ITEM_KEY_NAME,
+            "line_item_weight" => LINE_ITEM_WEIGHT,
+            "total_discount_text" => t("Total discount"),
+            "calculate_discount_response_line_items_key" => CALCULATE_DISCOUNT_RESPONSE_LINE_ITEMS_KEY,
+            "calculate_discount_response_errors_key" => CALCULATE_DISCOUNT_RESPONSE_ERRORS_KEY,
+            "calculate_discount_response_messages_key" => CALCULATE_DISCOUNT_RESPONSE_MESSAGES_KEY,
+            "progress_msg" => t("Calculating discounts..."),
+            "no_codes_entered" => t("Please enter at least one code"),
+            "no_applicable_discounts" => t("No applicable discounts"),
+            "err_msg" => t("There were problems determining if any discounts apply.  Please try again shortly.\nIf this does not resolve the issue, please call @phone to complete your order.",
+              array("@phone" => variable_get("uc_store_phone", NULL))
+            ),
+            "response_parse_err_msg" => t("Unable to parse response text: "),
+          ),
+        ), "setting");
+
+      drupal_add_js("$(document).ready(function() { uc_discountsOnLoad(); });", "inline");
+      drupal_add_js("misc/progress.js");
+      drupal_add_js(drupal_get_path("module", "uc_discounts") ."/uc_discounts.js");
+
+      return array("description" => $description, "contents" => $contents);
+
+    case "process":
+      //TO DO: only update codes if codes_string ($arg2["uc-discounts-codes"]) has changed
+
+      //Save form values from checkout pane in order ($arg1)
+      $arg1->uc_discounts_codes = get_codes($arg2["uc-discounts-codes"]);
+
+      $has_code_errors = FALSE;
+
+      $errors    = array();
+      $warnings  = array();
+      $discounts = get_discounts_for_order($arg1, $errors, $warnings);
+
+      foreach ($errors as $error) drupal_set_message($error, "error");
+      foreach ($warnings as $warning) drupal_set_message(t("Warning:") . $warning, "error");
+
+      //If there were errors, return FALSE
+      if (!empty($errors)) {
+        return FALSE;
+      }
+
+    //Add discount line items to order
+    add_discount_line_items_to_order($arg1, $discounts);
+
+    //Mark order as needing discount line items updated
+    $arg1->uc_discounts_line_items_need_updating = TRUE;
+    break;
+  }
 }
 
 /**
@@ -466,43 +446,40 @@ function uc_checkout_pane_discounts($op,
  *
  * Note: assumes discount objects are the result of a call to get_discounts_for_order()
  */
-function add_discount_line_items_to_order($order, $discounts)
-{
-	//Create line items for discounts and store in order's uc_discounts_line_items field
-	$line_items = array();
-	foreach ($discounts as $discount)
-	{
-		$line_item = array(
-			"type" => LINE_ITEM_KEY_NAME,
-			"title" => $discount->short_description,
-			"amount" => -$discount->amount,
-			"weight" => LINE_ITEM_WEIGHT,
-		);
-		
-		$line_items[] = $line_item;
-	}
-	$order->uc_discounts_line_items = $line_items;
+function add_discount_line_items_to_order($order, $discounts) {
+  //Create line items for discounts and store in order's uc_discounts_line_items field
+  $line_items = array();
+  foreach ($discounts as $discount) {
+    $line_item = array(
+      "type" => LINE_ITEM_KEY_NAME,
+      "title" => $discount->short_description,
+      "amount" => -$discount->amount,
+      "weight" => LINE_ITEM_WEIGHT,
+    );
+
+    $line_items[] = $line_item;
+  }
+  $order->uc_discounts_line_items = $line_items;
 }
 
 /**
  * Returns existing discounts line items for order.
  */
-function get_existing_discount_line_items($order)
-{
-	if ( is_array($order->line_items) )
-		$existing_line_items = $order->line_items;
-	else
-		$existing_line_items = uc_order_load_line_items($order->order_id, TRUE);
-
-	$line_items = array();
-	foreach ($existing_line_items as $line_item)
-	{
-		//If line item type is LINE_ITEM_KEY_NAME, add it to array
-		if ($line_item["type"] == LINE_ITEM_KEY_NAME)
-			$line_items[] = $line_item;
-	}
-	
-	return $line_items;
+function get_existing_discount_line_items($order) {
+  if (is_array($order->line_items)) {
+    $existing_line_items = $order->line_items;
+  }
+  else $existing_line_items = uc_order_load_line_items($order->order_id, TRUE);
+
+  $line_items = array();
+  foreach ($existing_line_items as $line_item) {
+    //If line item type is LINE_ITEM_KEY_NAME, add it to array
+    if ($line_item["type"] == LINE_ITEM_KEY_NAME) {
+      $line_items[] = $line_item;
+    }
+  }
+
+  return $line_items;
 }
 
 /**
@@ -510,64 +487,58 @@ function get_existing_discount_line_item
  *
  * Calculate discount for an order in the checkout page.
  */
-function uc_discounts_js_calculate()
-{
-	global $user;
-
-	//If session order exists, use it
-	if ( !empty($_SESSION["cart_order"]) )
-	{
-		$order_id = $_SESSION['cart_order'];
-		$order = uc_order_load($order_id);
-		if ( is_null($order) )
-		{
-			print "{}";
-			exit();
-			return;
-		}
-	}
-	//Otherwise create phony order
-	else
-	{
-		$order = new stdClass();
-		$order->uid = $user->uid;
-		$order->products = uc_cart_get_contents();
-	}
-
-	$order->uc_discounts_codes = get_codes($_POST["uc-discounts-codes"]);
-	
-	$line_items = array();
-	$errors = array();
-	$warnings = array();
-	$messages = array();
-
-	$discounts = get_discounts_for_order($order, $errors, $warnings, $messages);
-
-	$i = 0;
-	foreach ($discounts as $discount)
-	{
-		$line_item = array();
-		$line_item["id"] = LINE_ITEM_KEY_NAME . $i++;
-		$line_item["type"] = $discount->type;
-		$line_item["title"] = $discount->title;
-		$line_item["amount"] = -$discount->amount;
-		$line_item["weight"] = $discount->weight;
-		$line_items[] = $line_item;
-	}
-
-	if ( !empty($warnings) )
-	{
-		$warnings2 = array();
-		foreach ($warnings as $warning)
-			$warnings2[] = t("Warning:") . $warning;
-		$errors = array_merge($errors, $warnings2);
-	}
-
-	$calculate_discount_response = array(CALCULATE_DISCOUNT_RESPONSE_LINE_ITEMS_KEY => $line_items, 
-		CALCULATE_DISCOUNT_RESPONSE_ERRORS_KEY => $errors,
-		CALCULATE_DISCOUNT_RESPONSE_MESSAGES_KEY => $messages);
-	drupal_json($calculate_discount_response);
-	exit();
+function uc_discounts_js_calculate() {
+  global $user;
+
+  //If session order exists, use it
+  if (!empty($_SESSION["cart_order"])) {
+    $order_id = $_SESSION['cart_order'];
+    $order = uc_order_load($order_id);
+    if (is_null($order)) {
+      print "{}";
+      exit();
+      return;
+    }
+  }
+  //Otherwise create phony order
+  else {
+    $order           = new stdClass();
+    $order->uid      = $user->uid;
+    $order->products = uc_cart_get_contents();
+  }
+
+  $order->uc_discounts_codes = get_codes($_POST["uc-discounts-codes"]);
+
+  $line_items = array();
+  $errors     = array();
+  $warnings   = array();
+  $messages   = array();
+
+  $discounts = get_discounts_for_order($order, $errors, $warnings, $messages);
+
+  $i = 0;
+  foreach ($discounts as $discount) {
+    $line_item           = array();
+    $line_item["id"]     = LINE_ITEM_KEY_NAME . $i++;
+    $line_item["type"]   = $discount->type;
+    $line_item["title"]  = $discount->title;
+    $line_item["amount"] = -$discount->amount;
+    $line_item["weight"] = $discount->weight;
+    $line_items[]        = $line_item;
+  }
+
+  if (!empty($warnings)) {
+    $warnings2 = array();
+    foreach ($warnings as $warning) $warnings2[] = t("Warning:") . $warning;
+    $errors = array_merge($errors, $warnings2);
+  }
+
+  $calculate_discount_response = array(CALCULATE_DISCOUNT_RESPONSE_LINE_ITEMS_KEY => $line_items,
+    CALCULATE_DISCOUNT_RESPONSE_ERRORS_KEY => $errors,
+    CALCULATE_DISCOUNT_RESPONSE_MESSAGES_KEY => $messages,
+  );
+  drupal_json($calculate_discount_response);
+  exit();
 }
 
 
@@ -578,375 +549,348 @@ function uc_discounts_js_calculate()
 /**
  * Returns array of uc_discounts column names.
  */
-function get_uc_discounts_column_names()
-{
-	return array("name", "short_description", "description", "qualifying_type", 
-		"qualifying_amount", "has_qualifying_amount_max", "qualifying_amount_max", "discount_type", 
-		"discount_amount", "requires_code", "filter_type", "has_role_filter", 
-		"requires_single_product_to_qualify", "max_times_applied", "can_be_combined_with_other_discounts", "max_uses", 
-		"max_uses_per_user", "max_uses_per_code", "has_expiration", "expiration", 
-		"is_published", "weight");
+function get_uc_discounts_column_names() {
+  return array("name", "short_description", "description", "qualifying_type",
+    "qualifying_amount", "has_qualifying_amount_max", "qualifying_amount_max", "discount_type",
+    "discount_amount", "requires_code", "filter_type", "has_role_filter",
+    "requires_single_product_to_qualify", "max_times_applied", "can_be_combined_with_other_discounts", "max_uses",
+    "max_uses_per_user", "max_uses_per_code", "has_expiration", "expiration",
+    "is_published", "weight",
+  );
 }
+
 /**
  * Returns array of uc_discounts insert column names.
  */
-function get_uc_discounts_insert_column_names()
-{
-	return array_merge( get_uc_discounts_column_names(), array("insert_timestamp") );
+function get_uc_discounts_insert_column_names() {
+  return array_merge(get_uc_discounts_column_names(), array("insert_timestamp"));
 }
+
 /**
  * Returns array of uc_discounts update column names.
  */
-function get_uc_discounts_update_column_names()
-{
-	return get_uc_discounts_column_names();
+function get_uc_discounts_update_column_names() {
+  return get_uc_discounts_column_names();
 }
 
 /**
  * Returns array of uc_discounts column printf wildcards.
  */
-function get_uc_discounts_column_printf_wildcards()
-{
-	return array("'%s'", "'%s'", "'%s'", "%d", 
-		"%f", "%d", "%f", "%d", 
-		"%f", "%d", "%d", "%d", 
-		"%d", "%d", "%d", "%d", 
-		"%d", "%d", "%d", "%d", 
-		"%d", "%d");
+function get_uc_discounts_column_printf_wildcards() {
+  return array("'%s'", "'%s'", "'%s'", "%d",
+    "%f", "%d", "%f", "%d",
+    "%f", "%d", "%d", "%d",
+    "%d", "%d", "%d", "%d",
+    "%d", "%d", "%d", "%d",
+    "%d", "%d",
+  );
 }
+
 /**
  * Returns array of uc_discounts insert column printf wildcards.
  */
-function get_uc_discounts_column_insert_printf_wildcards()
-{
-	return array_merge( get_uc_discounts_column_printf_wildcards(), array("%d") );
+function get_uc_discounts_column_insert_printf_wildcards() {
+  return array_merge(get_uc_discounts_column_printf_wildcards(), array("%d"));
 }
+
 /**
  * Returns array of uc_discounts update column printf wildcards.
  */
-function get_uc_discounts_column_update_printf_wildcards()
-{
-	return get_uc_discounts_column_printf_wildcards();
+function get_uc_discounts_column_update_printf_wildcards() {
+  return get_uc_discounts_column_printf_wildcards();
 }
 
 /**
  * Inserts a uc_discounts row and returns its discount_id.
  */
-function uc_discounts_insert($name, $short_description, $description, $qualifying_type, 
-	$qualifying_amount, $has_qualifying_amount_max, $qualifying_amount_max, $discount_type, 
-	$discount_amount, $requires_code, $filter_type, $has_role_filter, 
-	$requires_single_product_to_qualify, $max_times_applied, $can_be_combined_with_other_discounts, $max_uses, 
-	$max_uses_per_user, $max_uses_per_code, $has_expiration, $expiration, 
-	$is_published, $weight, $insert_timestamp = NULL)
-{
-	if ( is_null($insert_timestamp) )
-		$insert_timestamp = time();
-
-	$query = "INSERT INTO {uc_discounts}(" . join( ",", get_uc_discounts_insert_column_names() ) 
-		. ") VALUES(" . join( ",", get_uc_discounts_column_insert_printf_wildcards() ) . ")";
-	uc_discounts_log("query=" . $query);
-	db_query($query, 
-		$name, $short_description, $description, $qualifying_type, 
-		$qualifying_amount, $has_qualifying_amount_max, $qualifying_amount_max, $discount_type, 
-		$discount_amount, $requires_code, $filter_type, $has_role_filter, 
-		$requires_single_product_to_qualify, $max_times_applied, $can_be_combined_with_other_discounts, $max_uses, 
-		$max_uses_per_user, $max_uses_per_code, $has_expiration, $expiration, 
-		$is_published, $weight, $insert_timestamp);
-	$discount_id = db_last_insert_id("uc_discounts", "discount_id");
-	uc_discounts_log("new discount_id=" . $discount_id);
-	return $discount_id;
+function uc_discounts_insert($name, $short_description, $description, $qualifying_type,
+  $qualifying_amount, $has_qualifying_amount_max, $qualifying_amount_max, $discount_type,
+  $discount_amount, $requires_code, $filter_type, $has_role_filter,
+  $requires_single_product_to_qualify, $max_times_applied, $can_be_combined_with_other_discounts, $max_uses,
+  $max_uses_per_user, $max_uses_per_code, $has_expiration, $expiration,
+  $is_published, $weight, $insert_timestamp = NULL
+) {
+  if (is_null($insert_timestamp)) {
+    $insert_timestamp = time();
+  }
+
+  $query = "INSERT INTO {uc_discounts}(". join(",", get_uc_discounts_insert_column_names()) .") VALUES(". join(",", get_uc_discounts_column_insert_printf_wildcards()) .")";
+  uc_discounts_log("query=". $query);
+  db_query($query,
+    $name, $short_description, $description, $qualifying_type,
+    $qualifying_amount, $has_qualifying_amount_max, $qualifying_amount_max, $discount_type,
+    $discount_amount, $requires_code, $filter_type, $has_role_filter,
+    $requires_single_product_to_qualify, $max_times_applied, $can_be_combined_with_other_discounts, $max_uses,
+    $max_uses_per_user, $max_uses_per_code, $has_expiration, $expiration,
+    $is_published, $weight, $insert_timestamp
+  );
+  $discount_id = db_last_insert_id("uc_discounts", "discount_id");
+  uc_discounts_log("new discount_id=". $discount_id);
+  return $discount_id;
 }
 
 /**
  * Updates a uc_discounts row.
  */
-function uc_discounts_update($discount_id, 
-	$name, $short_description, $description, $qualifying_type, 
-	$qualifying_amount, $has_qualifying_amount_max, $qualifying_amount_max, $discount_type, 
-	$discount_amount, $requires_code, $filter_type, $has_role_filter, 
-	$requires_single_product_to_qualify, $max_times_applied, $can_be_combined_with_other_discounts, $max_uses, 
-	$max_uses_per_user, $max_uses_per_code, $has_expiration, $expiration, 
-	$is_published, $weight)
-{
-	$query = "UPDATE {uc_discounts} SET ";
-	
-	$column_names = get_uc_discounts_update_column_names();
-	$printf_wildcards = get_uc_discounts_column_update_printf_wildcards();
-	
-	for ($i = 0; $i < count($column_names); $i++)
-	{
-		if ($i != 0)
-			$query .= ", ";
-		$query .= $column_names[$i] . "=" . $printf_wildcards[$i];
-	}
-	
-	$query .= " WHERE discount_id=%d";
-	
-	uc_discounts_log("query=" . $query);
-	db_query($query, 
-		$name, $short_description, $description, $qualifying_type, 
-		$qualifying_amount, $has_qualifying_amount_max, $qualifying_amount_max, $discount_type, 
-		$discount_amount, $requires_code, $filter_type, $has_role_filter, 
-		$requires_single_product_to_qualify, $max_times_applied, $can_be_combined_with_other_discounts, $max_uses, 
-		$max_uses_per_user, $max_uses_per_code, $has_expiration, $expiration, 
-		$is_published, $weight, $discount_id);
+function uc_discounts_update($discount_id,
+  $name, $short_description, $description, $qualifying_type,
+  $qualifying_amount, $has_qualifying_amount_max, $qualifying_amount_max, $discount_type,
+  $discount_amount, $requires_code, $filter_type, $has_role_filter,
+  $requires_single_product_to_qualify, $max_times_applied, $can_be_combined_with_other_discounts, $max_uses,
+  $max_uses_per_user, $max_uses_per_code, $has_expiration, $expiration,
+  $is_published, $weight
+) {
+  $query = "UPDATE {uc_discounts} SET ";
+
+  $column_names = get_uc_discounts_update_column_names();
+  $printf_wildcards = get_uc_discounts_column_update_printf_wildcards();
+
+  for ($i = 0; $i < count($column_names); $i++) {
+    if ($i != 0) {
+      $query .= ", ";
+    }
+    $query .= $column_names[$i] ."=". $printf_wildcards[$i];
+  }
+
+  $query .= " WHERE discount_id=%d";
+
+  uc_discounts_log("query=". $query);
+  db_query($query,
+    $name, $short_description, $description, $qualifying_type,
+    $qualifying_amount, $has_qualifying_amount_max, $qualifying_amount_max, $discount_type,
+    $discount_amount, $requires_code, $filter_type, $has_role_filter,
+    $requires_single_product_to_qualify, $max_times_applied, $can_be_combined_with_other_discounts, $max_uses,
+    $max_uses_per_user, $max_uses_per_code, $has_expiration, $expiration,
+    $is_published, $weight, $discount_id
+  );
 }
 
 /**
  * Deletes a uc_discounts row and all dependencies.
  */
-function uc_discounts_delete_all($discount_id)
-{
-	db_query("DELETE FROM {uc_discounts_uses} WHERE discount_id=%d", $discount_id);
-	db_query("DELETE FROM {uc_discounts_products} WHERE discount_id=%d", $discount_id);
-	db_query("DELETE FROM {uc_discounts_terms} WHERE discount_id=%d", $discount_id);
-	db_query("DELETE FROM {uc_discounts_skus} WHERE discount_id=%d", $discount_id);
-	db_query("DELETE FROM {uc_discounts_roles} WHERE discount_id=%d", $discount_id);
-	db_query("DELETE FROM {uc_discounts_codes} WHERE discount_id=%d", $discount_id);
-	db_query("DELETE FROM {uc_discounts} WHERE discount_id=%d", $discount_id);
+function uc_discounts_delete_all($discount_id) {
+  db_query("DELETE FROM {uc_discounts_uses} WHERE discount_id=%d", $discount_id);
+  db_query("DELETE FROM {uc_discounts_products} WHERE discount_id=%d", $discount_id);
+  db_query("DELETE FROM {uc_discounts_terms} WHERE discount_id=%d", $discount_id);
+  db_query("DELETE FROM {uc_discounts_skus} WHERE discount_id=%d", $discount_id);
+  db_query("DELETE FROM {uc_discounts_roles} WHERE discount_id=%d", $discount_id);
+  db_query("DELETE FROM {uc_discounts_codes} WHERE discount_id=%d", $discount_id);
+  db_query("DELETE FROM {uc_discounts} WHERE discount_id=%d", $discount_id);
 }
 
 /**
  * Returns codes for discount.
  */
-function get_codes_for_discount($discount_id)
-{
-	$codes = array();
-
-	//Get codes from database
-	$result = db_query("SELECT code FROM {uc_discounts_codes} WHERE discount_id=%d", $discount_id);
-	while ( $row = db_fetch_array($result) )
-		$codes[] = $row["code"];
-	return $codes;
+function get_codes_for_discount($discount_id) {
+  $codes = array();
+
+  //Get codes from database
+  $result = db_query("SELECT code FROM {uc_discounts_codes} WHERE discount_id=%d", $discount_id);
+  while ($row = db_fetch_array($result)) $codes[] = $row["code"];
+  return $codes;
 }
 
 /**
  * Inserts a uc_discounts_codes row and returns its discount_code_id.
  */
-function uc_discounts_codes_insert($discount_id, $code)
-{
-	$query = "INSERT INTO {uc_discounts_codes}(discount_id, code) VALUES(%d, '%s')";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id, $code);
-	return db_last_insert_id("uc_discounts_codes", "discount_code_id");
+function uc_discounts_codes_insert($discount_id, $code) {
+  $query = "INSERT INTO {uc_discounts_codes}(discount_id, code) VALUES(%d, '%s')";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id, $code);
+  return db_last_insert_id("uc_discounts_codes", "discount_code_id");
 }
 
 /**
  * Deletes all uc_discounts_codes rows for a discount.
  */
-function uc_discounts_codes_delete($discount_id)
-{
-	$query = "DELETE FROM {uc_discounts_codes} WHERE discount_id=%d";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id);
+function uc_discounts_codes_delete($discount_id) {
+  $query = "DELETE FROM {uc_discounts_codes} WHERE discount_id=%d";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id);
 }
 
 /**
  * Returns product_ids for discount object.
  * Note: this function correctly returns all products for term-based discounts.
  */
-function get_product_ids_for_discount_object($discount, $exclude_all_products = FALSE)
-{
-	switch ($discount->filter_type)
-	{
-		case FILTER_TYPE_PRODUCTS:
-			return get_product_ids_for_discount($discount->discount_id, $exclude_all_products);
+function get_product_ids_for_discount_object($discount, $exclude_all_products = FALSE) {
+  switch ($discount->filter_type) {
+    case FILTER_TYPE_PRODUCTS:
+      return get_product_ids_for_discount($discount->discount_id, $exclude_all_products);
 
-		case FILTER_TYPE_TERMS:
-			$product_ids = array();
+    case FILTER_TYPE_TERMS:
+      $product_ids = array();
 
-			//Get products for terms
-			$query = "SELECT DISTINCT p.nid FROM {uc_products} p
+      //Get products for terms
+      $query = "SELECT DISTINCT p.nid FROM {uc_products} p
 				INNER JOIN {term_node} tn ON p.nid=tn.nid
 				INNER JOIN {uc_discounts_terms} dt ON tn.tid=dt.term_id
 				WHERE dt.discount_id=%d";
-			uc_discounts_log($query);
-			$result = db_query($query, $discount->discount_id);
-			while ( $row = db_fetch_array($result) )
-				$product_ids[] = $row["nid"];
-			return $product_ids;
+      uc_discounts_log($query);
+      $result = db_query($query, $discount->discount_id);
+      while ($row = db_fetch_array($result)) $product_ids[] = $row["nid"];
+      return $product_ids;
 
-		case FILTER_TYPE_SKUS:
-			$query = "SELECT DISTINCT p.nid FROM {uc_products} p
+    case FILTER_TYPE_SKUS:
+      $query = "SELECT DISTINCT p.nid FROM {uc_products} p
 				INNER JOIN {uc_discounts_skus} ds ON p.model=ds.sku
 				WHERE ds.discount_id=%d";
-			uc_discounts_log($query);
-			$result = db_query($query, $discount->discount_id);
-			while ( $row = db_fetch_array($result) )
-				$product_ids[] = $row["nid"];
-			return $product_ids;
-	}
-	return array();
+      uc_discounts_log($query);
+      $result = db_query($query, $discount->discount_id);
+      while ($row = db_fetch_array($result)) $product_ids[] = $row["nid"];
+      return $product_ids;
+  }
+  return array();
 }
 
 /**
  * Returns product_ids for discount.
- * Note: this function does not check filter_type so a discount with filter_type other than 
+ * Note: this function does not check filter_type so a discount with filter_type other than
  *	  FILTER_TYPE_PRODUCTS will return no values.
  */
-function get_product_ids_for_discount($discount_id, $exclude_all_products = FALSE)
-{
-	$product_ids = array();
-
-	//Get products from database
-	if ($exclude_all_products)
-	{
-		$result = db_query("SELECT product_id FROM {uc_discounts_products} WHERE discount_id=%d AND product_id<>%d", 
-			$discount_id, ALL_PRODUCTS);
-	}
-	else
-		$result = db_query("SELECT product_id FROM {uc_discounts_products} WHERE discount_id=%d", $discount_id);
-
-	while ( $row = db_fetch_array($result) )
-		$product_ids[] = $row["product_id"];
-	return $product_ids;
+function get_product_ids_for_discount($discount_id, $exclude_all_products = FALSE) {
+  $product_ids = array();
+
+  //Get products from database
+  if ($exclude_all_products) {
+    $result = db_query("SELECT product_id FROM {uc_discounts_products} WHERE discount_id=%d AND product_id<>%d",
+      $discount_id, ALL_PRODUCTS
+    );
+  }
+  else $result = db_query("SELECT product_id FROM {uc_discounts_products} WHERE discount_id=%d", $discount_id);
+
+  while ($row = db_fetch_array($result)) $product_ids[] = $row["product_id"];
+  return $product_ids;
 }
 
 /**
  * Inserts a uc_discounts_products row and returns its discount_product_id.
  */
-function uc_discounts_products_insert($discount_id, $product_id)
-{
-	$query = "INSERT INTO {uc_discounts_products}(discount_id, product_id) VALUES(%d, %d)";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id, $product_id);
-	return db_last_insert_id("uc_discounts_products", "discount_product_id");
+function uc_discounts_products_insert($discount_id, $product_id) {
+  $query = "INSERT INTO {uc_discounts_products}(discount_id, product_id) VALUES(%d, %d)";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id, $product_id);
+  return db_last_insert_id("uc_discounts_products", "discount_product_id");
 }
 
 /**
  * Deletes all uc_discounts_products rows for a discount.
  */
-function uc_discounts_products_delete($discount_id)
-{
-	$query = "DELETE FROM {uc_discounts_products} WHERE discount_id=%d";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id);
+function uc_discounts_products_delete($discount_id) {
+  $query = "DELETE FROM {uc_discounts_products} WHERE discount_id=%d";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id);
 }
 
 /**
  * Returns term_ids for discount.
  */
-function get_term_ids_for_discount($discount_id, $exclude_all_terms = FALSE)
-{
-	$term_ids = array();
-
-	//Get terms from database
-	if ($exclude_all_terms)
-	{
-		$result = db_query("SELECT term_id FROM {uc_discounts_terms} WHERE discount_id=%d AND term_id<>%d", 
-			$discount_id, ALL_TERMS);
-	}
-	else
-		$result = db_query("SELECT term_id FROM {uc_discounts_terms} WHERE discount_id=%d", $discount_id);
-
-	while ( $row = db_fetch_array($result) )
-		$term_ids[] = $row["term_id"];
-	return $term_ids;
+function get_term_ids_for_discount($discount_id, $exclude_all_terms = FALSE) {
+  $term_ids = array();
+
+  //Get terms from database
+  if ($exclude_all_terms) {
+    $result = db_query("SELECT term_id FROM {uc_discounts_terms} WHERE discount_id=%d AND term_id<>%d",
+      $discount_id, ALL_TERMS
+    );
+  }
+  else $result = db_query("SELECT term_id FROM {uc_discounts_terms} WHERE discount_id=%d", $discount_id);
+
+  while ($row = db_fetch_array($result)) $term_ids[] = $row["term_id"];
+  return $term_ids;
 }
 
 /**
  * Returns SKUs for discount.
  */
-function get_skus_for_discount($discount_id, $exclude_all_skus = FALSE)
-{
-	$skus = array();
-
-	//Get SKUs from database
-	if ($exclude_all_skus)
-	{
-		$result = db_query("SELECT sku FROM {uc_discounts_skus} WHERE discount_id=%d AND sku<>%d", 
-			$discount_id, ALL_SKUS);
-	}
-	else
-		$result = db_query("SELECT sku FROM {uc_discounts_skus} WHERE discount_id=%d", $discount_id);
-
-	while ( $row = db_fetch_array($result) )
-		$skus[] = $row["sku"];
-	return $skus;
+function get_skus_for_discount($discount_id, $exclude_all_skus = FALSE) {
+  $skus = array();
+
+  //Get SKUs from database
+  if ($exclude_all_skus) {
+    $result = db_query("SELECT sku FROM {uc_discounts_skus} WHERE discount_id=%d AND sku<>%d",
+      $discount_id, ALL_SKUS
+    );
+  }
+  else $result = db_query("SELECT sku FROM {uc_discounts_skus} WHERE discount_id=%d", $discount_id);
+
+  while ($row = db_fetch_array($result)) $skus[] = $row["sku"];
+  return $skus;
 }
 
 /**
  * Returns role_ids for discount.
  */
-function get_role_ids_for_discount($discount_id, $exclude_all_roles = FALSE)
-{
-	$role_ids = array();
-
-	//Get roles from database
-	if ($exclude_all_roles)
-	{
-		$result = db_query("SELECT role_id FROM {uc_discounts_roles} WHERE discount_id=%d AND role_id<>%d", 
-			$discount_id, ALL_ROLES);
-	}
-	else
-		$result = db_query("SELECT role_id FROM {uc_discounts_roles} WHERE discount_id=%d", $discount_id);
-
-	while ( $row = db_fetch_array($result) )
-		$role_ids[] = $row["role_id"];
-	return $role_ids;
+function get_role_ids_for_discount($discount_id, $exclude_all_roles = FALSE) {
+  $role_ids = array();
+
+  //Get roles from database
+  if ($exclude_all_roles) {
+    $result = db_query("SELECT role_id FROM {uc_discounts_roles} WHERE discount_id=%d AND role_id<>%d",
+      $discount_id, ALL_ROLES
+    );
+  }
+  else $result = db_query("SELECT role_id FROM {uc_discounts_roles} WHERE discount_id=%d", $discount_id);
+
+  while ($row = db_fetch_array($result)) $role_ids[] = $row["role_id"];
+  return $role_ids;
 }
 
 /**
  * Inserts a uc_discounts_terms row and returns its discount_term_id.
  */
-function uc_discounts_terms_insert($discount_id, $term_id)
-{
-	$query = "INSERT INTO {uc_discounts_terms}(discount_id, term_id) VALUES(%d, %d)";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id, $term_id);
-	return db_last_insert_id("uc_discounts_terms", "discount_term_id");
+function uc_discounts_terms_insert($discount_id, $term_id) {
+  $query = "INSERT INTO {uc_discounts_terms}(discount_id, term_id) VALUES(%d, %d)";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id, $term_id);
+  return db_last_insert_id("uc_discounts_terms", "discount_term_id");
 }
 
 /**
  * Deletes all uc_discounts_terms rows for a discount.
  */
-function uc_discounts_terms_delete($discount_id)
-{
-	$query = "DELETE FROM {uc_discounts_terms} WHERE discount_id=%d";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id);
+function uc_discounts_terms_delete($discount_id) {
+  $query = "DELETE FROM {uc_discounts_terms} WHERE discount_id=%d";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id);
 }
 
 /**
  * Inserts a uc_discounts_skus row and returns its discount_sku_id.
  */
-function uc_discounts_skus_insert($discount_id, $sku)
-{
-	$query = "INSERT INTO {uc_discounts_skus}(discount_id, sku) VALUES(%d, '%s')";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id, $sku);
-	return db_last_insert_id("uc_discounts_skus", "discount_sku_id");
+function uc_discounts_skus_insert($discount_id, $sku) {
+  $query = "INSERT INTO {uc_discounts_skus}(discount_id, sku) VALUES(%d, '%s')";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id, $sku);
+  return db_last_insert_id("uc_discounts_skus", "discount_sku_id");
 }
 
 /**
  * Deletes all uc_discounts_skus rows for a discount.
  */
-function uc_discounts_skus_delete($discount_id)
-{
-	$query = "DELETE FROM {uc_discounts_skus} WHERE discount_id=%d";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id);
+function uc_discounts_skus_delete($discount_id) {
+  $query = "DELETE FROM {uc_discounts_skus} WHERE discount_id=%d";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id);
 }
 
 /**
  * Inserts a uc_discounts_roles row and returns its discount_role_id.
  */
-function uc_discounts_roles_insert($discount_id, $role_id)
-{
-	$query = "INSERT INTO {uc_discounts_roles}(discount_id, role_id) VALUES(%d, %d)";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id, $role_id);
-	return db_last_insert_id("uc_discounts_roles", "discount_role_id");
+function uc_discounts_roles_insert($discount_id, $role_id) {
+  $query = "INSERT INTO {uc_discounts_roles}(discount_id, role_id) VALUES(%d, %d)";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id, $role_id);
+  return db_last_insert_id("uc_discounts_roles", "discount_role_id");
 }
 
 /**
  * Deletes all uc_discounts_roles rows for a discount.
  */
-function uc_discounts_roles_delete($discount_id)
-{
-	$query = "DELETE FROM {uc_discounts_roles} WHERE discount_id=%d";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id);
+function uc_discounts_roles_delete($discount_id) {
+  $query = "DELETE FROM {uc_discounts_roles} WHERE discount_id=%d";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id);
 }
 
 /**
@@ -957,100 +901,95 @@ function uc_discounts_roles_delete($disc
  * @param $errors Reference to array to add error messages to
  * @param $messages Reference to array to add success messages to
  */
-function get_discounts_for_order($order, &$errors = NULL, &$warnings = NULL, &$messages = NULL)
-{
-	$order_product_id_subtotal_map = array();
-	$order_product_id_quantity_map = array();
-	$order_product_ids = array();
-	$order_product_ids_set = array();
-	$order_product_id_product_array_map = array();
-	$order_subtotal = 0;
-
-	//Create IN string of product node IDs in order
-	if ( is_array($order->products) && !empty($order->products) )
-	{
-		foreach ($order->products as $product)
-		{
-			$nid = $product->nid;
-
-			$order_product_ids_set[$nid] = TRUE;
-
-			uc_discounts_add_to_existing_map_number_value($order_product_id_subtotal_map, 
-				$nid, $product->price * $product->qty);
-			uc_discounts_add_to_existing_map_number_value($order_product_id_quantity_map, $nid, $product->qty);
-			
-			$a = $order_product_id_product_array_map[$nid];
-			if ( !is_array($a) )
-				$a = array();
-			$a[] = $product;
-			$order_product_id_product_array_map[$nid] = $a;
-
-			$order_subtotal += $product->price * $product->qty;
-		}
-	}
-
-	$order_product_ids = array_keys($order_product_ids_set);
-
-	$temp_product_ids = $order_product_ids;
-	$temp_product_ids[] = ALL_PRODUCTS;
-	$product_ids_clause = sprintf( "d.filter_type<>%d OR dp.product_id IN(%s)", 
-		FILTER_TYPE_PRODUCTS, join(",", $temp_product_ids) );
-
- 	//Create IN string of term TIDs in order
-	$temp_term_ids = array();
-	$temp_term_ids[] = ALL_TERMS;
-	if ( is_array($order->products) && !empty($order->products) )
-	{
-		//Get terms for order's products
-		$result = db_query( "SELECT DISTINCT tid FROM {term_node} WHERE nid IN(%s)", join(",", $order_product_ids) );
-		while ( $row = db_fetch_array($result) )
-		{
-			$temp_term_ids[] = $row["tid"];
-			$order_term_ids[] = $row["tid"];
-		}
-	}
-	$term_ids_clause = sprintf( "d.filter_type<>%d OR dt.term_id IN(%s)", 
-		FILTER_TYPE_TERMS, join(",", $temp_term_ids) );
-
- 	//Create IN string of SKUs in order
-	$temp_skus = array();
-	$temp_skus[] = "'" . db_escape_string(ALL_SKUS) . "'";
-	if ( is_array($order->products) && !empty($order->products) )
-	{
-		//Get SKUs for order's products
-		$result = db_query( "SELECT DISTINCT model FROM {uc_products} WHERE nid IN(%s)", join(",", $order_product_ids) );
-		while ( $row = db_fetch_array($result) )
-			$temp_skus[] = "'" . db_escape_string($row["model"]) . "'";;
-	}
-	$skus_clause = sprintf( "d.filter_type<>%d OR ds.sku IN(%s)", 
-		FILTER_TYPE_SKUS, join(",", $temp_skus) );
-
-	//Create codes clause
-	$escaped_codes_string = NULL;
-	if ( !empty($order->uc_discounts_codes) )
-	{
-		//Create IN string of product node IDs in order
-		$escaped_codes = array();
-		foreach ($order->uc_discounts_codes as $code)
-			$escaped_codes[] = "'" . db_escape_string($code) . "'";
-		$escaped_codes_string = join(",", $escaped_codes);
-
-		$codes_clause = sprintf(" OR d.discount_id IN( SELECT discount_id FROM {uc_discounts_codes} WHERE code IN(%s) )", 
-			$escaped_codes_string);
-	}
-	else
-		$codes_clause = "";
-
-	//Create roles clause
-	$auth_rid = ($order->uid != 0) ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
-	$roles_clause = sprintf(" OR d.discount_id IN(SELECT dr.discount_id FROM {uc_discounts_roles} dr"
-		. ", {users_roles} ur WHERE (dr.role_id=ur.rid AND ur.uid=%d) OR dr.role_id=%d OR dr.role_id=%d)", 
-		$order->uid, ALL_ROLES, $auth_rid);
-
-	//Add warnings for expired discounts with codes (if necessary)
-	if ( !empty($order->uc_discounts_codes) )
-	{
-		$query = sprintf( "SELECT DISTINCT d.*, dc.code code FROM {uc_discounts} d
+function get_discounts_for_order($order, &$errors = NULL, &$warnings = NULL, &$messages = NULL) {
+  $order_product_id_subtotal_map = array();
+  $order_product_id_quantity_map = array();
+  $order_product_ids = array();
+  $order_product_ids_set = array();
+  $order_product_id_product_array_map = array();
+  $order_subtotal = 0;
+
+  //Create IN string of product node IDs in order
+  if (is_array($order->products) && !empty($order->products)) {
+    foreach ($order->products as $product) {
+      $nid = $product->nid;
+
+      $order_product_ids_set[$nid] = TRUE;
+
+      uc_discounts_add_to_existing_map_number_value($order_product_id_subtotal_map,
+        $nid, $product->price * $product->qty
+      );
+      uc_discounts_add_to_existing_map_number_value($order_product_id_quantity_map, $nid, $product->qty);
+
+      $a = $order_product_id_product_array_map[$nid];
+      if (!is_array($a)) {
+        $a = array();
+      }
+      $a[] = $product;
+      $order_product_id_product_array_map[$nid] = $a;
+
+      $order_subtotal += $product->price * $product->qty;
+    }
+  }
+
+  $order_product_ids = array_keys($order_product_ids_set);
+
+  $temp_product_ids   = $order_product_ids;
+  $temp_product_ids[] = ALL_PRODUCTS;
+  $product_ids_clause = sprintf("d.filter_type<>%d OR dp.product_id IN(%s)",
+    FILTER_TYPE_PRODUCTS, join(",", $temp_product_ids)
+  );
+
+  //Create IN string of term TIDs in order
+  $temp_term_ids = array();
+  $temp_term_ids[] = ALL_TERMS;
+  if (is_array($order->products) && !empty($order->products)) {
+    //Get terms for order's products
+    $result = db_query("SELECT DISTINCT tid FROM {term_node} WHERE nid IN(%s)", join(",", $order_product_ids));
+    while ($row = db_fetch_array($result)) {
+      $temp_term_ids[] = $row["tid"];
+      $order_term_ids[] = $row["tid"];
+    }
+  }
+  $term_ids_clause = sprintf("d.filter_type<>%d OR dt.term_id IN(%s)",
+    FILTER_TYPE_TERMS, join(",", $temp_term_ids)
+  );
+
+  //Create IN string of SKUs in order
+  $temp_skus = array();
+  $temp_skus[] = "'". db_escape_string(ALL_SKUS) ."'";
+  if (is_array($order->products) && !empty($order->products)) {
+    //Get SKUs for order's products
+    $result = db_query("SELECT DISTINCT model FROM {uc_products} WHERE nid IN(%s)", join(",", $order_product_ids));
+    while ($row = db_fetch_array($result)) $temp_skus[] = "'". db_escape_string($row["model"]) ."'";;
+  }
+  $skus_clause = sprintf("d.filter_type<>%d OR ds.sku IN(%s)",
+    FILTER_TYPE_SKUS, join(",", $temp_skus)
+  );
+
+  //Create codes clause
+  $escaped_codes_string = NULL;
+  if (!empty($order->uc_discounts_codes)) {
+    //Create IN string of product node IDs in order
+    $escaped_codes = array();
+    foreach ($order->uc_discounts_codes as $code) $escaped_codes[] = "'". db_escape_string($code) ."'";
+    $escaped_codes_string = join(",", $escaped_codes);
+
+    $codes_clause = sprintf(" OR d.discount_id IN( SELECT discount_id FROM {uc_discounts_codes} WHERE code IN(%s) )",
+      $escaped_codes_string
+    );
+  }
+  else $codes_clause = "";
+
+  //Create roles clause
+  $auth_rid = ($order->uid != 0) ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
+  $roles_clause = sprintf(" OR d.discount_id IN(SELECT dr.discount_id FROM {uc_discounts_roles} dr" . ", {users_roles} ur WHERE (dr.role_id=ur.rid AND ur.uid=%d) OR dr.role_id=%d OR dr.role_id=%d)",
+    $order->uid, ALL_ROLES, $auth_rid
+  );
+
+  //Add warnings for expired discounts with codes (if necessary)
+  if (!empty($order->uc_discounts_codes)) {
+    $query = sprintf("SELECT DISTINCT d.*, dc.code code FROM {uc_discounts} d
 			LEFT JOIN {uc_discounts_products} dp ON d.discount_id=dp.discount_id
 			LEFT JOIN {uc_discounts_terms} dt ON d.discount_id=dt.discount_id
 			LEFT JOIN {uc_discounts_skus} ds ON d.discount_id=ds.discount_id
@@ -1062,18 +1001,19 @@ function get_discounts_for_order($order,
 			AND (%s)
 			AND (%s)
 			AND (d.has_expiration<>0 AND d.expiration<=%d)
-			ORDER BY weight", $escaped_codes_string, $roles_clause, $product_ids_clause, 
-				$term_ids_clause, $skus_clause, time() );
-		uc_discounts_log("query=" . $query);
-		$result = db_query($query);
-		while ( $discount = db_fetch_object($result) )
-		{
-			$warnings[] = t( 'The discount for code "@code" has expired.', 
-				array("@code" => $discount->code) );
-		}
-	}
+			ORDER BY weight", $escaped_codes_string, $roles_clause, $product_ids_clause,
+      $term_ids_clause, $skus_clause, time()
+    );
+    uc_discounts_log("query=". $query);
+    $result = db_query($query);
+    while ($discount = db_fetch_object($result)) {
+      $warnings[] = t('The discount for code "@code" has expired.',
+        array("@code" => $discount->code)
+      );
+    }
+  }
 
-	$query = sprintf( "SELECT DISTINCT d.* FROM {uc_discounts} d
+  $query = sprintf("SELECT DISTINCT d.* FROM {uc_discounts} d
 		LEFT JOIN {uc_discounts_products} dp ON d.discount_id=dp.discount_id
 		LEFT JOIN {uc_discounts_terms} dt ON d.discount_id=dt.discount_id
 		LEFT JOIN {uc_discounts_skus} ds ON d.discount_id=ds.discount_id
@@ -1082,517 +1022,493 @@ function get_discounts_for_order($order,
 		AND (%s)
 		AND (%s)
 		AND (d.has_expiration=0 OR d.expiration>%d)
-		ORDER BY weight", $codes_clause, $roles_clause, $product_ids_clause, 
-			$term_ids_clause, $skus_clause, time() );
-	uc_discounts_log("query=" . $query);
-	$result = db_query($query);
-
-	$total_discount_amount = 0;
-	$discounts = array();
-	while ( $discount = db_fetch_object($result) )
-	{
-		//Get code for discount (if one exists)
-		$discount->code = NULL;
-		if ( !empty($escaped_codes_string) )
-		{
-			$query = sprintf("SELECT code FROM {uc_discounts_codes} WHERE code IN(%s) AND discount_id=%d",
-				$escaped_codes_string, $discount->discount_id);
-			$row = db_fetch_array( db_query($query) );
-			if ( !empty($row) )
-				$discount->code = $row["code"];
-		}
-
-		//The query handled valid codes and expiration, this block must:
-		//	check max uses (if applicable)
-		//	check if discount is being combined and can be combined
-		//	check if order qualifies (type, requires_single_product_to_qualify, can_be_combined_with_other_discounts)
-		//	determine number of times to apply discount
-
-		//If this discount has a max uses amount, check max uses
-		if ($discount->max_uses > 0)
-		{
-			$row = db_fetch_array( db_query("SELECT COUNT(*) as uses_count FROM {uc_discounts_uses} WHERE discount_id=%d", 
-				$discount->discount_id) );
-			if ($row["uses_count"] >= $discount->max_uses)
-			{
-				//If this is a coded discount, add error message
-				if ( !is_null($warnings) && !is_null($discount->code) )
-				{
-					$warnings[] = t( 'The discount for code "@code" has reached its max number of uses.', 
-						array("@code" => $discount->code) );
-				}
-				continue;
-			}
-			
-			$discount->uses_count = $row["uses_count"];
-		}
-
-		//If this discount has a max uses per user amount, check max uses per user
-		if ($discount->max_uses_per_user > 0)
-		{
-			$row = db_fetch_array( db_query("SELECT COUNT(*) as user_uses_count FROM {uc_discounts_uses} WHERE discount_id=%d AND user_id=%d", 
-				$discount->discount_id, $order->uid) );
-			if ($row["user_uses_count"] >= $discount->max_uses_per_user)
-			{
-				//If this is a coded discount, add warning message
-				if ( !is_null($warnings) && !is_null($discount->code) )
-				{
-					$warnings[] = t( 'The discount for code "@code" has reached its max number of uses.', 
-						array("@code" => $discount->code) );
-				}
-				continue;
-			}
-			
-			$discount->user_uses_count = $row["user_uses_count"];
-		}
-
-		//If code exists and this discount has a max uses per code amount, check max uses per user
-		if ( !is_null($discount->code) && ($discount->max_uses_per_code > 0) )
-		{
-			$row = db_fetch_array( db_query("SELECT COUNT(*) as code_uses_count FROM {uc_discounts_uses} WHERE discount_id=%d AND code='%s'", 
-				$discount->discount_id, $discount->code) );
-			if ($row["code_uses_count"] >= $discount->max_uses_per_code)
-			{
-				//Add warning message
-				if ( !is_null($warnings) )
-				{
-					$warnings[] = t( 'The discount code "@code" has reached its max number of uses.', 
-						array("@code" => $discount->code) );
-				}
-				continue;
-			}
-			
-			$discount->code_uses_count = $row["code_uses_count"];
-		}
-
-		//If there are applied discounts, check if discount is being combined and can be combined
-		if (count($discounts) > 0)
-		{
-			if (!$discount->can_be_combined_with_other_discounts) 
-			{
-				//If this is a coded discount, add error message
-				if ( !is_null($warnings) && !is_null($discount->code) )
-				{
-					$warnings[] = t( 'The discount for code "@code" cannot be combined with other discounts.', 
-						array("@code" => $discount->code) );
-				}
-				continue;
-			}
-
-			if (!$discounts[0]->can_be_combined_with_other_discounts) 
-			{
-				//If first discount was a coded discount, add error message (only print warning if both 
-				//discounts have codes)
-				if ( !is_null($warnings) && !empty($discounts[0]->code) && !is_null($discount->code) )
-				{
-					$warnings[] = t( 'The discount for code "@code" cannot be combined with other discounts.', 
-						array("@code" => $discounts[0]->code) );
-				}
-				continue;
-			}
-		}
-
-
-		//Check if order qualifies for this discount (check type and requires_single_product_to_qualify)
-
-		//Get product IDs for discount
-		$discount_product_ids = get_product_ids_for_discount_object($discount);
-		if ( in_array(ALL_PRODUCTS, $discount_product_ids) )
-			$discount_product_ids = $order_product_ids;
-
-
-		//Determine total qualifying amount of order (store in order_qualifying_amount)
-		//and qualifying subtotal of order (store in order_qualifying_subtotal)
-
-		$order_qualifying_amount = 0;
-		$order_qualifying_subtotal = 0;
-
-		//If discount requires a single product
-		if ($discount->requires_single_product_to_qualify)
-		{
-			switch ($discount->qualifying_type)
-			{
-				case QUALIFYING_TYPE_MINIMUM_PRICE:
-					//Determine the maximum product subtotal
-					foreach ($discount_product_ids as $product_id)
-					{
-						if ( isset($order_product_id_subtotal_map[$product_id]) )
-						{
-							$order_qualifying_amount = 
-								max($order_qualifying_amount, $order_product_id_subtotal_map[$product_id]);
-						}
-					}
-
-					//Subtract already discounted amount
-					$order_qualifying_amount -= $total_discount_amount;
-//TO DO: keep track of each item's subtotal and decrement upon applying discount
-					break;
-
-				case QUALIFYING_TYPE_MINIMUM_QUANTITY:
-					//Determine the maximum product quantity
-					foreach ($discount_product_ids as $product_id)
-					{
-						if ( isset($order_product_id_quantity_map[$product_id]) )
-						{
-							$order_qualifying_amount = 
-								max($order_qualifying_amount, $order_product_id_quantity_map[$product_id]);
-						}
-					}
-//TO DO: keep track of each item's quantity and decrement upon applying discount
-					break;
-			}
-		}
-		//Otherwise sum product subtotals or quantities
-		else
-		{
-			switch ($discount->qualifying_type)
-			{
-				case QUALIFYING_TYPE_MINIMUM_PRICE:
-					//Determine the total subtotal of discount's products
-					foreach ($discount_product_ids as $product_id)
-					{
-						if ( isset($order_product_id_subtotal_map[$product_id]) )
-							$order_qualifying_amount += $order_product_id_subtotal_map[$product_id];
-					}
-
-					//Subtract already discounted amount
-					$order_qualifying_amount -= $total_discount_amount;
-					break;
-
-				case QUALIFYING_TYPE_MINIMUM_QUANTITY:
-					//Determine the total quantity of discount's products
-					foreach ($discount_product_ids as $product_id)
-					{
-						if ( isset($order_product_id_quantity_map[$product_id]) )
-							$order_qualifying_amount += $order_product_id_quantity_map[$product_id];
-					}
-//TO DO: keep track of each item's subtotal and decrement upon applying discount
-					break;
-			}
-		}
-
-		//If order does not qualify for this discount
-		if ($order_qualifying_amount < $discount->qualifying_amount)
-		{
-			//If this is a coded discount, add warning message
-			if ( !is_null($warnings) && !is_null($discount->code) )
-			{
-				switch ($discount->qualifying_type)
-				{
-					case QUALIFYING_TYPE_MINIMUM_PRICE:
-						$qualifying_amount = uc_currency_format($discount->qualifying_amount);
-						$warnings[] = t( 'The discount for code "@code" requires a minimum price of @qualifying_amount to qualify.', 
-							array("@code" => $discount->code, "@qualifying_amount" => $qualifying_amount) );
-						break;
-					case QUALIFYING_TYPE_MINIMUM_QUANTITY:
-						$warnings[] = t( 'The discount for code "@code" requires a minimum quantity of @qualifying_amount to qualify.', 
-							array("@code" => $discount->code, "@qualifying_amount" => $discount->qualifying_amount) );
-						break;
-				}
-			}
-			continue;
-		}
-
-		//If this discount has a maximum qualifying amount and the order exceeds it
-		if ( $discount->has_qualifying_amount_max && ($order_qualifying_amount > $discount->qualifying_amount_max) )
-		{
-			//If this is a coded discount, add error message
-			if ( !is_null($warnings) && !is_null($discount->code) )
-			{
-				$qualifying_amount_max = uc_currency_format($discount->qualifying_amount_max);
-				switch ($discount->qualifying_type)
-				{
-					case QUALIFYING_TYPE_MINIMUM_PRICE:
-						$warnings[] = t( 'The discount for code "@code" cannot exceed the price of @qualifying_amount_max to qualify.',
-							array("@code" => $discount->code, "@qualifying_amount_max" => $qualifying_amount_max) );
-						break;
-
-					case QUALIFYING_TYPE_MINIMUM_QUANTITY:
-						$warnings[] = t( 'The discount for code "@code" cannot exceed the quantity of @qualifying_amount_max to qualify.',
-							array("@code" => $discount->code, "@qualifying_amount_max" => $discount->qualifying_amount_max) );
-						break;
-				}
-			}
-			continue;
-		}
-
-		//Determine number of times to apply discount
-		if ($discount->qualifying_amount != 0)
-			$discount->times_applied = (int)($order_qualifying_amount / $discount->qualifying_amount);
-		else
-			$discount->times_applied = 1;
-		if ($discount->max_times_applied != 0)
-			$discount->times_applied = min($discount->times_applied, $discount->max_times_applied);
-
-		//Get product IDs in order that are in discount
-		$order_and_discount_product_ids = array_intersect($discount_product_ids, $order_product_ids);
-
-		//Create array of product objects related to this discount
-		$order_and_discount_products = array();
-		foreach ($order_and_discount_product_ids as $product_id)
-		{
-			if ( array_key_exists($product_id, $order_product_id_product_array_map) )
-			{
-				$order_and_discount_products = 
-					array_merge($order_and_discount_products, 
-						$order_product_id_product_array_map[$product_id]);
-			}
-		}
-
-		//Calculate discount amount
-		switch ($discount->discount_type)
-		{
-			case DISCOUNT_TYPE_FREE_ITEMS:
-				//The variable discount_amount is the monitary amount of discount
-				$discount_amount = 0;
-
-				//The variable free_items_remaining is the [max] number of free items for the order
-				$free_items_remaining = $discount->discount_amount * $discount->times_applied;
-
-				//Loop until all free items have been applied or there are no more products to 
-				//discount (discount cheapest first)
-				while ($free_items_remaining > 0)
-				{
-					//Determine cheapest remaining qualifying item
-					$cheapest_product = NULL;
-					foreach ($order_and_discount_products as $product)
-					{
-						//If this product has been fully discounted, continue
-						if ($product->uc_discounts_is_fully_discounted)
-							continue;
-
-						//If no current cheapest product exists, use this product						
-						if ( is_null($cheapest_product) )
-							$cheapest_product = $product;
-						else
-						{
-							//If this product is cheaper than the current cheapest product, 
-							//use this product instead
-							if ($product->price < $cheapest_product->price)
-								$cheapest_product = $product;
-						}
-					}
-					
-					//If no cheapest product could be found, there are no more products to 
-					//discount, break
-					if ( is_null($cheapest_product) )
-						break;
-
-					//Discount up to the lesser of cheapest product quantity and free_items_remaining
-					$discount_count = min($cheapest_product->qty, $free_items_remaining);
-
-					//Add current discount amount to running total
-					$discount_amount += $discount_count * $cheapest_product->price;
-					
-					//Mark item fully discounted
-					$cheapest_product->uc_discounts_is_fully_discounted = TRUE;
-					
-					$free_items_remaining -= $discount_count;
-				}
-
-				$discount->amount = $discount_amount;
-				break;
-
-			case DISCOUNT_TYPE_PERCENTAGE_OFF:
-				//Always apply once
-				$discount->times_applied = 1;
-
-				//If this discount uses all products and previous discount is:
-				//	same weight as this discount
-				//	percentage off
-				//	products of discounts must match
-				//discount using same subtotal as last discount
-				if (count($discounts) > 0)
-				{
-					$last_discount = $discounts[count($discounts) - 1];
-					if ( ($last_discount->weight == $discount->weight) 
-						&& ($last_discount->discount_type == DISCOUNT_TYPE_PERCENTAGE_OFF) )
-					{
-						//Last discount's and this discount's products must match exactly
-						$are_equal = TRUE;
-						$last_discount_product_ids = get_product_ids_for_discount_object($last_discount);
-						$this_discount_product_ids = get_product_ids_for_discount_object($discount);
-						//If both contain "all products" they are equal
-						if ( in_array(ALL_PRODUCTS, $last_discount_product_ids) 
-							&& in_array(ALL_PRODUCTS, $this_discount_product_ids) )
-							$are_equal = TRUE;
-						//Otherwise check arrays for equality
-						else
-						{
-							foreach ($this_discount_product_ids as $product_id)
-							{
-								if ( !in_array($product_id, $last_discount_product_ids) )
-								{
-									$are_equal = FALSE;
-									break;
-								}
-							}
-							
-							if ($are_equal)
-							{
-								foreach ($last_discount_product_ids as $product_id)
-								{
-									if ( !in_array($product_id, $this_discount_product_ids) )
-									{
-										$are_equal = FALSE;
-										break;
-									}
-								}
-							}
-						}
-
-						if ($are_equal)
-						{
-							//($last_discount->amount / $last_discount->discount_amount) == last discount's subtotal
-							$local_order_subtotal = ($last_discount->amount / $last_discount->discount_amount);
-							$discount->amount = $local_order_subtotal * $discount->discount_amount;
-							break;
-						}
-					}
-				}
-
-//Start patch from lutegrass:
-//This fixes the problem where a percent discount does not apply to all products
-//(but doesn't fix the problem where the products being discounted have already been discounted
-//in full, or the case where the cart consists only of the products included in this discount)
-				// Get qualifying products -- ignore "all products" selection
-				$discount_product_ids = get_product_ids_for_discount_object($discount, TRUE);
-
-				// Do we have any products
-				if (count($discount_product_ids) > 0) {
-				  $discounted_products_amount = 0;
-				  foreach ($order_and_discount_products as $product)
-				  {
-					$discounted_products_amount += $product->price * $product->qty;
-				  }
-				  $discount->amount = $discounted_products_amount * $discount->discount_amount;
-				// Discount the subtotal so far
-				} else {
-				  $discount->amount = max($order_subtotal - $total_discount_amount, 0) * $discount->discount_amount;
-				}
-//End patch from lutegrass
-				break;
-
-			case DISCOUNT_TYPE_FIXED_AMOUNT_OFF:
-				$discount->amount = $discount->discount_amount * $discount->times_applied;
-				break;
-			
-			case DISCOUNT_TYPE_FIXED_AMOUNT_OFF_PER_QUALIFYING_ITEM:
-				//Discount is the total quantity of qualifying items in order (order_qualifying_amount)
-				//times the discount amount
-				$discount->amount = $discount->discount_amount * $order_qualifying_amount;
-				break;
-		}
-
-		if ( !is_null($messages) )
-		{
-			$options = array("@short_description" => $discount->short_description, 
-				"@code" => $discount->code, 
-				"@times_applied" => $discount->times_applied, 
-				"@discount_amount" => uc_currency_format($discount->amount),
-				"@time_string" => $time_string);
-			if ( !is_null($discount->code) )
-			{
-				if ($discount->times_applied == 1)
-					$messages[] = t("The discount, '@short_description', with code '@code' was applied for a discount of @discount_amount.", 
-						$options);
-				else
-					$messages[] = t("The discount, '@short_description', with code '@code' was applied @times_applied times for a discount of @discount_amount.", 
-						$options);
-			}
-			else
-			{
-				if ($discount->times_applied == 1)
-					$messages[] = t("The discount, '@short_description', was applied for a discount of @discount_amount.", 
-						$options);
-				else
-					$messages[] = t("The discount, '@short_description', was applied @times_applied times for a discount of @discount_amount.", 
-						$options);
-			}
-		}
-
-		//Round the discount to two places
-		$discount->amount = round($discount->amount, 2);
-
-		//Add this discount's amount to running total
-		$total_discount_amount += $discount->amount;
-
-		//Add this discount to list of discounts applied to order
-		$discounts[] = $discount;
-	}
-	return $discounts;
+		ORDER BY weight", $codes_clause, $roles_clause, $product_ids_clause,
+    $term_ids_clause, $skus_clause, time()
+  );
+  uc_discounts_log("query=". $query);
+  $result = db_query($query);
+
+  $total_discount_amount = 0;
+  $discounts = array();
+  while ($discount = db_fetch_object($result)) {
+    //Get code for discount (if one exists)
+    $discount->code = NULL;
+    if (!empty($escaped_codes_string)) {
+      $query = sprintf("SELECT code FROM {uc_discounts_codes} WHERE code IN(%s) AND discount_id=%d",
+        $escaped_codes_string, $discount->discount_id
+      );
+      $row = db_fetch_array(db_query($query));
+      if (!empty($row)) {
+        $discount->code = $row["code"];
+      }
+    }
+
+    //The query handled valid codes and expiration, this block must:
+    //	check max uses (if applicable)
+    //	check if discount is being combined and can be combined
+    //	check if order qualifies (type, requires_single_product_to_qualify, can_be_combined_with_other_discounts)
+    //	determine number of times to apply discount
+
+    //If this discount has a max uses amount, check max uses
+    if ($discount->max_uses > 0) {
+      $row = db_fetch_array(db_query("SELECT COUNT(*) as uses_count FROM {uc_discounts_uses} WHERE discount_id=%d",
+          $discount->discount_id
+        ));
+      if ($row["uses_count"] >= $discount->max_uses) {
+        //If this is a coded discount, add error message
+        if (!is_null($warnings) && !is_null($discount->code)) {
+          $warnings[] = t('The discount for code "@code" has reached its max number of uses.',
+            array("@code" => $discount->code)
+          );
+        }
+        continue;
+      }
+
+      $discount->uses_count = $row["uses_count"];
+    }
+
+    //If this discount has a max uses per user amount, check max uses per user
+    if ($discount->max_uses_per_user > 0) {
+      $row = db_fetch_array(db_query("SELECT COUNT(*) as user_uses_count FROM {uc_discounts_uses} WHERE discount_id=%d AND user_id=%d",
+          $discount->discount_id, $order->uid
+        ));
+      if ($row["user_uses_count"] >= $discount->max_uses_per_user) {
+        //If this is a coded discount, add warning message
+        if (!is_null($warnings) && !is_null($discount->code)) {
+          $warnings[] = t('The discount for code "@code" has reached its max number of uses.',
+            array("@code" => $discount->code)
+          );
+        }
+        continue;
+      }
+
+      $discount->user_uses_count = $row["user_uses_count"];
+    }
+
+    //If code exists and this discount has a max uses per code amount, check max uses per user
+    if (!is_null($discount->code) && ($discount->max_uses_per_code > 0)) {
+      $row = db_fetch_array(db_query("SELECT COUNT(*) as code_uses_count FROM {uc_discounts_uses} WHERE discount_id=%d AND code='%s'",
+          $discount->discount_id, $discount->code
+        ));
+      if ($row["code_uses_count"] >= $discount->max_uses_per_code) {
+        //Add warning message
+        if (!is_null($warnings)) {
+          $warnings[] = t('The discount code "@code" has reached its max number of uses.',
+            array("@code" => $discount->code)
+          );
+        }
+        continue;
+      }
+
+      $discount->code_uses_count = $row["code_uses_count"];
+    }
+
+    //If there are applied discounts, check if discount is being combined and can be combined
+    if (count($discounts) > 0) {
+      if (!$discount->can_be_combined_with_other_discounts) {
+        //If this is a coded discount, add error message
+        if (!is_null($warnings) && !is_null($discount->code)) {
+          $warnings[] = t('The discount for code "@code" cannot be combined with other discounts.',
+            array("@code" => $discount->code)
+          );
+        }
+        continue;
+      }
+
+      if (!$discounts[0]->can_be_combined_with_other_discounts) {
+        //If first discount was a coded discount, add error message (only print warning if both
+        //discounts have codes)
+        if (!is_null($warnings) && !empty($discounts[0]->code) && !is_null($discount->code)) {
+          $warnings[] = t('The discount for code "@code" cannot be combined with other discounts.',
+            array("@code" => $discounts[0]->code)
+          );
+        }
+        continue;
+      }
+    }
+
+
+    //Check if order qualifies for this discount (check type and requires_single_product_to_qualify)
+
+    //Get product IDs for discount
+    $discount_product_ids = get_product_ids_for_discount_object($discount);
+    if (in_array(ALL_PRODUCTS, $discount_product_ids)) {
+      $discount_product_ids = $order_product_ids;
+    }
+
+
+    //Determine total qualifying amount of order (store in order_qualifying_amount)
+    //and qualifying subtotal of order (store in order_qualifying_subtotal)
+
+    $order_qualifying_amount = 0;
+    $order_qualifying_subtotal = 0;
+
+    //If discount requires a single product
+    if ($discount->requires_single_product_to_qualify) {
+      switch ($discount->qualifying_type) {
+        case QUALIFYING_TYPE_MINIMUM_PRICE:
+          //Determine the maximum product subtotal
+          foreach ($discount_product_ids as $product_id) {
+            if (isset($order_product_id_subtotal_map[$product_id])) {
+              $order_qualifying_amount = max($order_qualifying_amount, $order_product_id_subtotal_map[$product_id]);
+            }
+          }
+
+          //Subtract already discounted amount
+          $order_qualifying_amount -= $total_discount_amount;
+          //TO DO: keep track of each item's subtotal and decrement upon applying discount
+          break;
+
+        case QUALIFYING_TYPE_MINIMUM_QUANTITY:
+          //Determine the maximum product quantity
+          foreach ($discount_product_ids as $product_id) {
+            if (isset($order_product_id_quantity_map[$product_id])) {
+              $order_qualifying_amount = max($order_qualifying_amount, $order_product_id_quantity_map[$product_id]);
+            }
+          }
+          //TO DO: keep track of each item's quantity and decrement upon applying discount
+          break;
+      }
+    }
+    //Otherwise sum product subtotals or quantities
+    else {
+      switch ($discount->qualifying_type) {
+        case QUALIFYING_TYPE_MINIMUM_PRICE:
+          //Determine the total subtotal of discount's products
+          foreach ($discount_product_ids as $product_id) {
+            if (isset($order_product_id_subtotal_map[$product_id])) {
+              $order_qualifying_amount += $order_product_id_subtotal_map[$product_id];
+            }
+          }
+
+          //Subtract already discounted amount
+          $order_qualifying_amount -= $total_discount_amount;
+          break;
+
+        case QUALIFYING_TYPE_MINIMUM_QUANTITY:
+          //Determine the total quantity of discount's products
+          foreach ($discount_product_ids as $product_id) {
+            if (isset($order_product_id_quantity_map[$product_id])) {
+              $order_qualifying_amount += $order_product_id_quantity_map[$product_id];
+            }
+          }
+          //TO DO: keep track of each item's subtotal and decrement upon applying discount
+          break;
+      }
+    }
+
+    //If order does not qualify for this discount
+    if ($order_qualifying_amount < $discount->qualifying_amount) {
+      //If this is a coded discount, add warning message
+      if (!is_null($warnings) && !is_null($discount->code)) {
+        switch ($discount->qualifying_type) {
+          case QUALIFYING_TYPE_MINIMUM_PRICE:
+            $qualifying_amount = uc_currency_format($discount->qualifying_amount);
+            $warnings[] = t('The discount for code "@code" requires a minimum price of @qualifying_amount to qualify.',
+              array("@code" => $discount->code, "@qualifying_amount" => $qualifying_amount)
+            );
+            break;
+
+          case QUALIFYING_TYPE_MINIMUM_QUANTITY:
+            $warnings[] = t('The discount for code "@code" requires a minimum quantity of @qualifying_amount to qualify.',
+              array("@code" => $discount->code, "@qualifying_amount" => $discount->qualifying_amount)
+            );
+            break;
+        }
+      }
+      continue;
+    }
+
+    //If this discount has a maximum qualifying amount and the order exceeds it
+    if ($discount->has_qualifying_amount_max && ($order_qualifying_amount > $discount->qualifying_amount_max)) {
+      //If this is a coded discount, add error message
+      if (!is_null($warnings) && !is_null($discount->code)) {
+        $qualifying_amount_max = uc_currency_format($discount->qualifying_amount_max);
+        switch ($discount->qualifying_type) {
+          case QUALIFYING_TYPE_MINIMUM_PRICE:
+            $warnings[] = t('The discount for code "@code" cannot exceed the price of @qualifying_amount_max to qualify.',
+              array("@code" => $discount->code, "@qualifying_amount_max" => $qualifying_amount_max)
+            );
+            break;
+
+          case QUALIFYING_TYPE_MINIMUM_QUANTITY:
+            $warnings[] = t('The discount for code "@code" cannot exceed the quantity of @qualifying_amount_max to qualify.',
+              array("@code" => $discount->code, "@qualifying_amount_max" => $discount->qualifying_amount_max)
+            );
+            break;
+        }
+      }
+      continue;
+    }
+
+    //Determine number of times to apply discount
+    if ($discount->qualifying_amount != 0) {
+      $discount->times_applied = (int)($order_qualifying_amount / $discount->qualifying_amount);
+    }
+    else $discount->times_applied = 1;
+    if ($discount->max_times_applied != 0) {
+      $discount->times_applied = min($discount->times_applied, $discount->max_times_applied);
+    }
+
+    //Get product IDs in order that are in discount
+    $order_and_discount_product_ids = array_intersect($discount_product_ids, $order_product_ids);
+
+    //Create array of product objects related to this discount
+    $order_and_discount_products = array();
+    foreach ($order_and_discount_product_ids as $product_id) {
+      if (array_key_exists($product_id, $order_product_id_product_array_map)) {
+        $order_and_discount_products = array_merge($order_and_discount_products,
+          $order_product_id_product_array_map[$product_id]
+        );
+      }
+    }
+
+    //Calculate discount amount
+    switch ($discount->discount_type) {
+      case DISCOUNT_TYPE_FREE_ITEMS:
+        //The variable discount_amount is the monitary amount of discount
+        $discount_amount = 0;
+
+        //The variable free_items_remaining is the [max] number of free items for the order
+        $free_items_remaining = $discount->discount_amount * $discount->times_applied;
+
+        //Loop until all free items have been applied or there are no more products to
+        //discount (discount cheapest first)
+        while ($free_items_remaining > 0) {
+          //Determine cheapest remaining qualifying item
+          $cheapest_product = NULL;
+          foreach ($order_and_discount_products as $product) {
+            //If this product has been fully discounted, continue
+            if ($product->uc_discounts_is_fully_discounted) {
+              continue;
+            }
+
+            //If no current cheapest product exists, use this product
+            if (is_null($cheapest_product)) {
+              $cheapest_product = $product;
+            }
+            else {
+              //If this product is cheaper than the current cheapest product,
+              //use this product instead
+              if ($product->price < $cheapest_product->price) {
+                $cheapest_product = $product;
+              }
+            }
+          }
+
+          //If no cheapest product could be found, there are no more products to
+          //discount, break
+          if (is_null($cheapest_product))
+          break;
+
+          //Discount up to the lesser of cheapest product quantity and free_items_remaining
+          $discount_count = min($cheapest_product->qty, $free_items_remaining);
+
+          //Add current discount amount to running total
+          $discount_amount += $discount_count * $cheapest_product->price;
+
+          //Mark item fully discounted
+          $cheapest_product->uc_discounts_is_fully_discounted = TRUE;
+
+          $free_items_remaining -= $discount_count;
+        }
+
+        $discount->amount = $discount_amount;
+        break;
+
+      case DISCOUNT_TYPE_PERCENTAGE_OFF:
+        //Always apply once
+        $discount->times_applied = 1;
+
+        //If this discount uses all products and previous discount is:
+        //	same weight as this discount
+        //	percentage off
+        //	products of discounts must match
+        //discount using same subtotal as last discount
+        if (count($discounts) > 0) {
+          $last_discount = $discounts[count($discounts) - 1];
+          if (($last_discount->weight == $discount->weight)
+            && ($last_discount->discount_type == DISCOUNT_TYPE_PERCENTAGE_OFF)
+          ) {
+            //Last discount's and this discount's products must match exactly
+            $are_equal = TRUE;
+            $last_discount_product_ids = get_product_ids_for_discount_object($last_discount);
+            $this_discount_product_ids = get_product_ids_for_discount_object($discount);
+            //If both contain "all products" they are equal
+            if (in_array(ALL_PRODUCTS, $last_discount_product_ids)
+              && in_array(ALL_PRODUCTS, $this_discount_product_ids)
+            ) $are_equal = TRUE;
+            //Otherwise check arrays for equality
+            else {
+              foreach ($this_discount_product_ids as $product_id) {
+                if (!in_array($product_id, $last_discount_product_ids)) {
+                  $are_equal = FALSE;
+                  break;
+                }
+              }
+
+              if ($are_equal) {
+                foreach ($last_discount_product_ids as $product_id) {
+                  if (!in_array($product_id, $this_discount_product_ids)) {
+                    $are_equal = FALSE;
+                    break;
+                  }
+                }
+              }
+            }
+
+            if ($are_equal) {
+              //($last_discount->amount / $last_discount->discount_amount) == last discount's subtotal
+              $local_order_subtotal = ($last_discount->amount / $last_discount->discount_amount);
+              $discount->amount = $local_order_subtotal * $discount->discount_amount;
+              break;
+            }
+          }
+        }
+
+        //Start patch from lutegrass:
+        //This fixes the problem where a percent discount does not apply to all products
+        //(but doesn't fix the problem where the products being discounted have already been discounted
+        //in full, or the case where the cart consists only of the products included in this discount)
+        // Get qualifying products -- ignore "all products" selection
+        $discount_product_ids = get_product_ids_for_discount_object($discount, TRUE);
+
+        // Do we have any products
+        if (count($discount_product_ids) > 0) {
+          $discounted_products_amount = 0;
+          foreach ($order_and_discount_products as $product) {
+            $discounted_products_amount += $product->price * $product->qty;
+          }
+          $discount->amount = $discounted_products_amount * $discount->discount_amount;
+          // Discount the subtotal so far
+        }
+        else {
+          $discount->amount = max($order_subtotal - $total_discount_amount, 0) * $discount->discount_amount;
+        }
+        //End patch from lutegrass
+        break;
+
+      case DISCOUNT_TYPE_FIXED_AMOUNT_OFF:
+        $discount->amount = $discount->discount_amount * $discount->times_applied;
+        break;
+
+      case DISCOUNT_TYPE_FIXED_AMOUNT_OFF_PER_QUALIFYING_ITEM:
+        //Discount is the total quantity of qualifying items in order (order_qualifying_amount)
+        //times the discount amount
+        $discount->amount = $discount->discount_amount * $order_qualifying_amount;
+        break;
+    }
+
+    if (!is_null($messages)) {
+      $options = array("@short_description" => $discount->short_description,
+        "@code" => $discount->code,
+        "@times_applied" => $discount->times_applied,
+        "@discount_amount" => uc_currency_format($discount->amount),
+        "@time_string" => $time_string,
+      );
+      if (!is_null($discount->code)) {
+        if ($discount->times_applied == 1) $messages[] = t("The discount, '@short_description', with code '@code' was applied for a discount of @discount_amount.",
+          $options
+        );
+        else $messages[] = t("The discount, '@short_description', with code '@code' was applied @times_applied times for a discount of @discount_amount.",
+          $options
+        );
+      }
+      else {
+        if ($discount->times_applied == 1) $messages[] = t("The discount, '@short_description', was applied for a discount of @discount_amount.",
+          $options
+        );
+        else $messages[] = t("The discount, '@short_description', was applied @times_applied times for a discount of @discount_amount.",
+          $options
+        );
+      }
+    }
+
+    //Round the discount to two places
+    $discount->amount = round($discount->amount, 2);
+
+    //Add this discount's amount to running total
+    $total_discount_amount += $discount->amount;
+
+    //Add this discount to list of discounts applied to order
+    $discounts[] = $discount;
+  }
+  return $discounts;
 }
 
 /**
  * Returns all codeless discounts for product.
+ *
  * @param $product_id Node ID for product
  */
-function get_codeless_discounts_for_product($product, $sort_column = "weight", $is_ascending_sort = TRUE)
-{
-	return get_codeless_discounts_for_product_and_quantity($product, NULL, 
-		$sort_column, $is_ascending_sort);
+function get_codeless_discounts_for_product($product, $sort_column = "weight", $is_ascending_sort = TRUE) {
+  return get_codeless_discounts_for_product_and_quantity($product, NULL,
+    $sort_column, $is_ascending_sort
+  );
 }
 
 /**
  * Returns all codeless discounts for product when specified quantity is purchased.
+ *
  * @param $product_id Node ID for product
  */
-function get_codeless_discounts_for_product_and_quantity($product, $quantity = NULL, $sort_column = "weight", 
-	$is_ascending_sort = TRUE)
-{
-	if (is_null($product) || !$product)
-		return array();
-
-	//If quantity was specified
-	if ( !is_null($quantity) )
-	{
-		global $user;
-
-		//Create phony order and get discounts for order
-		$product->price = $product->sell_price;
-		$product->qty = $quantity;
-		$order = new stdClass();
-		$order->uid = $user->uid;
-		$order->products = array($product);
-		return get_discounts_for_order($order);
-	}
-
-	//Otherwise make special query
-
-	//Get terms for product
-	$term_ids = array();
-	$term_ids[] = ALL_TERMS;
-	$result = db_query("SELECT DISTINCT tid FROM {term_node} WHERE nid=%d", $product->nid);
-	while ( $row = db_fetch_array($result) )
-		$term_ids[] = $row["tid"];
-
-	//Get SKUs for product
-	$skus = array();
-	$skus[] = "'" . db_escape_string(ALL_SKUS) . "'";
-	$result = db_query("SELECT DISTINCT model FROM {uc_products} WHERE nid=%d", $product->nid);
-	while ( $row = db_fetch_array($result) )
-		$skus[] = "'" . db_escape_string($row["model"]) . "'";
-
-	//Create roles clause
-	global $user;
-	$auth_rid = ($user->uid != 0) ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
-	$roles_clause = sprintf(" OR d.discount_id IN(SELECT dr.discount_id FROM {uc_discounts_roles} dr"
-		. ", {users_roles} ur WHERE (dr.role_id=ur.rid AND ur.uid=%d) OR dr.role_id=%d OR dr.role_id=%d)", 
-		$user->uid, ALL_ROLES, $auth_rid);
-
-	$product_ids = array(ALL_PRODUCTS, $product->nid);
-	$product_ids_clause = sprintf( "d.filter_type<>%d OR dp.product_id IN(%s)", 
-		FILTER_TYPE_PRODUCTS, join(",", $product_ids) );
-
-	$term_ids_clause = sprintf( "d.filter_type<>%d OR dt.term_id IN(%s)", 
-		FILTER_TYPE_TERMS, join(",", $term_ids) );
-
-	$skus_clause = sprintf( "d.filter_type<>%d OR ds.sku IN(%s)", 
-		FILTER_TYPE_SKUS, join(",", $skus) );
+function get_codeless_discounts_for_product_and_quantity($product, $quantity = NULL, $sort_column = "weight",
+  $is_ascending_sort = TRUE
+) {
+  if (is_null($product) || !$product) {
+    return array();
+  }
+
+  //If quantity was specified
+  if (!is_null($quantity)) {
+    global $user;
+
+    //Create phony order and get discounts for order
+    $product->price  = $product->sell_price;
+    $product->qty    = $quantity;
+    $order           = new stdClass();
+    $order->uid      = $user->uid;
+    $order->products = array($product);
+    return get_discounts_for_order($order);
+  }
+
+  //Otherwise make special query
+
+  //Get terms for product
+  $term_ids   = array();
+  $term_ids[] = ALL_TERMS;
+  $result     = db_query("SELECT DISTINCT tid FROM {term_node} WHERE nid=%d", $product->nid);
+  while ($row = db_fetch_array($result)) $term_ids[] = $row["tid"];
+
+  //Get SKUs for product
+  $skus   = array();
+  $skus[] = "'". db_escape_string(ALL_SKUS) ."'";
+  $result = db_query("SELECT DISTINCT model FROM {uc_products} WHERE nid=%d", $product->nid);
+  while ($row = db_fetch_array($result)) $skus[] = "'". db_escape_string($row["model"]) ."'";
+
+  //Create roles clause
+  global $user;
+  $auth_rid = ($user->uid != 0) ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
+  $roles_clause = sprintf(" OR d.discount_id IN(SELECT dr.discount_id FROM {uc_discounts_roles} dr" . ", {users_roles} ur WHERE (dr.role_id=ur.rid AND ur.uid=%d) OR dr.role_id=%d OR dr.role_id=%d)",
+    $user->uid, ALL_ROLES, $auth_rid
+  );
+
+  $product_ids = array(ALL_PRODUCTS, $product->nid);
+  $product_ids_clause = sprintf("d.filter_type<>%d OR dp.product_id IN(%s)",
+    FILTER_TYPE_PRODUCTS, join(",", $product_ids)
+  );
+
+  $term_ids_clause = sprintf("d.filter_type<>%d OR dt.term_id IN(%s)",
+    FILTER_TYPE_TERMS, join(",", $term_ids)
+  );
+
+  $skus_clause = sprintf("d.filter_type<>%d OR ds.sku IN(%s)",
+    FILTER_TYPE_SKUS, join(",", $skus)
+  );
 
-	$sort_order_string = (is_ascending_sort) ? "ASC" : "DESC";
+  $sort_order_string = (is_ascending_sort) ? "ASC" : "DESC";
 
-	$query = sprintf("SELECT d.* FROM {uc_discounts} d
+  $query = sprintf("SELECT d.* FROM {uc_discounts} d
 		LEFT JOIN {uc_discounts_products} dp ON d.discount_id=dp.discount_id
 		LEFT JOIN {uc_discounts_terms} dt ON d.discount_id=dt.discount_id
 		LEFT JOIN {uc_discounts_skus} ds ON d.discount_id=ds.discount_id
@@ -1602,83 +1518,79 @@ function get_codeless_discounts_for_prod
 		AND (%s)
 		AND (%s)
 		AND (d.has_expiration=0 OR d.expiration>%d)
-		ORDER BY d.%s %s", $roles_clause, $product_ids_clause, $term_ids_clause, $skus_clause, time(), 
-			$sort_column, $sort_order_string);
-	uc_discounts_log("query=" . $query);
-	$result = db_query($query);
-	
-	$discounts = array();
-	while ( $discount = db_fetch_object($result) )
-		$discounts[] = $discount;
+		ORDER BY d.%s %s", $roles_clause, $product_ids_clause, $term_ids_clause, $skus_clause, time(),
+    $sort_column, $sort_order_string
+  );
+  uc_discounts_log("query=". $query);
+  $result = db_query($query);
 
-	return $discounts;
+  $discounts = array();
+  while ($discount = db_fetch_object($result)) $discounts[] = $discount;
+
+  return $discounts;
 }
 
 /**
  * Inserts a uc_discounts_uses row and returns its discount_use_id.
  */
 function uc_discounts_uses_insert($discount_id, $user_id, $order_id, $code, $times_applied, $amount,
-	$insert_timestamp = NULL)
-{
-	if ( is_null($insert_timestamp) )
-		$insert_timestamp = time();
-	
-	$query = "INSERT INTO {uc_discounts_uses}(discount_id, user_id, order_id, code, times_applied, amount, insert_timestamp)"
-		. " VALUES(%d, %d, %d, '%s', %d, %f, %d)";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id, $user_id, $order_id, $code, $times_applied, $amount, $insert_timestamp);
-	return db_last_insert_id("uc_discounts_uses", "discount_use_id");
+  $insert_timestamp = NULL
+) {
+  if (is_null($insert_timestamp)) {
+    $insert_timestamp = time();
+  }
+
+  $query = "INSERT INTO {uc_discounts_uses}(discount_id, user_id, order_id, code, times_applied, amount, insert_timestamp)" . " VALUES(%d, %d, %d, '%s', %d, %f, %d)";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id, $user_id, $order_id, $code, $times_applied, $amount, $insert_timestamp);
+  return db_last_insert_id("uc_discounts_uses", "discount_use_id");
 }
 
 /**
  * Deletes all uc_discounts_uses rows for a discount.
  */
-function uc_discounts_uses_delete_for_discount($discount_id)
-{
-	$query = "DELETE FROM {uc_discounts_uses} WHERE discount_id=%d";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $discount_id);
+function uc_discounts_uses_delete_for_discount($discount_id) {
+  $query = "DELETE FROM {uc_discounts_uses} WHERE discount_id=%d";
+  uc_discounts_log("query=". $query);
+  db_query($query, $discount_id);
 }
 
 /**
  * Deletes all uc_discounts_uses rows for an order.
  */
-function uc_discounts_uses_delete_for_order($order_id)
-{
-	$query = "DELETE FROM {uc_discounts_uses} WHERE order_id=%d";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $order_id);
+function uc_discounts_uses_delete_for_order($order_id) {
+  $query = "DELETE FROM {uc_discounts_uses} WHERE order_id=%d";
+  uc_discounts_log("query=". $query);
+  db_query($query, $order_id);
 }
 
 /**
  * Returns order codes for order.
  */
-function uc_discounts_order_codes_get($order_id)
-{
-	//Get order's codes from database
-	$row = db_fetch_array( db_query(
-		"SELECT codes FROM {uc_discounts_order_codes} WHERE order_id=%d", $order_id) );
-	return ( !empty($row) ) ? $row["codes"] : NULL;
+function uc_discounts_order_codes_get($order_id) {
+  //Get order's codes from database
+  $row = db_fetch_array(db_query(
+      "SELECT codes FROM {uc_discounts_order_codes} WHERE order_id=%d", $order_id
+    ));
+  return (!empty($row)) ? $row["codes"] : NULL;
 }
 
 /**
  * Inserts a uc_discounts_order_codes row.
  */
-function uc_discounts_order_codes_insert($order_id, $codes_string)
-{
-	$query = "INSERT INTO {uc_discounts_order_codes}(order_id, codes) VALUES(%d, '%s')";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $order_id, $codes_string);
+function uc_discounts_order_codes_insert($order_id, $codes_string) {
+  $query = "INSERT INTO {uc_discounts_order_codes}(order_id, codes) VALUES(%d, '%s')";
+  uc_discounts_log("query=". $query);
+  db_query($query, $order_id, $codes_string);
 }
 
 /**
  * Deletes all uc_discounts_order_codes rows for an order.
  */
-function uc_discounts_order_codes_delete($order_id)
-{
-	$query = "DELETE FROM {uc_discounts_order_codes} WHERE order_id=%d";
-	uc_discounts_log("query=" . $query);
-	db_query($query, $order_id);
+function uc_discounts_order_codes_delete($order_id) {
+  $query = "DELETE FROM {uc_discounts_order_codes} WHERE order_id=%d";
+  uc_discounts_log("query=". $query);
+  db_query($query, $order_id);
 }
 
 
@@ -1689,88 +1601,85 @@ function uc_discounts_order_codes_delete
 /**
  * Returns a string list of codes into an array of codes
  */
-function get_codes($codes_string)
-{
-	$codes = array();
-
-	if ( empty($codes_string) )
-		return $codes;
-
-	$raw_codes = explode("\n", $codes_string);
-
-	foreach ($raw_codes as $raw_code)
-	{
-		$code = trim($raw_code);
-		if ( !empty($code) )
-			$codes[] = $code;
-	}
-	
-	return $codes;
+function get_codes($codes_string) {
+  $codes = array();
+
+  if (empty($codes_string)) {
+
+    return $codes;
+
+  }
+
+  $raw_codes = explode("\n", $codes_string);
+
+  foreach ($raw_codes as $raw_code) {
+    $code = trim($raw_code);
+    if (!empty($code)) {
+      $codes[] = $code;
+    }
+  }
+
+  return $codes;
 }
 
 /**
  * Create a codes string from passed codes array.
  * Note: returns "" if passed array is null
  */
-function create_codes_string($codes)
-{
-	if ( empty($codes) )
-		return "";
-	return join("\n", $codes);
+function create_codes_string($codes) {
+  if (empty($codes)) {
+    return "";
+  }
+  return join("\n", $codes);
 }
 
 /**
  * Returns an array of qualifying types with descriptions.
  */
-function qualifying_type_options()
-{
-	static $options = NULL;
-	
-	if ( is_null($options) )
-	{
-		$options = array( QUALIFYING_TYPE_MINIMUM_PRICE => t("Minimum price"), 
-			QUALIFYING_TYPE_MINIMUM_QUANTITY => t("Minimum quantity") );
-	}
-	
-	return $options;
-}
-
-function qualifying_type_name($qualifying_type)
-{
-	$options = qualifying_type_options();
-	return $options[$qualifying_type];
+function qualifying_type_options() {
+  static $options = NULL;
+
+  if (is_null($options)) {
+    $options = array(QUALIFYING_TYPE_MINIMUM_PRICE => t("Minimum price"),
+      QUALIFYING_TYPE_MINIMUM_QUANTITY => t("Minimum quantity"),
+    );
+  }
+
+  return $options;
+}
+
+function qualifying_type_name($qualifying_type) {
+  $options = qualifying_type_options();
+  return $options[$qualifying_type];
 }
 
 /**
  * Returns an array of discount types with descriptions.
  */
-function discount_type_options()
-{
-	static $options = NULL;
-	
-	if ( is_null($options) )
-	{
-		$options = array( DISCOUNT_TYPE_PERCENTAGE_OFF => t("Percent off"), 
-			DISCOUNT_TYPE_FIXED_AMOUNT_OFF => t("Fixed amount off"),
-			DISCOUNT_TYPE_FIXED_AMOUNT_OFF_PER_QUALIFYING_ITEM => t("Fixed amount off per qualifying item"),
-			DISCOUNT_TYPE_FREE_ITEMS => t("Free items") );
-	}
-	
-	return $options;
-}
-
-function discount_type_name($discount_type)
-{
-	$options = discount_type_options();
-	return $options[$discount_type];
-}
-
-function uc_discounts_add_to_existing_map_number_value(&$a, $key, $value)
-{
-	$a[$key] = ( array_key_exists($key, $a) ) ? $a[$key] + $value : $value;
-}
-
-function uc_discounts_log($s)
-{
-//	error_log($s);
+function discount_type_options() {
+  static $options = NULL;
+
+  if (is_null($options)) {
+    $options = array(DISCOUNT_TYPE_PERCENTAGE_OFF => t("Percent off"),
+      DISCOUNT_TYPE_FIXED_AMOUNT_OFF => t("Fixed amount off"),
+      DISCOUNT_TYPE_FIXED_AMOUNT_OFF_PER_QUALIFYING_ITEM => t("Fixed amount off per qualifying item"),
+      DISCOUNT_TYPE_FREE_ITEMS => t("Free items"),
+    );
+  }
+
+  return $options;
 }
+
+function discount_type_name($discount_type) {
+  $options = discount_type_options();
+  return $options[$discount_type];
+}
+
+function uc_discounts_add_to_existing_map_number_value(&$a, $key, $value) {
+  $a[$key] = (array_key_exists($key, $a)) ? $a[$key] + $value : $value;
+}
+
+function uc_discounts_log($s) {
+  //	error_log($s);
+}
+
