<?php

/**
  * ---------------------------------------------------------------------------------
  *
  * This file is part of the 'OleaMultiPromos' module feature
  * Developped for Prestashop platform.
  * You are not allowed to use it on several site
  * You are not allowed to sell or redistribute this module
  * This header must not be removed
  *
  * @category
  * @author OleaCorner <contact@oleacorner.com> <www.oleacorner.com>
  * @copyright OleaCorner
  * @version 1.0
  *
  * ---------------------------------------------------------------------------------
  */


include_once (dirname(__FILE__).'/Oleapromo.php');

class AdminMultiPromos extends AdminTab
{
	private $_MODULE = null;

	public $multishop_context = -1;
	public $multishop_context_group = true;

	public function __construct()
	{
		$cookie = Context::getContext()->cookie;

		$this->table = 'oleapromo';
	 	$this->className = 'Oleapromo';
		$this->lang = false;
	 	$this->edit = true;
	 	$this->view = false;
	 	$this->delete = true;
	 	//$this->deleted = true;
	 	$this->_defaultOrderBy = 'position';

	 	if (!isset($this->identifiersDnd))
	 		$this->identifiersDnd = array();
 		$this->identifiersDnd = array_merge ($this->identifiersDnd, array('id_oleapromo'=>'id_oleapromo'));

 		if (!isset($this->_languages))
 			$this->_languages = Language::getLanguages(false);
		if (!isset($this->_defaultFormLanguage))
			$this->_defaultFormLanguage = (int)(Configuration::get('PS_LANG_DEFAULT'));

	 	$this->_select = 'a.position ';
	 	//$this->_join = '';
		//$this->_where = '';
		//$this->_group = '';
		//$this->_listSkipDelete = array(1);

	 	$this->fieldsDisplay = array(
		'id_oleapromo' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25),
	 	'name' => array('title' => $this->l('Name'), 'align' => 'left', 'width' => 300),
	 	'active' => array('title' => $this->l('Enabled'), 'width' => 25, 'align' => 'center', 'active' => 'status', 'type' => 'bool', 'orderby' => false),
		'position' => array('title' => $this->l('Position'), 'width' => 40,'filter_key' => 'position', 'align' => 'center', 'position' => 'position'),
	 	'global_family' => array('title' => $this->l('Family'), 'align' => 'left', 'width' => 120),
	 	'global_allows_others' => array('title' => $this->l('Others'), 'width' => 25, 'align' => 'center', 'activeVisu' => true, 'type' => 'bool', 'orderby' => false),
	 	'global_allows_family' => array('title' => $this->l('Allows fam'), 'width' => 25, 'align' => 'center', 'activeVisu' => true, 'type' => 'bool', 'orderby' => false),
	 	);

		$this->optionTitle = $this->l('Discount options');
		$this->_fieldsOptions = array(
			'OLEA_MAXIPROMO_MAIL_ORDERSTATE' => array('title' => $this->l('Order state for mail sending:'), 'desc' => $this->l('Order state on which to send the discounts to the customer'), 'cast' => 'intval', 'type' => 'select', 'identifier' => 'id_order_state', 'list' => OrderState::getOrderStates((int)(Configuration::get('PS_LANG_DEFAULT')))),
			'OLEA_MAXIPROMO_NBDAYS' => array('title' => $this->l('Default nb days:'), 'desc' => $this->l('Number of days to check for unused auto-generated discounts'), 'cast' => 'intval', 'size' => 5, 'type' => 'integer'),
			'OLEA_MAXIPROMO_ONLYDEFAULTGROUPS' => array('title' => $this->l('Only default group:'), 'desc' => $this->l('While testing the customer groups to apply a rule, test only the default group.'), 'cast' => 'intval', 'size' => 5, 'type' => 'bool'),
		);
		$oleaextcartrulemodule = Module::getInstanceByName('oleaextcartrulemodule');
		if (Validate::isLoadedObject($oleaextcartrulemodule) && $oleaextcartrulemodule->active)
			$this->_fieldsOptions['OLEA_MAXIPROMO_EXTRULEFAMILY'] = array('title' => $this->l('Extended Cart Rule family:'), 'desc' => $this->l('Default family of the Extended Cart Rules module for cart rule generated by this module'),
																		 'cast' => 'intval', 'type' => 'select', 'identifier' => 'id_oleacartrulefamily', 'list' => $oleaextcartrulemodule->getOleaCartRuleFamiliesList());

		$this->optionsList = array(
				'options' => array(
					'title' =>	($this->optionTitle) ? $this->optionTitle : $this->l('Options'),
					'fields' =>	$this->_fieldsOptions,
				),
		);

		$this->criteria_type_list = array();
		$this->criteria_type_list[Oleapromo::CRITERIA_TYPE_PRODUCT_NUMBER] = $this->l('Number of products');
		$this->criteria_type_list[Oleapromo::CRITERIA_TYPE_PRODUCT_AMOUNT] = $this->l('Total amount');

		$this->criteria_association_type_list = array();
		$this->criteria_association_type_list[Oleapromo::ASSOCIATION_TYPE_CATEGORY] = $this->l('Category');
		$this->criteria_association_type_list[Oleapromo::ASSOCIATION_TYPE_PRODUCT] = $this->l('Product');
		$this->criteria_association_type_list[Oleapromo::ASSOCIATION_TYPE_ATTRIBUTE] = $this->l('Product combination');

		$this->attribution_type_list = array();
		$this->attribution_type_list[Oleapromo::ATTRIBUTION_TYPE_PERCENT] = $this->l('Percentage of reduction');
		$this->attribution_type_list[Oleapromo::ATTRIBUTION_TYPE_AMOUNT] = $this->l('Amount of reduction');
		$this->attribution_type_list[Oleapromo::ATTRIBUTION_TYPE_AMOUNT_PRICES_RANGE] = $this->l('Amount per price range');
		$this->attribution_type_list[Oleapromo::ATTRIBUTION_TYPE_FDP] = $this->l('Free shipping');
		$this->attribution_type_list[Oleapromo::ATTRIBUTION_TYPE_FINAL_PRICE] = $this->l('Final price');

		$this->order_type_list = array();
		$this->order_type_list[Oleapromo::ORDER_TYPE_ALLORDERS] = $this->l('All orders');
		$this->order_type_list[Oleapromo::ORDER_TYPE_FIRSTORDER] = $this->l('First order');
		$this->order_type_list[Oleapromo::ORDER_TYPE_REORDER] = $this->l('Re-order');

		$this->sending_method_list = array();
		$this->sending_method_list[Oleapromo::SENDING_METHOD_CURRENT_CART] = $this->l('Into current cart');
		$this->sending_method_list[Oleapromo::SENDING_METHOD_MAIL] = $this->l('Sent by e-mail');

		$this->_html = '';
		parent::__construct();
	}

	function init_container_module_info () {
		$module_name = basename(dirname(__FILE__));
		include_once (dirname(__FILE__).'/'.$module_name.'.php');
		$this->_container_module = new $module_name ();
	}

	/*---------------------- Displays() ------------------------------------------------*/
	public function _getGlobalCriteriaTabHtml($obj) {
		$cookie = Context::getContext()->cookie;

		$retour = '';

		// -------- Dates ---------
		$date_from = ($obj->global_date_from <> '') ?$obj->global_date_from :date('Y-m-d');
		$date_to = ($obj->global_date_to <> '') ?$obj->global_date_to :date('Y-m-d', strtotime('+1 year'));
		$retour .= '
			<div class="clear">&nbsp;</div>
			<label>'.$this->l('Validity dates:').' </label>
				<div class="margin-form">
					<span>'.$this->l('From :').'<input type="text" size="15" name="global_date_from" id="global_date_from" value="'.htmlentities($date_from, ENT_COMPAT, 'UTF-8').'" />
					'.$this->l('To :').'<input type="text" size="15" name="global_date_to" id="global_date_to" value="'.htmlentities($date_to, ENT_COMPAT, 'UTF-8').'" />
					(\'yyyy/mm/dd\')</span></div>';

		// -------- Type ---------
		$retour .= '
			<div class="clear">&nbsp;</div>
			<label>'.$this->l('Order type:').' </label>
				<div class="margin-form">
					<select name="global_order_type" id="id_global_order_type">';
				$global_order_type = (int)$this->getFieldValue($obj, 'global_order_type');
				foreach ($this->order_type_list as $k=>$v) {
					$selected = ($k == $global_order_type) ?'SELECTED' :'';
					$retour .=  '<option value="'.$k.'" '.$selected.'>'.$v.'&nbsp;</option>';
				}
				$retour .=  '
					</select>
				</div>';

		// -------- Global cart amount ---------
		$retour .= '
			<div class="clear ">&nbsp;</div>
			<label class="">'.$this->l('Minimal cart amount:').' </label>
				<div class="margin-form ">
					<input type="text" size="10" name="global_cart_amount" value="'.(float)($this->getFieldValue($obj, 'global_cart_amount')).'" onKeyUp="javascript:this.value = this.value.replace(/,/g, \'.\'); " />
					&nbsp;<select id="global_cart_amount_id_currency" name="global_cart_amount_id_currency" style2="float:left;margin-left:10px;width:50px;" >';
			$obj_global_cart_amount_id_currency = (int)$this->getFieldValue($obj, 'global_cart_amount_id_currency');
			if ($obj_global_cart_amount_id_currency == 0)
				$obj_global_cart_amount_id_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT');
			foreach (Currency::getCurrencies() as $row)
				if ($row['id_currency'] == (int)Configuration::get('PS_CURRENCY_DEFAULT'))
					$retour .= '<option value="'.(int)$row['id_currency'].'" '.(($obj_global_cart_amount_id_currency == $row['id_currency']) ? 'selected="selected"' : '').'>'.$row['sign'].'&nbsp;</option>';
		$retour .= '</select>
					<p>'.$this->l('Minimal cart amount to apply the rule (products total, without any discount and without carrier)').'</p>
				</div>';

		// -------- Global Cart Amount taxes ---------
		$retour .= '
			<label class=" ">'.$this->l('Min cart amount taxes included:').' </label>
				<div class="margin-form ">
					<input type="radio" name="global_cart_amount_withtaxes" id="global_cart_amount_withtaxes_on" value="1" '.($this->getFieldValue($obj, 'global_cart_amount_withtaxes') ? 'checked="checked" ' : '').'/>
					<label class="t" for="global_cart_amount_withtaxes_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="global_cart_amount_withtaxes" id="global_cart_amount_withtaxes_off" value="0" '.(!$this->getFieldValue($obj, 'global_cart_amount_withtaxes') ? 'checked="checked" ' : '').'/>
					<label class="t" for="global_cart_amount_withtaxes_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p>'.$this->l('Indicates if the minimal cart amount includes or not the taxes').'</p>
				</div>';

		// -------- Cumulable with discounts 1.4 ---------
		if (version_compare('1.5', _PS_VERSION_) <= 0){
			 $retour .= '<input type="hidden" value="'.(int)$this->getFieldValue($obj, 'global_cumulable_with_discounts').'" name="global_cumulable_with_discounts"/>';
		} else { // 1.4 Only
			$retour .= '
			<div class="clear">&nbsp;</div>
			<label  >'.$this->l('Cumulable with discounts:').' </label>
				<div  class="margin-form">
					<input type="radio" name="global_cumulable_with_discounts" id="global_cumulable_with_discounts_on" value="1" '.($this->getFieldValue($obj, 'global_cumulable_with_discounts') ? 'checked="checked" ' : '').'/>
					<label class="t" for="global_cumulable_with_discounts_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="global_cumulable_with_discounts" id="global_cumulable_with_discounts_off" value="0" '.(!$this->getFieldValue($obj, 'global_cumulable_with_discounts') ? 'checked="checked" ' : '').'/>
					<label class="t" for="global_cumulable_with_discounts_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p class="clear">'.$this->l('Specify if this promotion is cumulable with standards discount codes').'</p>
				</div>';
		}

		// -------- Cart rule priority 1.5 ---------
		if (version_compare('1.5', _PS_VERSION_) <= 0){   // 1.5 Only
		$global_cart_rule_priority = (int)$this->getFieldValue($obj, 'global_cart_rule_priority');
		$retour .= '
			<div class="clear">&nbsp;</div>
			<label>'.$this->l('Cart rule priority:').' </label>
				<div class="margin-form">
					<input type="text" size="15" name="global_cart_rule_priority" id="global_cart_rule_priority" value="'.htmlentities(($global_cart_rule_priority) ?$global_cart_rule_priority :1, ENT_COMPAT, 'UTF-8').'" />
				<p class="clear">'.$this->l('Specify the priority of the cart rule that the module generates').'</p>
			</div>';
		}

		// ------------- Extended Cart rule module -------------------------
		$oleaextcartrulemodule = Module::getInstanceByName('oleaextcartrulemodule');
		if (Validate::isLoadedObject($oleaextcartrulemodule) && $oleaextcartrulemodule->active)
		{
			$retour .= '<div class="clear">&nbsp;</div>
				<label>'.$this->l('ExtCartRule Family:').' </label>
				<div class="margin-form">
					<select name="attribution_id_extcartrulefamily" id="attribution_id_extcartrulefamily" >
						';
			foreach ($oleaextcartrulemodule->getOleaCartRuleFamiliesList() as $row)
				$retour .= '<OPTION value="'.$row['id_oleacartrulefamily'].'" '.(($this->getFieldValue($obj, 'attribution_id_extcartrulefamily') == $row['id_oleacartrulefamily']) ? 'selected="selected"' : '').'>'.$row['name'].'&nbsp;</OPTION>';
			$retour .= '</SELECT>
				<p class="clear">'.$this->l('Specify the family group of the Extended Cart Rule module.').'</p>
				</div>';
		}

		// -------- Cart rule restriction 1.5 ---------
		if (0 AND version_compare('1.5', _PS_VERSION_) <= 0){   // 1.5 Only... but not yet supported : cart rule restriction strangely managed by the core

				// -------- Script ---------
		$retour .= '
		<script type="text/javascript">
			function removeCartRuleOption(item) {
				var id = $(item).attr(\'id\').replace(\'_remove\', \'\');
				$(\'#\' + id + \'_2 option:selected\').remove().appendTo(\'#\' + id + \'_1\');
			}

			function addCartRuleOption(item) {
				var id = $(item).attr(\'id\').replace(\'_add\', \'\');
				$(\'#\' + id + \'_1 option:selected\').remove().appendTo(\'#\' + id + \'_2\');
			}

			$(document).ready(function(){
				$(\'#cart_rule_select_remove\').click(function() {removeCartRuleOption(this);});
				$(\'#cart_rule_select_add\').click(function() {addCartRuleOption(this);});
				$(\'#id_form_multipromo\').submit(function() {
					$(\'#cart_rule_select_1 option\').each(function(i) {
						$(this).attr(\'selected\', true);
					});
				});
			});
		</script>';

		$cart_rule = new CartRule();
		$all_cart_rules = $cart_rule->getAssociatedRestrictions('cart_rule', true, true);
		$global_cart_rule_exclusion = $obj->getGlobalCartrulesExclusion();
		foreach ($all_cart_rules['selected'] as $k=>$cr)
			if ((int)($cr['is_for_oleamultipromo']))
				unset($all_cart_rules['selected'][$k]);
			else if (in_array($cr['id_cart_rule'], $global_cart_rule_exclusion)) {
				$all_cart_rules['unselected'][] = $cr;
				unset($all_cart_rules['selected'][$k]);
			}
		$retour .= '
			<label  >'.$this->l('Cart rules restriction:').' </label>
				<div id="cart_rule_restriction_div" class="margin-form" style2="border:1px solid #AAAAAA;margin-top:10px;padding:0 10px 10px 10px;background-color:#FFF5D3">
				<p class="clear2">'.$this->l('Specify the cart rules the generated cart rule is compatible with').'</p>
				<table>
				<tr>
					<td style="padding-left:0px;">
					<p><strong>'.$this->l('Not cumulable with').'</strong></p>
					<select name="select_global_cart_rule_exclusion[]"  id="cart_rule_select_1" style="border:1px solid #AAAAAA;width:400px;height:160px" multiple>';
					foreach ($all_cart_rules['unselected'] as $k=>$cr)
						$retour .= '<option value="'.(int)$cr['id_cart_rule'].'">&nbsp;'.$cr['name'].'</option>';
				$retour .= '
					</select><br /><br />
					<a id="cart_rule_select_add"
					style="text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px">
					'.$this->l('Set as cumulable').' &gt;&gt;
					</a>
					</td>
					<td>
					<p><strong>'.$this->l('Cumulable with').'</strong></p>
					<select id="cart_rule_select_2" style="border:1px solid #AAAAAA;width:400px;height:160px" multiple>';
					foreach ($all_cart_rules['selected'] as $k=>$cr)
						$retour .= '<option value="'.(int)$cr['id_cart_rule'].'">&nbsp;'.$cr['name'].'</option>';
		$retour .= '
					</select><br /><br />
					<a id="cart_rule_select_remove"
						style="text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px">
						&lt;&lt; '.$this->l('Set as not cumulable').'
					</a>
					</td>
				</tr>
				</table>
			</div>';
		}

		// -------- Related groups ---------
		$retour .= '
			<div class="clear">&nbsp;</div>
			<label>'.$this->l('Related groups:').' </label>
				<div class="margin-form">';
					$groups = Group::getGroups(intval($cookie->id_lang));
					if (sizeof($groups))
					{
						$retour .= '
						<table cellspacing="0" cellpadding="0" class="table" style="width: 28em;">
							<tr>
								<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'groupBox[]\', this.checked)"'.(!isset($obj->id) ? 'checked="checked" ' : '').' /></th>
								<th>'.$this->l('ID').'</th>
								<th>'.$this->l('Group name').'</th>
							</tr>';
							$irow = 0;
							$customer_groups = $obj->getGlobalGroups();
							foreach ($groups as $group)
								$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
									<td><input type="checkbox" name="groupBox[]" class="groupBox" id="groupBox_'.$group['id_group'].'" value="'.$group['id_group'].'" '.((in_array($group['id_group'], $customer_groups) OR (!isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>'.$group['id_group'].'</td>
									<td><label for="groupBox_'.$group['id_group'].'" class="t">'.$group['name'].'</label></td>
								</tr>';
							$retour .= '
						</table>
						<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Groups of customer to which the promotion applies').'</p>
						';
					} else
						$retour .= '<p>'.$this->l('No group created').'</p>';
				$retour .= '
				</div>';

		if (Shop::isFeatureActive() )
			{
				$helper = new HelperForm();
				$helper->id = (int)Tools::getValue('id_oleapromo');
				$helper->table = 'oleapromo';
				$helper->identifier = 'id_oleapromo';
				$helper->base_folder = _PS_ADMIN_DIR_.'/themes/default/template/helpers/form/';

//die ('<pre>This='.print_r($this,true));
//	die('<pre>helper='.print_r($helper, true));
//	$this->module = $this->_container_module;
				$retour .= '<div class="clear">&nbsp;</div>
					<label for="shop_association">'.$this->l('Shop association:').'</label>
					<div id="shop_association" class="margin-form">'.$helper->renderAssoShop().'</div>';
			}

		return $retour;
	}

	public function _getProductsCriteriaTabHtml($obj) {
		$cookie = Context::getContext()->cookie;

		$retour = '';

		// -------- Script ---------
		$retour .= '
		<script type="text/javascript">
			function criteriaType()
			{
				if ($("#id_criteria_type").val() == '.Oleapromo::CRITERIA_TYPE_PRODUCT_NUMBER.') {
					$(".criteria_products_number").css("display", "block");
					$(".criteria_products_amount").css("display", "none");
				} else if ($("#id_criteria_type").val() == '.Oleapromo::CRITERIA_TYPE_PRODUCT_AMOUNT.') {
					$(".criteria_products_number").css("display", "none");
					$(".criteria_products_amount").css("display", "block");
				}
			}
			function repetitions() {
				if ($("#criteria_repetitions_atleast").attr("checked"))
					$("#id_criteria_repetitions").val(1);
				if ($("#criteria_repetitions_every").attr("checked"))
					$("#id_criteria_repetitions").val(0);
				if ($("#criteria_repetitions_max").attr("checked"))
					$("#id_criteria_repetitions").val(2);
				if ($("#id_criteria_repetitions").val() < 2)
					$("#id_criteria_repetitions").css("visibility", "hidden");
				else
					$("#id_criteria_repetitions").css("visibility", "visible");
			}
			function manufacturersAndSuppliersCriteria() {
				if ($("#manufacturerBoxCriteria_none").attr("checked"))
					$(".manufacturerCriteriaLine").css("display", "none");
				else
					$(".manufacturerCriteriaLine").css("display", "");
				if ($("#supplierBoxCriteria_none").attr("checked"))
					$(".supplierCriteriaLine").css("display", "none");
				else
					$(".supplierCriteriaLine").css("display", "");
			}

			$(document).ready(function(){
				$("#id_criteria_type").change(function(){criteriaType();});
				$("#criteria_repetitions_atleast").change(function(){repetitions();});
				$("#criteria_repetitions_every").change(function(){repetitions();});
				$("#criteria_repetitions_max").change(function(){repetitions();});
				$("#manufacturerBoxCriteria_none").change(function(){manufacturersAndSuppliersCriteria();});
				$("#supplierBoxCriteria_none").change(function(){manufacturersAndSuppliersCriteria();});
				criteriaType();
				repetitions();
				manufacturersAndSuppliersCriteria();
			});
		</script>';

		// -------- Type ---------
		$retour .= '
			<div class="clear">&nbsp;</div>
			<label>'.$this->l('Criteria type:').' </label>
				<div class="margin-form">
					<select name="criteria_type" id="id_criteria_type">';
				$obj_criteria_type = (int)$this->getFieldValue($obj, 'criteria_type');
				foreach ($this->criteria_type_list as $k=>$v) {
					$selected = ($k == $obj_criteria_type) ?'SELECTED' :'';
					$retour .=  '<option value="'.$k.'" '.$selected.'>'.$v.'&nbsp;</option>';
				}
				$retour .=  '
					</select>
				</div>';

		// -------- Association type ---------
		$retour .= '
			<label>'.$this->l('Computed by:').' </label>
				<div class="margin-form">
					<select name="criteria_association_type" id="id_criteria_association_type">';
				$obj_criteria_association_type = (int)$this->getFieldValue($obj, 'criteria_association_type');
				foreach ($this->criteria_association_type_list as $k=>$v) {
					$selected = ($k == $obj_criteria_association_type) ?'SELECTED' :'';
					$retour .=  '<option value="'.$k.'" '.$selected.'>'.$v.'&nbsp;</option>';
				}
				$retour .=  '
					</select>
				</div>';

		// -------- Product number ---------
		$retour .= '
			<div class="clear criteria_products_number">&nbsp;</div>
			<label class="criteria_products_number" >'.$this->l('Products number:').' </label>
				<div class="margin-form criteria_products_number">
					<input type="text" size="10" name="criteria_products_number" value="'.(int)$this->getFieldValue($obj, 'criteria_products_number').'"/>
				</div>';

		// -------- Product amount ---------
		$retour .= '
			<div class="clear criteria_products_amount">&nbsp;</div>
			<label class="criteria_products_amount">'.$this->l('Products amount:').' </label>
				<div class="margin-form criteria_products_amount">
					<input type="text" size="10" name="criteria_products_amount" value="'.(float)($this->getFieldValue($obj, 'criteria_products_amount')).'" onKeyUp="javascript:this.value = this.value.replace(/,/g, \'.\'); " />
					&nbsp;<select id="criteria_id_currency" name="criteria_id_currency" style2="float:left;margin-left:10px;width:50px;" >';
			$obj_criteria_id_currency = (int)$this->getFieldValue($obj, 'criteria_id_currency');
			if ($obj_criteria_id_currency == 0)
				$obj_criteria_id_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT');
			foreach (Currency::getCurrencies() as $row) {
				if ((int)$row['id_currency'] == (int)Configuration::get('PS_CURRENCY_DEFAULT')) // For now, only default currency
					$retour .= '<option value="'.(int)$row['id_currency'].'" '.(($obj_criteria_id_currency == $row['id_currency']) ? 'selected="selected"' : '').'>'.$row['sign'].'&nbsp;</option>';
			}
			$retour .= '</select>
				</div>';

		// -------- With or without taxes ---------
		$retour .= '
			<label class="criteria_products_amount">'.$this->l('Amount computation:').' </label>
				<div class="margin-form criteria_products_amount">
					<input type="radio" name="criteria_amount_withtaxes" id="criteria_amount_withtaxes_on" value="1" '.($this->getFieldValue($obj, 'criteria_amount_withtaxes') ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_amount_withtaxes_on">'.$this->l('With Taxes').'</label>
					<input type="radio" name="criteria_amount_withtaxes" id="criteria_amount_withtaxes_off" value="0" '.(!$this->getFieldValue($obj, 'criteria_amount_withtaxes') ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_amount_withtaxes_off">'.$this->l('Without Taxes').'</label>
					<p>'.$this->l('Indicate if the amount must be computated with or without taxes').'</p>
				</div>';


		// -------- Repetitions ---------
		$retour .= '
			<div class="clear ">&nbsp;</div>
			<label class="criteria_repetitions">'.$this->l('Repetition:').' </label>
				<div class="margin-form ">
					<input type="radio" name="pseudo_repetion" id="criteria_repetitions_atleast" '.($this->getFieldValue($obj, 'criteria_repetitions')==1 ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_repetitions_atleast">'.$this->l('One time').'</label>
					<input type="radio" name="pseudo_repetion" id="criteria_repetitions_every" '.($this->getFieldValue($obj, 'criteria_repetitions')==0 ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_repetitions_every">'.$this->l('Every').'</label>
					<input type="radio" name="pseudo_repetion" id="criteria_repetitions_max"  '.($this->getFieldValue($obj, 'criteria_repetitions')>1 ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_repetitions_max">'.$this->l('Max').'</label>
					<input type="text" size="10" name="criteria_repetitions" id="id_criteria_repetitions" value="'.(int)$this->getFieldValue($obj, 'criteria_repetitions').'"/>
					<p>'.$this->l('Indicates if the amount/number must be detected only one time or as much as possible or a predefined number of time').'</p>
				</div>';

		// -------- Products with reduction ---------
		$retour .= '
			<div class="clear ">&nbsp;</div>
			<label>'.$this->l('Products with reduction :').' </label>
				<div class="margin-form">
					<input type="radio" name="criteria_product_with_reductions" id="criteria_product_with_reductions_on" value="1" '.($this->getFieldValue($obj, 'criteria_product_with_reductions') ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_product_with_reductions_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="criteria_product_with_reductions" id="criteria_product_with_reductions_off" value="0" '.(!$this->getFieldValue($obj, 'criteria_product_with_reductions') ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_product_with_reductions_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p>'.$this->l('Includes or not products that have reduction').'</p>
				</div>';

		// -------- Products with quantity price ---------
		if (version_compare('1.4', _PS_VERSION_) <= 0) {
		$retour .= '
			<div class="clear ">&nbsp;</div>
			<label>'.$this->l('Products with quantity price :').' </label>
				<div class="margin-form">
					<input type="radio" name="criteria_product_with_quantity_price" id="criteria_product_with_quantity_price_on" value="1" '.($this->getFieldValue($obj, 'criteria_product_with_quantity_price') ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_product_with_quantity_price_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="criteria_product_with_quantity_price" id="criteria_product_with_quantity_price_off" value="0" '.(!$this->getFieldValue($obj, 'criteria_product_with_quantity_price') ? 'checked="checked" ' : '').'/>
					<label class="t" for="criteria_product_with_quantity_price_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p>'.$this->l('Includes or not products for which a quantity price applies').$this->msg_for_patch_price_quantity.'</p>
				</div>';
		}

		// -------- Categories ---------
		$retour .=  '
				<label>'.$this->l('Related categories:').' </label>
					<div class="margin-form">
							<table cellspacing="0" cellpadding="0" class="table" style="">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'categoryBoxCriteria[]\', this.checked)" /></th>
										<th>'.$this->l('ID').'</th>
										<th>'.$this->l('Name').'</th>
									</tr>';
		$index = array();
		$categories = Category::getCategories(intval($cookie->id_lang), false);
		$categoriesNotOrdered = Category::getCategories(intval($cookie->id_lang), false, false);
		$indexedCategories = $obj->getCriteriaCategories();
		if (count($indexedCategories) == 0){
			$indexedCategories = array();
			foreach ($categoriesNotOrdered as $cat)
				$indexedCategories[] = $cat['id_category'];
		}
		if (version_compare (_PS_VERSION_, '1.4') < 0)
			//$retour .= $this->recurseCategoryForInclude_ps13('categoryBoxCriteria', $indexedCategories, $categories, $categories[0][1], 1);
			$retour .= $this->recurseCategoryForInclude_ps14('categoryBoxCriteria', (int)(Tools::getValue($this->identifier)), $indexedCategories, $categories, $categories[0][1], 1, $obj->id);
		else
			$retour .= $this->recurseCategoryForInclude_ps14('categoryBoxCriteria', (int)(Tools::getValue($this->identifier)), $indexedCategories, $categories, $categories[0][1], 1, $obj->id);
		$retour .=  '</table>
			<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Categories to which products should belong to').'</p>
			</div>';

		// --------- Manufacturers ----------------
		$manufacturers = (array)Manufacturer::getManufacturers();
		$configured_manufacturers = $obj->getCriteriaManufacturers();
		$retour .=  '
				<label>'.$this->l('Related manufacturers:').' </label>
					<div class="margin-form">';
		if (count($manufacturers)) {
			$retour .= '	<table cellspacing="0" cellpadding="0" class="table" style="">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'manufacturerBoxCriteria[]\', this.checked)" /></th>
										<th>'.$this->l('ID').'</th>
										<th>'.$this->l('Name').'</th>
									</tr>';
			$irow = 0;
			$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').' ">
									<td><input type="checkbox" name="manufacturerBoxCriteriaNone" class="" id="manufacturerBoxCriteria_none" value="none" '.((in_array(0, $configured_manufacturers) OR (!isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>&nbsp</td>
									<td><label for="manufacturerBoxCriteria_0" class="t">'.$this->l('-- no manufacturers filter --').'</label></td>
								</tr>';
			foreach ($manufacturers as $manufacturer) {
				$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').' manufacturerCriteriaLine">
									<td><input type="checkbox" name="manufacturerBoxCriteria[]" class="manufacturerBoxCriteria" id="manufacturerBoxCriteria_'.$manufacturer['id_manufacturer'].'" value="'.$manufacturer['id_manufacturer'].'" '.((in_array($manufacturer['id_manufacturer'], $configured_manufacturers) AND (isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>'.$manufacturer['id_manufacturer'].'</td>
									<td><label for="manufacturerBoxCriteria_'.$manufacturer['id_manufacturer'].'" class="t">'.$manufacturer['name'].'</label></td>
								</tr>';
			}
			$retour .= '</table>
				<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Manufacturers from which the product must be from').'</p>';
		} else {
			$retour .= $this->l('None').'<input type="hidden" value="none" name="manufacturerBoxCriteriaNone" />';
		}
		$retour .= '</div>';


		// ---------- Suppliers --------------------
		$suppliers = (array)Supplier::getSuppliers();
		$configured_suppliers = $obj->getCriteriaSuppliers();
		$retour .=  '
				<label>'.$this->l('Related suppliers:').' </label>
					<div class="margin-form">';
		if (count($suppliers)) {
			$retour .= '	<table cellspacing="0" cellpadding="0" class="table" style="">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'supplierBoxCriteria[]\', this.checked)" /></th>
										<th>'.$this->l('ID').'</th>
										<th>'.$this->l('Name').'</th>
									</tr>';
			$irow = 0;
			$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
									<td><input type="checkbox" name="supplierBoxCriteriaNone" class="" id="supplierBoxCriteria_none" value="none" '.((in_array(0, $configured_suppliers) OR (!isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>&nbsp</td>
									<td><label for="supplierBoxCriteria_0" class="t">'.$this->l('-- no suppliers filter --').'</label></td>
								</tr>';
			foreach ($suppliers as $supplier) {
				$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').' supplierCriteriaLine">
									<td><input type="checkbox" name="supplierBoxCriteria[]" class="supplierBoxCriteria" id="supplierBoxCriteria_'.$supplier['id_supplier'].'" value="'.$supplier['id_supplier'].'" '.((in_array($supplier['id_supplier'], $configured_suppliers) AND (isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>'.$supplier['id_supplier'].'</td>
									<td><label for="supplierBoxCriteria_'.$supplier['id_supplier'].'" class="t">'.$supplier['name'].'</label></td>
								</tr>';
			}
			$retour .= '</table>
				<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Supppliers from which the product must be from').'</p>';
		} else {
			$retour .= $this->l('None').'<input type="hidden" value="none" name="supplierBoxCriteriaNone" />';
		}
		$retour .= '</div>';


		return $retour;
	}

	public function _getAttributionTabHtml($obj) {
		$cookie = Context::getContext()->cookie;

		$retour = '';

		// -------- Script ---------
		$retour .= '
		<script type="text/javascript">
			function attributionType()
			{
				if ($("#id_attribution_type").val() == '.Oleapromo::ATTRIBUTION_TYPE_PERCENT.') {
					$(".attribution_amount").css("display", "none");
					$(".attribution_amount_prices_range").css("display", "none");
					$(".attribution_fdp").css("display", "none");
					$(".attribution_percent").css("display", "");
					selectionProductCriteria();
					selectionSameCategory();
					selectionSameManufacturer();
					selectionSameSupplier();
				} else if ($("#id_attribution_type").val() == '.Oleapromo::ATTRIBUTION_TYPE_AMOUNT.') {
					$(".attribution_percent").css("display", "none");
					$(".attribution_amount_prices_range").css("display", "none");
					$(".attribution_fdp").css("display", "none");
					$(".attribution_amount").css("display", "");
					selectionProductCriteria();
					selectionSameCategory();
					selectionSameManufacturer();
					selectionSameSupplier();
				} else if ($("#id_attribution_type").val() == '.Oleapromo::ATTRIBUTION_TYPE_AMOUNT_PRICES_RANGE.') {
					$(".attribution_percent").css("display", "none");
					$(".attribution_amount").css("display", "none");
					$(".attribution_fdp").css("display", "none");
					$(".attribution_amount_prices_range").css("display", "");
				} else if ($("#id_attribution_type").val() == '.Oleapromo::ATTRIBUTION_TYPE_FDP.') {
					$(".attribution_percent").css("display", "none");
					$(".attribution_amount").css("display", "none");
					$(".attribution_amount_prices_range").css("none");
					$(".attribution_fdp").css("display", "");
				} else if ($("#id_attribution_type").val() == '.Oleapromo::ATTRIBUTION_TYPE_FINAL_PRICE.') {
					$(".attribution_percent").css("display", "none");
					$(".attribution_amount_prices_range").css("display", "none");
					$(".attribution_fdp").css("display", "none");
					$(".attribution_amount").css("display", "");
					selectionProductCriteria();
					selectionSameCategory();
					selectionSameManufacturer();
					selectionSameSupplier();
				}
			}

			function selectionSameCategory() {
				if ($("#attribution_categories_of_criteria_on").attr("checked"))
					$(".attribution_categories_of_criteria").slideUp(300, function() {$(this).css("display", "none");});
				else
					$(".attribution_categories_of_criteria").slideDown(300);
			}

			function selectionProductCriteria() {
				if ($("#attribution_products_of_criteria_on").attr("checked"))
					$(".attribution_products_of_criteria").slideUp(300, function() {$(this).css("display", "none");});
				else {
					$(".attribution_products_of_criteria").slideDown(300);
					manufacturersAndSuppliersAttribution();
					selectionSameManufacturer();
					selectionSameSupplier();
				}
			}

			function selectionSameManufacturer() {
				if ($("#attribution_manufacturers_of_criteria_on").attr("checked"))
					$(".attribution_manufacturers_of_criteria").slideUp(300, function() {$(this).css("display", "none");});
				else
					$(".attribution_manufacturers_of_criteria").slideDown(300);
			}

			function selectionSameSupplier() {
				if ($("#attribution_suppliers_of_criteria_on").attr("checked"))
					$(".attribution_suppliers_of_criteria").slideUp(300, function() {$(this).css("display", "none");});
				else
					$(".attribution_suppliers_of_criteria").slideDown(300);
			}

			function manufacturersAndSuppliersAttribution() {
				if ($("#manufacturerBoxAttribution_none").attr("checked"))
					$(".manufacturerAttributionLine").css("display", "none");
				else
					$(".manufacturerAttributionLine").css("display", "");
				if ($("#supplierBoxAttribution_none").attr("checked"))
					$(".supplierAttributionLine").css("display", "none");
				else
					$(".supplierAttributionLine").css("display", "");
			}

			$(document).ready(function(){
				$("#id_attribution_type").change(function(){attributionType();});
				attributionType();
				$("#attribution_products_of_criteria_on").change(function(){selectionProductCriteria();});
				$("#attribution_products_of_criteria_off").change(function(){selectionProductCriteria();});
				$("#attribution_categories_of_criteria_on").change(function(){selectionSameCategory();});
				$("#attribution_categories_of_criteria_off").change(function(){selectionSameCategory();});
				$("#attribution_manufacturers_of_criteria_on").change(function(){selectionSameManufacturer();});
				$("#attribution_manufacturers_of_criteria_off").change(function(){selectionSameManufacturer();});
				$("#attribution_suppliers_of_criteria_on").change(function(){selectionSameSupplier();});
				$("#attribution_suppliers_of_criteria_off").change(function(){selectionSameSupplier();});
				$("#manufacturerBoxAttribution_none").change(function(){manufacturersAndSuppliersAttribution();});
				$("#supplierBoxAttribution_none").change(function(){manufacturersAndSuppliersAttribution();});
				selectionProductCriteria();
				manufacturersAndSuppliersAttribution();
				selectionSameManufacturer();
				selectionSameSupplier();
			});
		</script>';

		// -------- Type ---------
		$retour .= '
			<div class="clear">&nbsp;</div>
			<label>'.$this->l('Attribution type:').' </label>
				<div class="margin-form">
					<select name="attribution_type" id="id_attribution_type">';
				$obj_attribution_type = (int)$this->getFieldValue($obj, 'attribution_type');
				foreach ($this->attribution_type_list as $k=>$v) {
					$selected = ($k == $obj_attribution_type) ?'SELECTED' :'';
					$retour .=  '<option value="'.$k.'" '.$selected.'>'.$v.'&nbsp;</option>';
				}
				$retour .=  '
					</select>
				</div>';

		// -------- Discount percent ---------
		$retour .= '
			<label class="attribution_percent " >'.$this->l('Discount percent:').' </label>
				<div class="margin-form attribution_percent  ">
					<input type="text" size="10" name="attribution_percent" value="'.(float)$this->getFieldValue($obj, 'attribution_percent').'"/>
				</div>';

		// -------- Discount amount ---------
		$retour .= '
			<label class="attribution_amount attribution_amount_prices_range">'.$this->l('Amount:').' </label>
				<div class="margin-form attribution_amount attribution_amount_prices_range">
					<input type="text" size="10" name="attribution_amount" value="'.(float)($this->getFieldValue($obj, 'attribution_amount')).'" onKeyUp="javascript:this.value = this.value.replace(/,/g, \'.\'); " />
					&nbsp;<select id="attribution_id_currency" name="attribution_id_currency" style2="float:left;margin-left:10px;width:50px;" >';
			$obj_attribution_id_currency = (int)$this->getFieldValue($obj, 'attribution_id_currency');
			if ($obj_attribution_id_currency == 0)
				$obj_attribution_id_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT');
			foreach (Currency::getCurrencies() as $row)
				if ($row['id_currency'] == (int)Configuration::get('PS_CURRENCY_DEFAULT'))
					$retour .= '<option value="'.(int)$row['id_currency'].'" '.(($obj_attribution_id_currency == $row['id_currency']) ? 'selected="selected"' : '').'>'.$row['sign'].'&nbsp;</option>';
		$retour .= '</select>
				</div>';

		// -------- Amount taxes ---------
		$retour .= '
			<label class="attribution_amount attribution_amount_prices_range">'.$this->l('Amount taxes included:').' </label>
				<div class="margin-form attribution_amount attribution_amount_prices_range">
					<input type="radio" name="attribution_amount_withtaxes" id="attribution_amount_withtaxes_on" value="1" '.($this->getFieldValue($obj, 'attribution_amount_withtaxes') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_amount_withtaxes_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="attribution_amount_withtaxes" id="attribution_amount_withtaxes_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_amount_withtaxes') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_amount_withtaxes_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p>'.$this->l('Indicates if the discount amount includes or not the taxes').'</p>
				</div>';

		// -------- MAX amount ---------
		$retour .= '
			<div class="clear ">&nbsp;</div>
			<label class="">'.$this->l('Voucher max amount:').' </label>
				<div class="margin-form ">
					<input type="text" size="10" name="attribution_maxamount" value="'.(float)($this->getFieldValue($obj, 'attribution_maxamount')).'" onKeyUp="javascript:this.value = this.value.replace(/,/g, \'.\'); " />
					&nbsp;<select id="attribution_maxamount_id_currency" name="attribution_maxamount_id_currency" style2="float:left;margin-left:10px;width:50px;" >';
			$obj_attribution_maxamount_id_currency = (int)$this->getFieldValue($obj, 'attribution_maxamount_id_currency');
			if ($obj_attribution_maxamount_id_currency == 0)
				$obj_attribution_maxamount_id_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT');
			foreach (Currency::getCurrencies() as $row)
				if ($row['id_currency'] == (int)Configuration::get('PS_CURRENCY_DEFAULT'))
					$retour .= '<option value="'.(int)$row['id_currency'].'" '.(($obj_attribution_maxamount_id_currency == $row['id_currency']) ? 'selected="selected"' : '').'>'.$row['sign'].'&nbsp;</option>';
		$retour .= '</select>
					<p>'.$this->l('Maximum amount the generated voucher can have. Let 0 for no limitation.').'</p>
				</div>';

		// -------- Max Amount taxes ---------
		$retour .= '
			<label class=" ">'.$this->l('Max amount taxes included:').' </label>
				<div class="margin-form ">
					<input type="radio" name="attribution_maxamount_withtaxes" id="attribution_maxamount_withtaxes_on" value="1" '.($this->getFieldValue($obj, 'attribution_maxamount_withtaxes') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_maxamount_withtaxes_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="attribution_maxamount_withtaxes" id="attribution_maxamount_withtaxes_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_maxamount_withtaxes') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_maxamount_withtaxes_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p>'.$this->l('Indicates if the maximum amount includes or not the taxes').'</p>
				</div>';

		// -------- Nb of products ---------
		$retour .= '
			<div class="clear attribution_percent attribution_amount">&nbsp;</div>
			<label class=" attribution_percent attribution_amount">'.$this->l('Number of impacted products:').' </label>
				<div class="margin-form attribution_percent attribution_amount">
					<input type="text" size="10" name="attribution_nb_impacted_products" value="'.(int)$this->getFieldValue($obj, 'attribution_nb_impacted_products').'"/>
					<p>'.$this->l('0 for all products, otherwise this is the N products the less costly').'</p>
				</div>';

		// -------- Block cart lines ---------
		$retour .= '
			<label class=" ">'.$this->l('Block cart line:').' </label>
				<div class="margin-form ">
					<input type="radio" name="attribution_block_cart_line" id="attribution_block_cart_line_on" value="1" '.($this->getFieldValue($obj, 'attribution_block_cart_line') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_block_cart_line_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="attribution_block_cart_line" id="attribution_block_cart_line_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_block_cart_line') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_block_cart_line_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p>'.$this->l('If activated, when this rule computes a reduction on at least one product of a cart line,').'<br>'.$this->l('the other products of this line can\'t have a promotion from another maxi-promo rule.').'</p>
				</div>';

		// -------- Nb cart lines required ---------
		$retour .= '
			<div class="clear ">&nbsp;</div>
			<label class="  ">'.$this->l('Number of cart lines required:').' </label>
				<div class="margin-form  ">
					<input type="text" size="10" name="attribution_nb_cart_lines_required" value="'.(int)$this->getFieldValue($obj, 'attribution_nb_cart_lines_required').'"/>
					<p>'.$this->l('Reduction is computed if number of cart lines is higher than this number.').'<br>'.$this->l('In such case, it is computed based on this number of cart lines with highest price.').'<br>'.$this->l('Set to 0 for computation based on all lines (no requirement).').'</p>
				</div>';

		// -------- Products with reduction ---------
		$retour .= '
			<label class=" attribution_percent attribution_amount attribution_products_of_criteria ">'.$this->l('Products with reduction :').' </label>
				<div class="margin-form attribution_percent attribution_amount attribution_products_of_criteria ">
					<input type="radio" name="attribution_product_with_reductions" id="attribution_product_with_reductions_on" value="1" '.($this->getFieldValue($obj, 'attribution_product_with_reductions') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_product_with_reductions_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="attribution_product_with_reductions" id="attribution_product_with_reductions_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_product_with_reductions') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_product_with_reductions_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p>'.$this->l('Includes or not products with reduction for promotion amount computation').'</p>
				</div>';

		// -------- Products with quantity price ---------
		if (version_compare('1.4', _PS_VERSION_) <= 0) {
		$retour .= '
			<div class="clear attribution_percent attribution_amount attribution_products_of_criteria ">&nbsp;</div>
			<label class="attribution_percent attribution_amount attribution_products_of_criteria ">'.$this->l('Products with quantity price :').' </label>
				<div class="margin-form attribution_percent attribution_amount attribution_products_of_criteria ">
					<input type="radio" name="attribution_product_with_quantity_price" id="attribution_product_with_quantity_price_on" value="1" '.($this->getFieldValue($obj, 'attribution_product_with_quantity_price') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_product_with_quantity_price_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="attribution_product_with_quantity_price" id="attribution_product_with_quantity_price_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_product_with_quantity_price') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_product_with_quantity_price_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p>'.$this->l('Includes or not products for which a quantity price applies').$this->msg_for_patch_price_quantity.'</p>
				</div>';
		}

		// -------- Products of criteria ---------
		$retour .= '
			<div class="clear attribution_percent attribution_amount">&nbsp;<HR /></div>
			<label class=" attribution_percent attribution_amount" >'.$this->l('Same products as criterias:').' </label>
				<div  class="margin-form attribution_percent attribution_amount">
					<input type="radio" name="attribution_products_of_criteria" id="attribution_products_of_criteria_on" value="1" '.($this->getFieldValue($obj, 'attribution_products_of_criteria') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_products_of_criteria_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="attribution_products_of_criteria" id="attribution_products_of_criteria_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_products_of_criteria') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_products_of_criteria_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p class="clear">'.$this->l('Applies discounts on the products retrieved by the criteria.').'</p>
				</div>';

		// -------- Same categories as criteria ---------
		$retour .= '
			<div class="clear attribution_products_of_criteria attribution_percent attribution_amount">&nbsp;</div>
			<label class=" attribution_products_of_criteria attribution_percent attribution_amount" >'.$this->l('Same categories as criteria:').' </label>
				<div  class="margin-form attribution_products_of_criteria attribution_percent attribution_amount">
					<input type="radio" name="attribution_categories_of_criteria" id="attribution_categories_of_criteria_on" value="1" '.($this->getFieldValue($obj, 'attribution_categories_of_criteria') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_categories_of_criteria_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="attribution_categories_of_criteria" id="attribution_categories_of_criteria_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_categories_of_criteria') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_categories_of_criteria_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p class="clear">'.$this->l('Applies discount on same categories than criteria one').'</p>
				</div>';

		// -------- Categories ---------
		$retour .=  '
				<label class="attribution_products_of_criteria attribution_categories_of_criteria attribution_percent attribution_amount">'.$this->l('Related categories:').' </label>
					<div class="margin-form attribution_products_of_criteria attribution_categories_of_criteria attribution_percent attribution_amount">
							<table cellspacing="0" cellpadding="0" class="table" style="">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'categoryBoxAttribution[]\', this.checked)" /></th>
										<th>'.$this->l('ID').'</th>
										<th>'.$this->l('Name').'</th>
									</tr>';
		$index = array();
		$categories = Category::getCategories(intval($cookie->id_lang), false);
		$categoriesNotOrdered = Category::getCategories(intval($cookie->id_lang), false, false);
		$indexedCategories = $obj->getAttributionCategories();
		if (count($indexedCategories) == 0){
			$indexedCategories = array();
			foreach ($categoriesNotOrdered as $cat)
				$indexedCategories[] = $cat['id_category'];
		}

		if (version_compare (_PS_VERSION_, '1.4') < 0)
			//$retour .= $this->recurseCategoryForInclude_ps13('categoryBoxAttribution', $indexedCategories, $categories, $categories[0][1], 1);
			$retour .= $this->recurseCategoryForInclude_ps14('categoryBoxAttribution', (int)(Tools::getValue($this->identifier)), $indexedCategories, $categories, $categories[0][1], 1, $obj->id);
		else
			$retour .= $this->recurseCategoryForInclude_ps14('categoryBoxAttribution', (int)(Tools::getValue($this->identifier)), $indexedCategories, $categories, $categories[0][1], 1, $obj->id);
		$retour .=  '</table>
			<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Categories to which products should belong to').'</p>
			</div>';

		// -------- Same manufacturers as criteria ---------
		$retour .= '
			<div class="clear attribution_products_of_criteria attribution_percent attribution_amount">&nbsp;</div>
			<label class=" attribution_products_of_criteria attribution_percent attribution_amount" >'.$this->l('Same manufacturers as criteria:').' </label>
				<div  class="margin-form attribution_products_of_criteria attribution_percent attribution_amount">
					<input type="radio" name="attribution_manufacturers_of_criteria" id="attribution_manufacturers_of_criteria_on" value="1" '.($this->getFieldValue($obj, 'attribution_manufacturers_of_criteria') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_manufacturers_of_criteria_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="attribution_manufacturers_of_criteria" id="attribution_manufacturers_of_criteria_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_manufacturers_of_criteria') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_manufacturers_of_criteria_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p class="clear">'.$this->l('Applies discount on same manufacturers than criteria one').'</p>
				</div>';

		// --------- Manufacturers ----------------
		$manufacturers = (array)Manufacturer::getManufacturers();
		$configured_manufacturers = $obj->getAttributionManufacturers();
		$retour .=  '
				<label class=" attribution_products_of_criteria attribution_percent attribution_amount attribution_manufacturers_of_criteria" >'.$this->l('Related manufacturers:').' </label>
					<div class="margin-form attribution_products_of_criteria attribution_percent attribution_amount attribution_manufacturers_of_criteria">';
		if (count($manufacturers)) {
			$retour .= '	<table cellspacing="0" cellpadding="0" class="table" style="">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'manufacturerBoxAttribution[]\', this.checked)" /></th>
										<th>'.$this->l('ID').'</th>
										<th>'.$this->l('Name').'</th>
									</tr>';
			$irow = 0;
			$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').' ">
									<td><input type="checkbox" name="manufacturerBoxAttributionNone" class="" id="manufacturerBoxAttribution_none" value="none" '.((in_array(0, $configured_manufacturers) OR (!isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>&nbsp</td>
									<td><label for="manufacturerBoxAttribution_0" class="t">'.$this->l('-- no manufacturers filter --').'</label></td>
								</tr>';
			foreach ($manufacturers as $manufacturer) {
				$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').' manufacturerAttributionLine">
									<td><input type="checkbox" name="manufacturerBoxAttribution[]" class="manufacturerBoxAttribution" id="manufacturerBoxAttribution_'.$manufacturer['id_manufacturer'].'" value="'.$manufacturer['id_manufacturer'].'" '.((in_array($manufacturer['id_manufacturer'], $configured_manufacturers) AND (isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>'.$manufacturer['id_manufacturer'].'</td>
									<td><label for="manufacturerBoxAttribution_'.$manufacturer['id_manufacturer'].'" class="t">'.$manufacturer['name'].'</label></td>
								</tr>';
			}
			$retour .= '</table>
				<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Manufacturers from which the product must be from').'</p>';
		} else {
			$retour .= $this->l('None').'<input type="hidden" value="manufacturerBoxAttributionNone" name="none" />';
		}
		$retour .= '</div>';


		// -------- Same suppliers as criteria ---------
		$retour .= '
			<div class="clear attribution_products_of_criteria attribution_percent attribution_amount ">&nbsp;</div>
			<label class=" attribution_products_of_criteria attribution_percent attribution_amount" >'.$this->l('Same suppliers as criteria:').' </label>
				<div  class="attribution_products_of_criteria margin-form attribution_percent attribution_amount">
					<input type="radio" name="attribution_suppliers_of_criteria" id="attribution_suppliers_of_criteria_on" value="1" '.($this->getFieldValue($obj, 'attribution_suppliers_of_criteria') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_suppliers_of_criteria_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="attribution_suppliers_of_criteria" id="attribution_suppliers_of_criteria_off" value="0" '.(!$this->getFieldValue($obj, 'attribution_suppliers_of_criteria') ? 'checked="checked" ' : '').'/>
					<label class="t" for="attribution_suppliers_of_criteria_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p class="clear">'.$this->l('Applies discount on same suppliers than criteria one').'</p>
				</div>';

		// ---------- Suppliers --------------------
		$suppliers = (array)Supplier::getSuppliers();
		$configured_suppliers = $obj->getAttributionSuppliers();
		$retour .=  '
				<label class=" attribution_products_of_criteria attribution_percent attribution_amount attribution_suppliers_of_criteria" >'.$this->l('Related suppliers:').' </label>
					<div class="margin-form attribution_products_of_criteria attribution_percent attribution_amount attribution_suppliers_of_criteria">';
		if (count($suppliers)) {
			$retour .= '	<table cellspacing="0" cellpadding="0" class="table" style="">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'supplierBoxAttribution[]\', this.checked)" /></th>
										<th>'.$this->l('ID').'</th>
										<th>'.$this->l('Name').'</th>
									</tr>';
			$irow = 0;
			$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
									<td><input type="checkbox" name="supplierBoxAttributionNone" class="" id="supplierBoxAttribution_none" value="none" '.((in_array(0, $configured_suppliers) OR (!isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>&nbsp</td>
									<td><label for="supplierBoxAttribution_0" class="t">'.$this->l('-- no suppliers filter --').'</label></td>
								</tr>';
			foreach ($suppliers as $supplier) {
				$retour .= '
								<tr class="'.($irow++ % 2 ? 'alt_row' : '').' supplierAttributionLine">
									<td><input type="checkbox" name="supplierBoxAttribution[]" class="supplierBoxAttribution" id="supplierBoxAttribution_'.$supplier['id_supplier'].'" value="'.$supplier['id_supplier'].'" '.((in_array($supplier['id_supplier'], $configured_suppliers) AND (isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
									<td>'.$supplier['id_supplier'].'</td>
									<td><label for="supplierBoxCriteria_'.$supplier['id_supplier'].'" class="t">'.$supplier['name'].'</label></td>
								</tr>';
			}
			$retour .= '</table>
				<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Supppliers from which the product must be from').'</p>';
		} else {
			$retour .= $this->l('None').'<input type="hidden" value="none" name="supplierBoxAttributionNone" />';
		}
		$retour .= '</div>';

		$retour .= '
			<div class="clear  attribution_fdp">&nbsp;</div>
			<label class=" attribution_fdp" >'.$this->l('Applicable to zones:').' </label>
			<div class="margin-form attribution_fdp">';
					$promo_zones = $obj->getZonesFDP();
					$promo_zones_ids = array();
					if (is_array($promo_zones))
						foreach($promo_zones as $promo_zone)
							$promo_zones_ids[] = $promo_zone;

					$zones = Zone::getZones(false);
					foreach ($zones AS $zone)
						$retour .= '<input type="checkbox" id="zone_'.$zone['id_zone'].'" name="zones_fdp[]" value="'.$zone['id_zone'].'" '.
							Tools::getValue('zone_'.$zone['id_zone'], (in_array($zone['id_zone'], $promo_zones_ids) ? ' checked="checked"' : '')).'>
							<label class="t" for="zone_'.$zone['id_zone'].'"> <b>'.$zone['name'].'</b></label><br />';

					$retour .= '<p>'.$this->l('The zone to which the port is to be offered').'</p>
			</div>';

		$retour .= '
			<div class="clear  attribution_fdp">&nbsp;</div>
			<label class=" attribution_fdp" >'.$this->l('Applicable to carriers:').' </label>
			<div class="margin-form attribution_fdp">';
					$promo_carriers = $obj->getCarriersFDP();
					$promo_carriers_ids = array();
					if (is_array($promo_carriers))
						foreach($promo_carriers as $promo_carrier)
							$promo_carriers_ids[] = $promo_carrier;

					$carriers = Carrier::getCarriers(Context::getContext()->cookie->id_lang, true, false, false, null, Carrier::ALL_CARRIERS);
					foreach ($carriers AS $carrier)
						$retour .= '<input type="checkbox" id="carrier_fdp_'.$carrier['id_reference'].'" name="carriers_fdp[]" value="'.$carrier['id_reference'].'" '.
							Tools::getValue('carriers_fdp_'.$carrier['id_reference'], (in_array($carrier['id_reference'], $promo_carriers_ids) ? ' checked="checked"' : '')).'>
							<label class="t" for="carrier_fdp_'.$carrier['id_reference'].'"> <b>'.$carrier['name'].'</b></label><br />';

					$retour .= '<p>'.$this->l('The carriers to which the port is to be offered').'</p>
			</div>';
					return $retour;
	}

	public function _getCommunicationTabHtml($obj) {
		$defaultLanguage = intval(Configuration::get('PS_LANG_DEFAULT'));
		$languages = Language::getLanguages();

		$tags = array(
			'#NT#' => $this->l('Number Total of products implies in the promotion'),
			'#NPR#' => $this->l('Number of Products with Reduced price'),
			'#NPF#' => $this->l('Number of Products at Full price'),
			'#RM#' => $this->l('Reduction aMount'),
			'#R%0#' => $this->l('Reduction percent, without decimal'),
			'#R%1#' => $this->l('Reduction percent, 1 deciaml'),
			'#R%2#' => $this->l('Reduction percent, 2 decimal'),
			'#PB#' => $this->l('Price Base'),
			'#PR#' => $this->l('Price Reduced'),
			'#PF#' => $this->l('Price Final'),
			'#HD#' => $this->l('HiDden, equal "hidden" if promotion is not compatible with tags'),
			 );

		$retour = '';
		$retour .= '<P>'.$this->l('Tags may be used in the following hook text').'<br />'
				.$this->l('Theses tags are available only for promotion where :').'<br />'
				.'&nbsp&nbsp&nbsp&nbsp-&nbsp'.$this->l('Criteria is by product number, applicable by product or attributes').'<br />'
				.'&nbsp&nbsp&nbsp&nbsp-&nbsp'.$this->l('Amount is computed on same products than criteria, either in percentage or amount')
				.'</P>';
		$retour .= '<div class="margin-form"><table class="table">';
		foreach ($tags as $k=>$t)
			$retour .= '<tr><td>'.$k.'</td><td>'.$t.'</td></tr>';
		$retour .= '</table></div>';
		$retour .= '  <div class="clear">&nbsp;</div>
				<label>'.$this->l('Product extra right hook').' </label>
				<div class="margin-form">';
				foreach ($languages as $language)
				$retour .= '
					<div id="communication_extra_right_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">
						<textarea class="rte" name="communication_extra_right_'.$language['id_lang'].'" rows="5" cols="40">'.htmlentities($this->getFieldValue($obj, 'communication_extra_right', intval($language['id_lang'])), ENT_COMPAT, 'UTF-8').'</textarea>
					</div>';
				$retour .= $this->displayFlags($languages, $defaultLanguage, 'communication_extra_right', 'communication_extra_right', true);
				$retour .= '&nbsp;</div>';

		$retour .= '  <div class="clear">&nbsp;</div>
				<label>'.$this->l('Product footer hook').' </label>
				<div class="margin-form">';
				foreach ($languages as $language)
				$retour .= '
					<div id="communication_product_footer_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">
						<textarea class="rte" name="communication_product_footer_'.$language['id_lang'].'" rows="5" cols="40">'.htmlentities($this->getFieldValue($obj, 'communication_product_footer', intval($language['id_lang'])), ENT_COMPAT, 'UTF-8').'</textarea>
					</div>';
				$retour .= $this->displayFlags($languages, $defaultLanguage, 'communication_product_footer', 'communication_product_footer', true);
				$retour .= '&nbsp;</div>';

				return $retour;
	}

	public function _getMailTabHtml($obj) {
		$cookie = Context::getContext()->cookie;

		$defaultLanguage = intval(Configuration::get('PS_LANG_DEFAULT'));
		$languages = Language::getLanguages();

		$retour = '';

		$retour .= '
		<script type="text/javascript">
			function affectationType()
			{
				if ($("#sending_method").val() == '.Oleapromo::SENDING_METHOD_MAIL.') {
					$(".formail").slideDown(300);
				} else {
					$(".formail").slideUp(300);
				}
			};

			function selectionMailType () {
				thetype = $("#id_mail_discount_type").val();
				if (thetype==0 || thetype==3) {
					$("#mail_value_div").slideUp(300, function() {$(this).css("display", "none");});
				} else {
					$("#mail_value_div").slideDown(300);
					if (thetype==1) {
						$("#mail_percent_span").show();
						$("#mail_amount_span").hide();
					} else {
						$("#mail_percent_span").hide();
						$("#mail_amount_span").show();}
				}
			}

			function selectionMailSameCategory() {
				if ($("#mail_categories_of_criteria_on").attr("checked"))
					$(".mail_categories_of_criteria").slideUp(300, function() {$(this).css("display", "none");});
				else
					$(".mail_categories_of_criteria").slideDown(300);
			}

			$(document).ready(function(){
				$("#sending_method").change(function(){affectationType();});
				$("#id_mail_discount_type").change(function(){selectionMailType()});
				$("#mail_categories_of_criteria_on").change(function(){selectionMailSameCategory();});
				$("#mail_categories_of_criteria_off").change(function(){selectionMailSameCategory();});
				affectationType();
				selectionMailType();
				selectionMailSameCategory();
				if ($("#sending_method").val() != '.Oleapromo::SENDING_METHOD_MAIL.')
					$(".formail").css("display", "none");
			});
		</script>
		';

		// ----------- METHOD -------------------------
		$retour .=  '
				<div class="clear">&nbsp;</div>
				<label class="">'.$this->l('Discount affectation method:').' </label>
					<div class="margin-form ">
						<select name="sending_method" id="sending_method">';
			foreach ($this->sending_method_list as $k=>$n)
				$retour .= '<OPTION value="'.$k.'" '.(($obj->sending_method==$k) ?'SELECTED' :'').' >'.$n.'&nbsp;</OPTION>';
		$retour	.= '	</select>
					</div>
					<div class="formail">
					';
		// ----------- INFOS -------------------------
		$retour .= '<h4>'.$this->l('Voucher by e-mail').'</h4>
					<p>'.$this->l('The computated voucher won\'t be added to the cart, but sent by email').'<br/>
						'.$this->l('Enter here the informations related to this voucher').'<br />
						</p>';

		// ----------- TYPE -------------------------
		$retour .= '<label>'.$this->l('Type:').' </label>
				<div class="margin-form">
					<select name="mail_discount_type" id="id_mail_discount_type" onchange="selectionMailType()">
						';
		if (version_compare('1.5', _PS_VERSION_) <= 0) {
			$discountTypes = array(
					array('id_discount_type'=>Oleapromo::MAIL_DISCOUNT_TYPE_COMPUTED, 'name'=>$this->l('Computed amount')),
					array('id_discount_type'=>Oleapromo::MAIL_DISCOUNT_TYPE_AMOUNT,   'name'=>$this->l('Predefined amount')),
					array('id_discount_type'=>Oleapromo::MAIL_DISCOUNT_TYPE_PERCENT,  'name'=>$this->l('Percent')),
					array('id_discount_type'=>Oleapromo::MAIL_DISCOUNT_TYPE_FDP,      'name'=>$this->l('Free port')),
				);
		} else { // We keep as it, whereas it was not well coded
			$retour .= '<option value="0">'.$this->l('Computed amount').'</option>';
			$discountTypes = Discount::getDiscountTypes((int)($cookie->id_lang));
		}
		foreach ($discountTypes AS $discountType)
			$retour .= '<option value="'.(int)($discountType['id_discount_type']).'"'.
			(($this->getFieldValue($obj, 'mail_discount_type') == $discountType['id_discount_type']) ? ' selected="selected"' : '').'>'.$discountType['name'].'</option>';
		$retour .= '
				</select></div>
				<div id="mail_value_div" style2="display:none">
					<label>'.$this->l('Value').'</label>
					<div class="margin-form">
						<input style="float:left;width:80px" type="text" name="mail_discount_value" id="mail_discount_value" value="'.(float)($this->getFieldValue($obj, 'mail_discount_value')).'" onKeyUp="javascript:this.value = this.value.replace(/,/g, \'.\'); " />
						<select id="mail_amount_span"  style2="float:left;margin-left:10px;width:50px;display:none">';
			foreach (Currency::getCurrencies() as $row)
				if ($row['id_currency'] == (int)Configuration::get('PS_CURRENCY_DEFAULT'))
					$retour .= '			<option value="'.(int)$row['id_currency'].'" '.(($this->getFieldValue($obj, 'id_currency') == $row['id_currency']) ? 'selected="selected"' : '').'>'.$row['sign'].'&nbsp;</option>';
		$retour .= '			</select>
						<span id="mail_percent_span" style="margin-left:10px;display:none;float:left;font-size:12px;font-weight:bold;color:black"> %</span>
						<p class="clear">'.$this->l('Either the monetary amount or the %, depending on Type selected above').'</p>
					</div>
				</div>';

		// ----------- DESCRIPTION -------------------------
		$retour .= '<div class="clear">&nbsp;</div>
				<label>'.$this->l('Description:').' </label>
				<div class="margin-form">';
		foreach ($languages as $language)
			$retour .= '	<div id="mail_description_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">
						<input size="50" type="text" name="mail_description_'.$language['id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'mail_description', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'" />
						<span class="hint" name="help_box">'.$this->l('Invalid characters:').' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
						<p class="clear">'.$this->l('Description of the voucher sent to customer').'<br/>
						'.$this->l('Use the #V# tag to represent the percentage or the amount of the discount').'</p>
					</div>';
		$retour .= $this->displayFlags($languages, $defaultLanguage, 'mail_description', 'mail_description', true);
		$retour .= '&nbsp;</div>
		';

		// ----------- MESSAGE -------------------------
		$retour .= '<div class="clear">&nbsp;</div>
				<label>'.$this->l('Message:').' </label>
				<div class="margin-form">';
		foreach ($languages as $language)
			$retour .= '	<div id="mail_message_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').'; float: left;">
						<input size="80" type="text" name="mail_message_'.$language['id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'mail_message', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'" />
						<span class="hint" name="help_box">'.$this->l('Invalid characters:').' <>;=#{}</span><span class="hint-pointer">&nbsp;</span>
						<p class="clear">'.$this->l('Message set in the email to describe the discount.').'<br />'.
						$this->l('Give information regarding the conditions to obtain the discount, the dates...').'<br/>
						'.$this->l('Use the #V# tag to represent the percentage or the amount of the discount').'</p>
					</div>';
		$retour .= $this->displayFlags($languages, $defaultLanguage, 'mail_message', 'mail_message', true);
		$retour .= '&nbsp;</div>
		';

		// ------------- MINIMAL AMOUNT -------------------------
		$retour .= '<div class="clear">&nbsp;</div>
				<label>'.$this->l('Minimum amount').'</label>
				<div class="margin-form">
					<input type="text" size="15" name="mail_minimal" value="'.($this->getFieldValue($obj, 'mail_minimal') ? (float)($this->getFieldValue($obj, 'mail_minimal')) : '0').'" onkeyup="javascript:this.value = this.value.replace(/,/g, \'.\'); " />
					<p class="clear">'.$this->l('0 if not applicable').'</p>
				</div>';

		// ------------- CUMULATIVE -------------------------
		/* Not in 1.5/1.6
		$retour .= '
				<div class="margin-form">
					<p>
						<input type="checkbox" name="mail_cumulable"'.(($this->getFieldValue($obj, 'mail_cumulable') == 1) ? ' checked="checked"' : '').' id="mail_cumulable_on" value="1" />
						<label class="t" for="mail_cumulable_on"> '.$this->l('Cumulative with other vouchers').'</label>
					</p>
				</div>
				<div class="margin-form">
					<p>
						<input type="checkbox" name="mail_cumulable_reduction"'.(($this->getFieldValue($obj, 'mail_cumulable_reduction') == 1) ? ' checked="checked"' : '').' id="mail_cumulable_reduction_on" value="1" />
						<label class="t" for="mail_cumulable_reduction_on"> '.$this->l('Cumulative with price reductions').'</label>
					</p>
				</div>';
		*/

		// ------------- Extended Cart rule module -------------------------
		$oleaextcartrulemodule = Module::getInstanceByName('oleaextcartrulemodule');
		if (Validate::isLoadedObject($oleaextcartrulemodule) && $oleaextcartrulemodule->active)
		{
			$retour .= '<div class="clear">&nbsp;</div>
				<label>'.$this->l('ExtCartRule Family:').' </label>
				<div class="margin-form">
					<select name="mail_id_extcartrulefamily" id="mail_id_extcartrulefamily" >
						';
			foreach ($oleaextcartrulemodule->getOleaCartRuleFamiliesList() as $row)
				$retour .= '<OPTION value="'.$row['id_oleacartrulefamily'].'" '.(($this->getFieldValue($obj, 'mail_id_extcartrulefamily') == $row['id_oleacartrulefamily']) ? 'selected="selected"' : '').'>'.$row['name'].'&nbsp;</OPTION>';
			$retour .= '</SELECT>
				<p class="clear">'.$this->l('Specify the family group of the Extended Cart Rule module').'</p>
				</div>';
		}

		// -------- Date From ---------
		$mail_date_from = ($this->getFieldValue($obj, 'mail_date_from')<>'') ?$this->getFieldValue($obj, 'mail_date_from') :date('Y-m-d');
		$retour .= '
			<div class="clear ">&nbsp;</div>
			<label class="">'.$this->l('Start date:').' </label>
				<div class="margin-form ">
					<input type="radio" name="mail_date_from_of_order" id="mail_date_from_of_order_fixed" value="0" '.($this->getFieldValue($obj, 'mail_date_from_of_order')==0 ? 'checked="checked" ' : '').'/>
					<label class="t" for="mail_date_from_of_order_fixed">'.$this->l('Fixed date').'</label>
					<input type="text" size="10" name="mail_date_from" id="id_mail_date_from" value="'.htmlentities($mail_date_from, ENT_COMPAT, 'UTF-8').'"/>&nbsp;&nbsp;
					<input type="radio" name="mail_date_from_of_order" id="mail_date_from_of_order_same" value="1" '.($this->getFieldValue($obj, 'mail_date_from_of_order')==1 ? 'checked="checked" ' : '').'/>
					<label class="t" for="mail_date_from_of_order_same">'.$this->l('Date of order').'</label>
					<p>'.$this->l('Select the start date of the discount sent to the customer').'</p>
				</div>';

		// -------- Date To ---------
		$mail_date_to = ($this->getFieldValue($obj, 'mail_date_to')<>'') ?$this->getFieldValue($obj, 'mail_date_to') :date('Y-m-d', time()+(365*24*3600));
		$retour .= '
			<div class="clear ">&nbsp;</div>
			<label class="">'.$this->l('End date:').' </label>
				<div class="margin-form ">
					<input type="radio" name="mail_date_to_selector" value="fixed" id="id_mail_date_to_selector_fixed" '.($this->getFieldValue($obj, 'mail_validity_days')==0 ? 'checked="checked" ' : '').'/>
					<label class="t" for="mail_date_to_selector_fixed">'.$this->l('Fixed date').'</label>
					<input type="text" size="10" name="mail_date_to" id="id_mail_date_to" value="'.htmlentities($mail_date_to, ENT_COMPAT, 'UTF-8').'"/>&nbsp;&nbsp;
					<input type="radio" name="mail_date_to_selector" value="days" id="mail_date_to_selector_days" '.($this->getFieldValue($obj, 'mail_validity_days')<>0 ? 'checked="checked" ' : '').'/>
					<label class="t" for="mail_date_to_selector_days">'.$this->l('Nb days after start date').'</label>
					<input type="text" size="10" name="mail_validity_days" value="'.($this->getFieldValue($obj, 'mail_validity_days') ? (int)($this->getFieldValue($obj, 'mail_validity_days')) : '30').'"  />
					<p>'.$this->l('Select the end date of the discount or the number of validity days after the start date').'</p>
				</div>';

		// ------------- NB DAYS -------------------------
		/*
		$retour .= '<div class="clear">&nbsp;</div>
				<label>'.$this->l('Nb days of validity').'</label>
				<div class="margin-form">
					<input type="text" size="10" name="mail_validity_days" value="'.($this->getFieldValue($obj, 'mail_validity_days') ? (int)($this->getFieldValue($obj, 'mail_validity_days')) : '30').'"  />
					<p class="clear">'.$this->l('Number of days of validity of the voucher sent by mail').'</p>
				</div>';
		*/
		// -------- Categories ---------
		/*
		$retour .=  '
				<label class="   ">'.$this->l('Affected to categories:').' </label>
					<div class="margin-form    ">
							<table cellspacing="0" cellpadding="0" class="table" style="width: 29.5em;">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'categoryBoxMail[]\', this.checked)" /></th>
										<th>'.$this->l('ID').'</th>
										<th>'.$this->l('Name').'</th>
									</tr>';
		$index = array();
		$categories = Category::getCategories(intval($cookie->id_lang), false);
		$categoriesNotOrdered = Category::getCategories(intval($cookie->id_lang), false, false);
		$indexedCategories = array(); //$obj->getMailCategories();
		if (count($indexedCategories) == 0){
			$indexedCategories = array();
			foreach ($categoriesNotOrdered as $cat)
				$indexedCategories[] = $cat['id_category'];
		}
		if (version_compare (_PS_VERSION_, '1.4') < 0)
			//$retour .= $this->recurseCategoryForInclude_ps13('categoryBoxAttribution', $indexedCategories, $categories, $categories[0][1], 1);
			$retour .= $this->recurseCategoryForInclude_ps14('categoryBoxMail', (int)(Tools::getValue($this->identifier)), $indexedCategories, $categories, $categories[0][1], 1, $obj->id);
		else
			$retour .= $this->recurseCategoryForInclude_ps14('categoryBoxMail', (int)(Tools::getValue($this->identifier)), $indexedCategories, $categories, $categories[0][1], 1, $obj->id);
		$retour .=  '</table>
			<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Categories to which the new voucher applies').'</p>
			</div>';
				*/

		// -------- Same categories as criteria ---------
		$mail_categories = $obj->getMailCategories();
		$retour .= '
			<div class="clear   ">&nbsp;</div>
			<label class="   " >'.$this->l('Same categories as criteria:').' </label>
				<div  class="margin-form   ">
					<input type="radio" name="mail_categories_of_criteria" id="mail_categories_of_criteria_on" value="1" '.((count($mail_categories)==0) ? 'checked="checked" ' : '').'/>
					<label class="t" for="mail_categories_of_criteria_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
					<input type="radio" name="mail_categories_of_criteria" id="mail_categories_of_criteria_off" value="0" '.(!(count($mail_categories)==0) ? 'checked="checked" ' : '').'/>
					<label class="t" for="mail_categories_of_criteria_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" /></label>
					<p class="clear">'.$this->l('Applies discount on same categories than criteria one').'</p>
				</div>';

		// -------- Categories ---------
		$retour .=  '
				<label class="mail_categories_of_criteria ">'.$this->l('Related categories:').' </label>
					<div class="margin-form  mail_categories_of_criteria  ">
							<table cellspacing="0" cellpadding="0" class="table" style="">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'categoryBoxMail[]\', this.checked)" /></th>
										<th>'.$this->l('ID').'</th>
										<th>'.$this->l('Name').'</th>
									</tr>';
		$index = array();
		$categories = Category::getCategories(intval($cookie->id_lang), false);
		$categoriesNotOrdered = Category::getCategories(intval($cookie->id_lang), false, false);
		$indexedCategories = $obj->getMailCategories();
		if (count($indexedCategories) == 0){
			$indexedCategories = array();
			foreach ($categoriesNotOrdered as $cat)
				$indexedCategories[] = $cat['id_category'];
		}

		if (version_compare (_PS_VERSION_, '1.4') < 0)
			//$retour .= $this->recurseCategoryForInclude_ps13('categoryBoxAttribution', $indexedCategories, $categories, $categories[0][1], 1);
			$retour .= $this->recurseCategoryForInclude_ps14('categoryBoxMail', (int)(Tools::getValue($this->identifier)), $indexedCategories, $categories, $categories[0][1], 1, $obj->id);
		else
			$retour .= $this->recurseCategoryForInclude_ps14('categoryBoxMail', (int)(Tools::getValue($this->identifier)), $indexedCategories, $categories, $categories[0][1], 1, $obj->id);
		$retour .=  '</table>
			<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Categories to which to discount applies').'</p>
			</div>';

		$retour .= '&nbsp;</div>';
		return $retour;
	}

	public function _getCommentTabHtml($obj) {

		$retour = '';

		$retour .=  '
				<div class="clear">&nbsp;</div>
				<label class="">'.$this->l('Your comment:').' </label>
					<div class="margin-form ">
						<textarea name="comments" rows="10" cols="50">'.htmlentities($this->getFieldValue($obj, 'comments'), ENT_COMPAT, 'UTF-8').'</textarea>
					</div>
					';
		return $retour;
	}

	public function displayForm($firstCall = true)
	{
	    $cookie = Context::getContext()->cookie;
		$currentIndex = self::$currentIndex;

		if ($currentIndex == '')
			$currentIndex = $_SERVER['SCRIPT_NAME'].(($controller = Tools::getValue('controller')) ? '?controller='.$controller: '');

		$obj = $this->loadObject(true);
		if (version_compare('1.5', _PS_VERSION_)<=0)
			echo '<h2>'.$this->l('Maxi Promos').' &gt; '.(($obj->id) ?'Edit' :'New').'</h2>';

		parent::displayForm($firstCall);

		if (version_compare('1.5.3', _PS_VERSION_) <= 0)
			includeDatepicker(array('global_date_from','global_date_to', 'id_mail_date_from', 'id_mail_date_to'));
		$this->echo_tinyMCE ();

		if (version_compare('1.6.1', _PS_VERSION_) <= 0) {
			$admin_webpath = str_ireplace(_PS_CORE_DIR_, '', _PS_ADMIN_DIR_);
			$admin_webpath = preg_replace('/^'.preg_quote(DIRECTORY_SEPARATOR, '/').'/', '', $admin_webpath);
			echo '
			<script type="text/javascript" src="'.__PS_BASE_URI__.$admin_webpath.'/themes/default/js/tree.js"></script>';
		}

		$fname = _PS_ROOT_DIR_.'/classes/Cart.php';
		$is_cart_patch_ok = false;
		if ($handle = @fopen($fname, 'r')) {
			$content = fread ($handle, filesize($fname));
			$pos = strpos ($content, 'OleacornerQtyPrices for Maxi-Promo');
		    if ($pos !== false)
		       	$is_cart_patch_ok = true;
			fclose ($handle);
		}

		$this->msg_for_patch_price_quantity = (version_compare('1.5', _PS_VERSION_)<=0) ?''
							:(($is_cart_patch_ok) ?'' :'<br/><span class="red">'.$this->l('File /classes/Cart.php must be patched as described in the documentation to set this parameter to false').'</span>');

		echo '
		<form id="id_form_multipromo" action="'.$currentIndex.'&submitAdd'.$this->table.'=1&token='.$this->token.'" method="post" enctype="multipart/form-data" class="'.((version_compare('1.5', _PS_VERSION_)<=0) ?'' :'width4').'">
		'.($obj->id ? '<input type="hidden" name="id_'.$this->table.'" value="'.$obj->id.'" />' : '');

		/* First fieldset */
		echo '
			<fieldset class=" " ><legend>'.$this->l('General Info').'</legend>';

		echo '
				<label>'.$this->l('Name :').' </label>
				<div class="margin-form">
					<input type="text" size="60" name="name" value="'.htmlentities($this->getFieldValue($obj, 'name'), ENT_COMPAT, 'UTF-8').'"/><sup> *</sup>
				</div>';

		echo '
			<label>'.$this->l('Status :').' </label>
				<div class="margin-form">
					<input type="radio" name="active" id="active_on" value="1" '.($this->getFieldValue($obj, 'active') ? 'checked="checked" ' : '').'/>
					<label class="t" for="active_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="active" id="active_off" value="0" '.(!$this->getFieldValue($obj, 'active') ? 'checked="checked" ' : '').'/>
					<label class="t" for="active_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p>'.$this->l('Activate or desactivate').'</p>
				</div>';

		echo '
			<label>'.$this->l('Discount description:').' </label>
				<div class="margin-form">';
		foreach ($this->_languages as $language)
			echo '	<div id="discountobj_description_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none').'; float: left;">
						<input size="70" type="text" name="discountobj_description_'.$language['id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'discountobj_description', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'" /><sup> *</sup>
						<span class="hint" name="help_box">'.$this->l('Invalid characters:').' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
						<p class="clear">'.$this->l('Discount description displayed to customer in cart and invoice').'</p>
					</div>';
		$this->displayFlags($this->_languages, $this->_defaultFormLanguage, 'discountobj_description', 'discountobj_description');
		echo '	</div>';

		echo '
			<div class="clear">&nbsp;</div>
				<label>'.$this->l('Family :').' </label>
				<div class="margin-form">
					<input type="text" size="60" name="global_family" value="'.htmlentities($this->getFieldValue($obj, 'global_family'), ENT_COMPAT, 'UTF-8').'"/>
					<p>'.$this->l('Used to group promotion by family, to allow stopping the evaluation of following promotions of per family').'</p>
				</div>';

		echo '
				<label>'.$this->l('Allows others:').' </label>
				<div class="margin-form">
					<input type="radio" name="global_allows_others" id="global_allows_others_on" value="1" '.($this->getFieldValue($obj, 'global_allows_others') ? 'checked="checked" ' : '').'/>
					<label class="t" for="global_allows_others_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="global_allows_others" id="global_allows_others_off" value="0" '.(!$this->getFieldValue($obj, 'global_allows_others') ? 'checked="checked" ' : '').'/>
					<label class="t" for="global_allows_others_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p>'.$this->l('If this promotion is applied, indicates if following promotions of the list are allowed').'</p>
				</div>';

		echo '
				<label>'.$this->l('Allows others of family:').' </label>
				<div class="margin-form">
					<input type="radio" name="global_allows_family" id="global_allows_family_on" value="1" '.($this->getFieldValue($obj, 'global_allows_family') ? 'checked="checked" ' : '').'/>
					<label class="t" for="global_allows_family_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="global_allows_family" id="global_allows_family_off" value="0" '.(!$this->getFieldValue($obj, 'global_allows_family') ? 'checked="checked" ' : '').'/>
					<label class="t" for="global_allows_family_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p>'.$this->l('If this promotion is applied, indicates if following promotions of the same family are allowed').'</p>
				</div>';

		$tabpane_path = (version_compare('1.5', _PS_VERSION_) <= 0)
			?_PS_BASE_URL_SSL_._PS_JS_DIR_.'jquery/plugins/tabpane/jquery.tabpane' :_PS_BASE_URL_._PS_JS_DIR_.'tabpane';

		echo '
			<div class="clear">&nbsp;</div>
			<script type="text/javascript">
				var pos_select = '.(($tab = (int)Tools::getValue('tabs')) ? $tab : '0').';
			</script>
			<script type="text/javascript" src="'.$tabpane_path.'.js"></script>
			<link type="text/css" rel="stylesheet" href="'.$tabpane_path.'.css" />
			<input type="hidden" name="tabs" id="tabs" value="0" />
			<div class="tab-pane" id="tab-pane-1" style="width:100%;">
				 <div class="tab-page" id="step1">
					<h4 class="tab">'.$this->l('Global Criteria').'</h4>
					'.$this->_getGlobalCriteriaTabHtml($obj).'
				</div>
				<div class="tab-page" id="step2">
					<h4 class="tab">'.$this->l('Products criteria').'</h4>
					'.$this->_getProductsCriteriaTabHtml($obj).'
				</div>
				<div class="tab-page" id="step3">
					<h4 class="tab">'.$this->l('Amount computation').'</h4>
					'.$this->_getAttributionTabHtml($obj).'
				</div>
				<div class="tab-page" id="step4">
					<h4 class="tab">'.$this->l('Communication').'</h4>
					'.$this->_getCommunicationTabHtml($obj).'
				</div>
				<div class="tab-page" id="step5">
					<h4 class="tab">'.$this->l('Mail').'</h4>
					'.$this->_getMailTabHtml($obj).'
				</div>
				<div class="tab-page" id="step6">
					<h4 class="tab">'.$this->l('Comment').'</h4>
					'.$this->_getCommentTabHtml($obj).'
				</div>
			</div>
			<div class="clear"></div>
			<script type="text/javascript">
				function loadTab(id){}
				setupAllTabs();
			</script>';

		/* SAVE */
		echo '
				<div class="clear">&nbsp;</div>
				<div class="margin-form">
					<input type="submit" value="'.$this->l('   Save   ').'" name="submitAdd'.$this->table.'" class="button" />
				</div>
				<div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
			</fieldset>';


		echo '
			</form>';
	}


	public function displayOptionsList () {

		parent::displayOptionsList ();

		$currentIndex = self::$currentIndex;
		if ($currentIndex == '')
			$currentIndex = $_SERVER['SCRIPT_NAME'].(($controller = Tools::getValue('controller')) ? '?controller='.$controller: '');

		echo '<br />
		<form action="'.$currentIndex.'"  method="post">
			<fieldset>';
				$nb_days = (int)Configuration::get('OLEA_MAXIPROMO_NBDAYS');

				include_once dirname(__FILE__).'/OleaDiscountMulti.php';
				$nb_discounts = OleaDiscountMulti::countOldDiscount($nb_days);
				echo '<legend>'.$this->l('Discounts clean-up').'</legend>';
				echo '<p>'.$this->l('The module may create several discounts per cart created by the customer.').'('.$this->l('Discounts are cart rules in 1.5').')</p>';
				echo '<p>'.$this->l('You can clean-up all old discounts that were not used due to cart not converted into order.').'</p>';
				echo '<p>'.sprintf($this->l('You currently have %d discounts older than %d days, that you can suppress.'), $nb_discounts, $nb_days).'</p>';
				echo '<div class="margin-form">
					<input type="hidden" value="'.$this->token.'" name="token" />
					<input type="submit" value="'.$this->l('Delete old discounts').'" name="submitDeleteDiscounts'.$this->table.'" class="button" />
				</div>';
				echo '</fieldset>
			</form>';
	}

	public function displayList() {
		if (version_compare('1.5', _PS_VERSION_)<=0)
			echo '<h2>'.$this->l('Maxi Promos').'</h2>';
		if (version_compare('1.6.1', _PS_VERSION_) <= 0)
			echo '<div class="bootstrap" id="olea-debug-to-remove"><div class="alert alert-warning">
					'.$this->l('There is an issue in the prestashop core to manage correctly the javascript animation of this tab').'<br>
					'.$this->l('- Open the file [YourAdminDir]/header.inc.php').'<br>
					'.$this->l('- Add the line concerning the javascript between the header and the footer').'<br>
							\'display_header\' => true,<br>
							\'display_header_javascript\' => true,<br>
							\'display_footer\' => true,<br>
					</div></div>
					<script>
						$(function() {
							$("#olea-debug-to-remove").remove();
						});
					</script>';

		return parent::displayList();
	}

	public function display () {
		$this->init_container_module_info ();
		if (!$this->_container_module->is_version_ok()) {
			echo '<p>'.$this->l('New version of the module has been installed',__CLASS__).'</p>';
			echo '<p>'.$this->l('Use the configuration tab of the module',__CLASS__).
					': <a href="index.php?tab=AdminModules&configure='.basename(dirname(__FILE__)).'&token='.self::getAdminTokenLite('AdminModules').'" style="text-decoration: underline;">'.$this->l('Here',__CLASS__).'</a></p>';
			'</p>';
			return;
		}
		parent::display();

		$cookie = Context::getContext()->cookie;
		$path = '../modules/'.$this->_container_module->name.'/';
		$lang = new Language($cookie->id_lang);
		$filename = 'readme_'.$lang->iso_code.'.pdf';
		if (!file_exists(dirname(__FILE__).'/'.$filename)) {
			$filename = 'readme_en.pdf';
			if (!file_exists(dirname(__FILE__).'/'.$filename))
				$filename = '';
		}
		$support_link = ($lang->iso_code == 'fr')
		              ? 'https://addons.prestashop.com/fr/ecrire-au-developpeur?id_product=3462'
		              : 'https://addons.prestashop.com/en/write-to-developper?id_product=3462';
		echo '
				<br /><p>'.$this->l('Module',__CLASS__).' <i>'.$this->_container_module->displayName.'</i>, '.$this->l('version',__CLASS__).' '.$this->_container_module->version.' - '.
					$this->l('developped by',__CLASS__).' <b style="font-size:1.2em;" >Oleacorner.com</b>
					<a class="button" target="_blank" href="'.$support_link.'" ><b>'.$this->l('Support',__CLASS__).'</b> </a>';
		if ($filename <> '')
			echo '<a class="button" href="../modules/'.$this->_container_module->name.'/'.$filename.'" target="_blank" ><b>'.$this->l('Documentation',__CLASS__).'</b> </a>';
		echo '	<a class="button" target="_blank" href="http://addons.prestashop.com/'.(($lang->iso_code == 'fr') ?'fr' :'en').'/8_oleacorner" ><b>'.$this->l('Our modules',__CLASS__).'</b> </a></p>';
	}

	/*---------------------- PostProcess() ------------------------------------------------*/
	protected function _childValidation() {
		$attribution_type = Tools::getValue('attribution_type');
		$criteria_type = Tools::getValue('criteria_type');
		if ($attribution_type == Oleapromo::ATTRIBUTION_TYPE_AMOUNT_PRICES_RANGE
			AND  $criteria_type <> Oleapromo::CRITERIA_TYPE_PRODUCT_AMOUNT) {
				$this->_errors[] = $this->l('Criteria').' "'.$this->criteria_type_list[$criteria_type].'" '
							.$this->l('is not compatible with amount computation').' "'.$this->attribution_type_list[Oleapromo::ATTRIBUTION_TYPE_AMOUNT_PRICES_RANGE].'"';
		}
	}

	protected function copyFromPost(&$object, $table)
	{
		$groups = array();
		foreach (Tools::getValue('groupBox') as $g)
			$groups[(int)$g] = (int)$g;
		$object->setGlobalGroups($groups);

		$global_cart_rule_exclusion = array();
		foreach ((array)Tools::getValue('select_global_cart_rule_exclusion') as $cr)
			$global_cart_rule_exclusion[(int)$cr] = (int)$cr;
		$object->setGlobalCartrulesExclusion($global_cart_rule_exclusion);

		$categories = array();
		$categoryBox = Tools::getValue('categoryBoxCriteria');
		if (is_array($categoryBox) AND count($categoryBox))
			foreach ($categoryBox as $c)
				if ((int)$c <> 0)
					$categories[(int)$c] = (int)$c;
		$object->setCriteriaCategories($categories);

		if (Tools::isSubmit('manufacturerBoxCriteriaNone')) {
			$object->setCriteriaManufacturers(array(0)); // Only O, meaning don't filter on manufacturer
		} else {
			$manufacturers = array();
			$manufacturerBox = Tools::getValue('manufacturerBoxCriteria');
			if (is_array($manufacturerBox) AND count($manufacturerBox))
				foreach ($manufacturerBox as $m)
					if ((int)$m > 0)
						$manufacturers[(int)$m] = (int)$m;
			$object->setCriteriaManufacturers($manufacturers);
		}

		if (Tools::isSubmit('supplierBoxCriteriaNone')) {
			$object->setCriteriaSuppliers(array(0)); // Only O, meaning don't filter on suppliers
		} else {
			$suppliers = array();
			$supplierBox = Tools::getValue('supplierBoxCriteria');
			if (is_array($supplierBox) AND count($supplierBox))
				foreach ($supplierBox as $s)
					if ((int)$s > 0)
						$suppliers[(int)$s] = (int)$s;
			$object->setCriteriaSuppliers($suppliers);
		}

		$categories = array();
		$categoryBox = Tools::getValue('categoryBoxAttribution');
		if (is_array($categoryBox) AND count($categoryBox))
			foreach ($categoryBox as $c)
				if ((int)$c <> 0)
					$categories[(int)$c] = (int)$c;
		$object->setAttributionCategories($categories);

		if (Tools::isSubmit('manufacturerBoxAttributionNone')) {
			$object->setAttributionManufacturers(array(0)); // Only O, meaning don't filter on manufacturer
		} else {
			$manufacturers = array();
			$manufacturerBox = Tools::getValue('manufacturerBoxAttribution');
			if (is_array($manufacturerBox) AND count($manufacturerBox))
				foreach ($manufacturerBox as $m)
					if ((int)$m > 0)
						$manufacturers[(int)$m] = (int)$m;
			$object->setAttributionManufacturers($manufacturers);
		}

		if (Tools::isSubmit('supplierBoxAttributionNone')) {
			$object->setAttributionSuppliers(array(0)); // Only O, meaning don't filter on suppliers
		} else {
			$suppliers = array();
			$supplierBox = Tools::getValue('supplierBoxAttribution');
			if (is_array($supplierBox) AND count($supplierBox))
				foreach ($supplierBox as $s)
					if ((int)$s > 0)
						$suppliers[(int)$s] = (int)$s;
			$object->setAttributionSuppliers($suppliers);
		}

		if ((float)Tools::getValue('attribution_percent') > 100)
			$_POST['attribution_percent'] = 100;

		$zones = array();
		foreach ((array)Tools::getValue('zones_fdp') as $z)
			$zones[(int)$z] = (int)$z;
		$object->setZonesFDP($zones);

		$carriers_fdp = array();
		foreach ((array)Tools::getValue('carriers_fdp') as $c)
			$carriers_fdp[(int)$c] = (int)$c;
		$object->setCarriersFDP($carriers_fdp);

		if (Tools::getValue('mail_date_to_selector') == 'fixed')  //	was	if (pSQL($_POST['mail_date_to_selector']) == 'fixed')
		    $object->mail_validity_days = 0;

		if ((int)Tools::getValue('mail_categories_of_criteria') == 1)   // was  if ((int)$_POST['mail_categories_of_criteria'] == 1)
			$object->mail_categories = '';
		else {
			$categories = array();
			$categoryBox = Tools::getValue('categoryBoxMail');
			if (is_array($categoryBox) AND count($categoryBox))
				foreach ($categoryBox as $c)
					if ((int)$c <> 0)
						$categories[(int)$c] = (int)$c;
			$object->setMailCategories($categories);
		}

		$object->mail_cumulable = Tools::getIsset('mail_cumulable');   //  was  (!isset($_POST['mail_cumulable']) ? false : true);
		$object->mail_cumulable_reduction = Tools::getIsset('mail_cumulable_reduction');   //  was   (!isset($_POST['mail_cumulable_reduction']) ? false : true);

		parent::copyFromPost($object, $table);
	}

	public function postProcess ()
	{
	    $cookie = Context::getContext()->cookie;
		$currentIndex = self::$currentIndex;
		if ($currentIndex == '')
			$currentIndex = $_SERVER['SCRIPT_NAME'].(($controller = Tools::getValue('controller')) ? '?controller='.$controller: '');

		if (Tools::isSubmit('submitDeleteDiscounts'.$this->table)) {
			include_once dirname(__FILE__).'/OleaDiscountMulti.php';
			$nb_days = (int)Configuration::get('OLEA_MAXIPROMO_NBDAYS');
			$res = OleaDiscountMulti::deleteOldDiscount($nb_days);
			if ($res == true)
				Tools::redirectAdmin($currentIndex.'&conf=1&token='.$this->token);
		}
		else
			parent::postProcess();
	}


	/*---------------------- T O O L S ------------------------------------------------*/
	public static function getAdminTokenLite($tab)
	{
		$cookie = Context::getContext()->cookie;
		return Tools::getAdminToken($tab.(int)(Tab::getIdFromClassName($tab)).(int)($cookie->id_employee));
	}

	/***** For some translation compatibilities issues between 1.3 and 1.4 ******/
	protected function l($string, $class = 'AdminTab', $addslashes = FALSE, $htmlentities = TRUE)
	{
		return parent::l($string, $class, $addslashes, $htmlentities);
	}

	function recurseCategoryForInclude_ps13($htmlElem, $indexedCategories, $categories, $current, $id_category = 1, $id_category_default = NULL)
	{
		return 'NOT SUPPORTED';
	}

	public static function recurseCategoryForInclude_ps14($htmlElem, $id_obj, $indexedCategories, $categories, $current, $id_category = 1, $id_category_default = NULL, $has_suite = array())
	{
		static $done=array();
		static $irow;

		if (!isset($done[$current['infos']['id_parent']]))
			$done[$current['infos']['id_parent']] = 0;
		$done[$current['infos']['id_parent']] += 1;

		$todo = sizeof($categories[$current['infos']['id_parent']]);
		$doneC = $done[$current['infos']['id_parent']];

		$level = $current['infos']['level_depth'] + 1;

		$retour = '';
		$retour .= '
		<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
			<td>
				<input type="checkbox" name="'.$htmlElem.'[]" class="'.$htmlElem.($id_category_default == $id_category ? ' id_category_default' : '').'" id="'.$htmlElem.'_'.$id_category.'" value="'.$id_category.'"'.((in_array($id_category, $indexedCategories) OR ((int)(Tools::getValue('id_category')) == $id_category AND !(int)($id_obj)) OR Tools::getIsset('adddiscount')) ? ' checked="checked"' : '').' />
			</td>
			<td>
				'.$id_category.'
			</td>
			<td>';
			for ($i = 2; $i < $level; $i++)
				$retour .= '<img src="../img/admin/lvl_'.$has_suite[$i - 2].'.gif" alt="" style="vertical-align: middle;"/>';
			$retour .= '<img src="../img/admin/'.($level == 1 ? 'lv1.gif' : 'lv2_'.($todo == $doneC ? 'f' : 'b').'.gif').'" alt="" style="vertical-align: middle;"/> &nbsp;
			<label for="'.$htmlElem.'_'.$id_category.'" class="t">'.Tools::stripslashes($current['infos']['name']).'</label></td>
		</tr>';

		if ($level > 1)
			$has_suite[] = ($todo == $doneC ? 0 : 1);
		if (isset($categories[$id_category]))
			foreach ($categories[$id_category] AS $key => $row)
				if ($key != 'infos')
					$retour .= self::recurseCategoryForInclude_ps14($htmlElem, $id_obj, $indexedCategories, $categories, $categories[$id_category][$key], $key, $id_category_default, $has_suite);
		return $retour;
	}

	public function echo_tinyMCE () {
	    $cookie = Context::getContext()->cookie;
		$currentIndex = self::$currentIndex;
		if ($currentIndex == '')
			$currentIndex = $_SERVER['SCRIPT_NAME'].(($controller = Tools::getValue('controller')) ? '?controller='.$controller: '');

		$iso = Language::getIsoById($cookie->id_lang);
		if (version_compare(_PS_VERSION_, '1.5', '>=')){
		$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
		$ad = dirname($_SERVER["PHP_SELF"]);
		$this->_html .= '
			<script type="text/javascript">
			var iso = \''.$isoTinyMCE.'\' ;
			var pathCSS = \''._THEME_CSS_DIR_.'\' ;
			var ad = \''.$ad.'\' ;
			</script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>
			<script language="javascript" type="text/javascript">id_language = Number('.$this->context->language->id.');</script>';
		} else if (version_compare(_PS_VERSION_, '1.4.1', '>=')){// tinyMCE 1.4
			$iso = Language::getIsoById((int)($cookie->id_lang));
			$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
			$ad = dirname($_SERVER["PHP_SELF"]);
			echo  '
				<script type="text/javascript">
				var iso = \''.$isoTinyMCE.'\' ;
				var pathCSS = \''._THEME_CSS_DIR_.'\' ;
				var ad = \''.$ad.'\' ;
				</script>
				<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
				<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>';
		} elseif (version_compare(_PS_VERSION_, '1.4', '>=')) {
			echo ' <script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
				<script type="text/javascript">
					tinyMCE.init({
						mode : "textareas",
						theme : "advanced",
						plugins : "safari,pagebreak,style,layer,table,advimage,advlink,inlinepopups,media,searchreplace,contextmenu,paste,directionality,fullscreen",
						// Theme options
						theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
						theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,,|,forecolor,backcolor",
						theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media,|,ltr,rtl,|,fullscreen",
						theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,pagebreak",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_resizing : false,
						content_css : "'.__PS_BASE_URI__.'themes/'._THEME_NAME_.'/css/global.css",
						document_base_url : "'.__PS_BASE_URI__.'",
						width: "600",
						height: "auto",
						font_size_style_values : "8pt, 10pt, 12pt, 14pt, 18pt, 24pt, 36pt",
						elements : "nourlconvert,ajaxfilemanager",
						file_browser_callback : "ajaxfilemanager",
						entity_encoding: "raw",
						convert_urls : false,
						language : "'.(file_exists(_PS_ROOT_DIR_.'/js/tinymce/jscripts/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en').'"

					});
					function ajaxfilemanager(field_name, url, type, win) {
						var ajaxfilemanagerurl = "'.dirname($_SERVER["PHP_SELF"]).'/ajaxfilemanager/ajaxfilemanager.php";
						switch (type) {
							case "image":
								break;
							case "media":
								break;
							case "flash":
								break;
							case "file":
								break;
							default:
								return false;
					}
		            tinyMCE.activeEditor.windowManager.open({
		                url: "'.dirname($_SERVER["PHP_SELF"]).'/ajaxfilemanager/ajaxfilemanager.php",
		                width: 782,
		                height: 440,
		                inline : "yes",
		                close_previous : "no"
		            },{
		                window : win,
		                input : field_name
		            });

		}
	</script>';

		} elseif (version_compare(_PS_VERSION_, '1.2', '>=')) {
		// tinyMCE 1.2 / 1.3
			echo '
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce/jscripts/tiny_mce/jquery.tinymce.js"></script>
			<script type="text/javascript">
			function tinyMCEInit(element)
			{
				$().ready(function() {
					$(element).tinymce({
						// Location of TinyMCE script
						script_url : \''.__PS_BASE_URI__.'js/tinymce/jscripts/tiny_mce/tiny_mce.js\',
						// General options
						theme : "advanced",
						plugins : "safari,pagebreak,style,layer,table,advimage,advlink,inlinepopups,media,searchreplace,contextmenu,paste,directionality,fullscreen",
						// Theme options
						theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
						theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,,|,forecolor,backcolor",
						theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media,|,ltr,rtl,|,fullscreen",
						theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,pagebreak",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_resizing : true,
						content_css : "'.__PS_BASE_URI__.'themes/'._THEME_NAME_.'/css/global.css",
						// Drop lists for link/image/media/template dialogs
						template_external_list_url : "lists/template_list.js",
						external_link_list_url : "lists/link_list.js",
						external_image_list_url : "lists/image_list.js",
						media_external_list_url : "lists/media_list.js",
						elements : "nourlconvert",
						convert_urls : false,
						language : "'.(file_exists(_PS_ROOT_DIR_.'/js/tinymce/jscripts/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en').'"
					});
				});
			}
			tinyMCEInit(\'textarea.rte\');
			</script>		';
		} else {
		// tinyMCE 1.1
		echo '
			<script type="text/javascript" src="../js/tinymce/jscripts/tiny_mce/tiny_mce_gzip.js"></script>
			<script type="text/javascript">
				tinyMCE_GZ.init({
					plugins : "contextmenu, directionality, media, paste, preview, safari",
					themes : "advanced",
					languages : "'.((!file_exists(PS_ADMIN_DIR.'/../js/tinymce/jscripts/tiny_mce/langs/'.$iso.'.js')) ? 'en' : $iso).'",
					disk_cache : false,
					debug : false
				});
			</script>
			<script type="text/javascript">
				tinyMCE.init({
					mode : "textareas",
					plugins : "contextmenu, directionality, media, paste, preview, safari",
					theme : "advanced",
					language : "'.((!file_exists(PS_ADMIN_DIR.'/../js/tinymce/jscripts/tiny_mce/langs/'.$iso.'.js')) ? 'en' : $iso).'",
					elements : "nourlconvert",
					convert_urls : false,
					theme_advanced_buttons1 : "bold, italic, underline, fontselect, fontsizeselect",
					theme_advanced_buttons2 : "forecolor, backcolor, separator, justifyleft, justifycenter, justifyright, justifyfull, separator, bullist, numlist, separator, undo, redo, separator, link, unlink, separator, code",
					theme_advanced_buttons3 : "",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_buttons3_add : "ltr,rtl,pastetext,pasteword,selectall",
					theme_advanced_buttons1_add : "media,preview",
					paste_create_paragraphs : false,
					paste_create_linebreaks : false,
					paste_use_dialog : true,
					paste_auto_cleanup_on_paste : true,
					paste_convert_middot_lists : false,
					paste_unindented_list_class : "unindentedList",
					paste_convert_headers_to_strong : true,
					plugin_preview_width : "500",
					plugin_preview_height : "600",
					extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]"
				});';
		echo '</script>';

		}
	}

	protected function updateAssoShop($id_object = false)
	{
		if (!(int)$id_object)
			return ;

		$asso = array();

		if (!Shop::isFeatureActive())
			$asso[] = '('.(int)$id_object.', 1)';
		else
			foreach ((array)Tools::getValue('checkBoxShopAsso_oleapromo') as $id_shop => $selected) {
				if ($selected && (int)$id_shop > 0)
					$asso[] = '('.(int)$id_object.', '.(int)$id_shop.')';
			};

		if (!count($asso))
			return;

		Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.$this->table.'_shop  WHERE `'.$this->identifier.'`='.(int)$id_object);
		Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.$this->table.'_shop (`'.pSQL($this->identifier).'`, id_shop)
											VALUES '.implode(',', $asso));
	}

	public function addCSS() {
	}

	public function addJS () {
	}

}
