<?php use_javascript('dd/coordinates.js') ?>
<?php use_javascript('dd/drag.js') ?>
<?php use_javascript('dd/dragdrop.js') ?>
<?php use_stylesheet('dd/lists.css') ?>

<?php $katao_period = $form->getObject() ?>
<div class="content-add01">
	<div class="heading01"><h1><?php echo $katao_period->isNew() ? 'Ajout' : 'Modification' ?> d'une période</h1></div>
</div>

<form action="<?php echo url_for('kataoPeriod/update' . (!$katao_period->isNew() ? '?id=' . $katao_period->getId() : '')) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?>>
  <table>
    <tfoot>
      <tr>
        <td colspan="2">
          <br /><?php echo submit_tag('Sauver', array('onclick' => 'getSort();')) ?> ou <a href="<?php echo url_for('kataoPeriod/index') ?>">annuler</a>
        </td>
      </tr>
    </tfoot>
    <tbody>
      <?php echo $form->renderGlobalErrors() ?>
      <tr valign="top">
        <th align="left"><?php echo $form['name']->renderLabel() ?></th>
        <td>
          <?php echo $form['name'] ?>
		  <?php echo $form['name']->renderError() ?>
        </td>
      </tr>
      <tr valign="top">
        <th align="left"><?php echo $form['begin_at']->renderLabel() ?></th>
        <td>
          <?php echo $form['begin_at'] ?>
		  <?php echo $form['begin_at']->renderError() ?>
        </td>
      </tr>
      <tr valign="top">
        <th align="left"><?php echo $form['order_ended_at']->renderLabel() ?></th>
        <td>
          <?php echo $form['order_ended_at'] ?> <i>(inclus)</i>
		  <?php echo $form['order_ended_at']->renderError() ?>
        </td>
      </tr>
      <tr valign="top">
        <th align="left"><?php echo $form['finish_at']->renderLabel() ?></th>
        <td>
          <?php echo $form['finish_at'] ?> <i>(inclus)</i>
		  <?php echo $form['finish_at']->renderError() ?>

        <?php echo $form['id'] ?>
        </td>
      </tr>
    </tbody>
  </table>

<br />
<div class="content-add01">
	<div class="heading01"><h1>Choix des fournisseurs/produits disponibles</h1></div>
</div>

<p>
	Faites glisser les fournisseurs disponibles dans les listes suivantes :
	<ul>
		<li><u>Tous les produits</u> si vous souhaitez activer tous les produits</li>
		<li><u>Certains produits</u> si vous ne souhaitez activer que certains produits</li>
	</ul>
</p>

<?php echo input_hidden_tag('id', $katao_period->getId()) ?>
<?php echo input_hidden_tag('suppliers_with_all_products', '') ?>

<table cellpadding="0" border="0">
<tr valign="top">
	<td rowspan="3">
		<div class="section-title-filter4"><b>Fournisseurs :</b></div>
		<div class="section-container-filter4">
			<ul id="left_col" class="sortable boxy" style="min-height: 250px">
			<?php foreach ($katao_suppliers['not_select'] as $id => $name): ?>
				<li id="supplier-<?php echo $id ?>" onmouseup="refreshProducts(this)"><?php echo $name ?></li>
			<?php endforeach ?>
			</ul>
		</div>
	</td>
	<td>&nbsp;&nbsp;</td>
	<td>
		<table cellpadding="0" border="0">
		<tr valign="top">
			<td>
				<div class="section-title-filter4"><b>Tous les produits :</b></div>
				<div class="section-container-filter4">
					<ul id="middle_col" class="sortable boxy boxy-large" style="min-height: 150px">
					<?php foreach ($katao_suppliers['all_product'] as $id => $name): ?>
						<li id="all-products-<?php echo $id ?>" onmouseup="refreshProducts(this)"><?php echo $name ?></li>
					<?php endforeach ?>
					</ul>
				</div>
			</td>
		</tr>
		<tr><td>&nbsp;</td></tr>
		<tr valign="top">
			<td>
				<div class="section-title-filter4"><b>Certains produits :</b> <em>(choisir dans la liste ci-dessous)</em></div>
				<div class="section-container-filter4">
					<ul id="right_col" class="sortable boxy boxy-large" style="min-height: 150px">
					<?php foreach ($katao_suppliers['some_product'] as $id => $name): ?>
						<li id="products-<?php echo $id ?>" onmouseup="refreshProducts(this)"><?php echo $name ?></li>
					<?php endforeach ?>
					</ul>
				</div>
			</td>
		</tr>
		<tr valign="top">
			<td>
				<b>Produits sélectionnés :</b>
			</td>
		</tr>
		<tr valign="top">
			<td id="dynamic_product">
				<?php echo select_tag('products', options_for_select($products['list'], $products['selected']), array('multiple' => 'multiple', 'style' => 'width:365px;')) ?>
			</td>
		</tr>
		</table>
	</td>
</tr>
</table>

<br />
<?php echo submit_tag('Sauver', array('onclick' => 'getSort();')) ?> ou <a href="<?php echo url_for('kataoPeriod/index') ?>">annuler</a>

</form>

<script type="text/javascript" language="JavaScript">
/* <![CDATA[ */

all_supplier = new Array();
<?php if(!empty($katao_suppliers['all']) && is_array($katao_suppliers['all']) && 0 < count($katao_suppliers['all'])) : ?>
<?php foreach($katao_suppliers['all'] as $name) : ?>
all_supplier.push('<?php echo $name ?>');
<?php endforeach ?>
<?php endif ?>

function in_array(needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net

    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

window.onload = function() {
	list = document.getElementById("left_col");
	DragDrop.makeListContainer( list, 'g1' );
	list.onDragOver = function() { this.style["background"] = "#eff3fc"; };
	list.onDragOut = function() {this.style["background"] = "none"; };

	list = document.getElementById("middle_col");
	DragDrop.makeListContainer( list, 'g1' );
	list.onDragOver = function() { this.style["background"] = "#eff3fc"; };
	list.onDragOut = function() {this.style["background"] = "none"; };

	list = document.getElementById("right_col");
	DragDrop.makeListContainer( list, 'g1' );
	list.onDragOver = function() { this.style["background"] = "#eff3fc"; };
	list.onDragOut = function() {this.style["background"] = "none"; };
};

function getSort() {
	$("suppliers_with_all_products").value = DragDrop.serData('g1', null);
}

function showValue() {
	suppliers_with_all_products = document.getElementById("suppliers_with_all_products");
	alert(suppliers_with_all_products.value);
}

function refreshProducts(element){
	var parent = element.parentNode; //right_col
	var supplier_id = element.id;
	var childs = parent.childNodes;
	var period_id = $('id');
	var params = new Array();
	if (parent.id == 'right_col') {
		for(var i = 0; i < childs.length; i++){
			if ('LI' == childs[i].nodeName) {
				var supplier_id = childs[i].id;
				supplier_id = supplier_id.substr(13, supplier_id.length - 13);
				params.push(supplier_id);
			}
		}
		var tidyParams = params.join(',');
		var url = '<?php echo url_for('kataoPeriod/refreshProducts') ?>';
		var myAjax = new Ajax.Request(
		    url,
		    {
		      method: 'get',
			  parameters: {
			  			 suppliers_ids:tidyParams,
						 id:period_id.value
			  },

			  onSuccess: manageResponse
		    });
	}
	if (parent.id == 'middle_col' || parent.id == 'left_col') {
		var right_col = $('right_col');
		var childs_right_col = right_col.childNodes;
		for(var i = 0; i < childs_right_col.length; i++){
			if ('LI' == childs_right_col[i].nodeName) {
				var supplier_id = childs_right_col[i].id;
				supplier_id = supplier_id.substr(9, supplier_id.length - 9);
				params.push(supplier_id)
			}
		}
		var tidyParams = params.join(',');
		var url = '<?php echo url_for('kataoPeriod/refreshProducts') ?>';
		var myAjax = new Ajax.Request(
		    url,
		    {
		      method: 'get',
			  parameters: {
			  			 suppliers_ids:tidyParams,
						 id:period_id.value
			  },

			  onSuccess: manageResponse
		    });
	}
}

function manageResponse(xhr){
	var products = xhr.responseText.evalJSON();
	var mySelect = '<select name="products[]" id="products" multiple="multiple" style="width:365px;">';
	var optSelect = new Array();
	products.selected.each(
	    function (result)
	    {
			optSelect = Object.values(result);
		});
	products.list.each(
        function (supplier)
        {
			//console.log(products.selected);
            for(var i = 0; i < all_supplier.length; i++){
				var product_list = eval('supplier["' + all_supplier[i] + '"]');
				if (product_list != undefined) {
				    mySelect += '<optgroup label="'+all_supplier[i]+'">';
					product_list.each(
					function (opt_list)
        			{
						var opt_names = Object.values(opt_list);
						var opt_ids = Object.keys(opt_list);
						for(var i = 0; i < opt_ids.length; i++){
							// mySelect += '<option value="'+opt_ids[i]+'">'+opt_names[i]+'</option>';
							if (in_array(opt_ids[i],optSelect)) {
								mySelect += '<option value="'+opt_ids[i]+'" selected="selected">'+opt_names[i]+'</option>';
							}else{
								mySelect += '<option value="'+opt_ids[i]+'">'+opt_names[i]+'</option>';
							}
						}
					});
					mySelect += '</optgroup>';
				}
			}
        });
	mySelect += '</select>';
	$('dynamic_product').update();
	$('dynamic_product').innerHTML
	$('dynamic_product').update(mySelect);
	$('dynamic_product').innerHTML
}

/* ]]> */
</script>