<?php

		global $conf, $db, $langs, $user, $hookmanager;

		if (empty($conf->global->DOLITOOLS_USE_CUSTOMREF)) return;

        if (! in_array('propalcard',$hookmanager->contextarray) && ! in_array('ordercard',$hookmanager->contextarray) && ! in_array('invoicecard',$hookmanager->contextarray) && ! in_array('expeditioncard',$hookmanager->contextarray)) return;

        $langs->load('customref@dolitools');

  		$element = $object->element;

		// TODO uniformiser
		if ($element == 'propal') $element = 'propale';

		if ($element == 'propale' || $element=='commande' || $element == 'facture' || $element == 'shipping')
		{
			// creation sans PROV
			$glovar = "CUSTOMREF_".strtoupper($element)."_NOPROV";
			if ($action == 'create' && !empty($conf->global->$glovar))
			{
				$sep = $conf->global->CUSTOMREF_SEPARATOR?$conf->global->CUSTOMREF_SEPARATOR:'';
				$lensep = mb_strlen($sep);

				$soc = new Societe($db);
				$socid=GETPOST('socid','int');
				if ($socid>0) $res=$soc->fetch($socid);

				$ref = GETPOST('ref1');
				$nextref = $object->getNextNumRef($soc);
				$refsuffix = GETPOST('ref2')?GETPOST('ref2'):substr($ref, strlen($nextref));
				if (substr($refsuffix, 0, $lensep) == $sep) $refsuffix = substr($refsuffix, $lensep);
				$refsuffix = dol_string_nospecial(trim($refsuffix));

				$origin=GETPOST('origin','alpha');
				$originid=(GETPOST('originid','int')?GETPOST('originid','int'):GETPOST('origin_id','int')); // For backward compatibility
				$glovar = "CUSTOMREF_".strtoupper($element)."_KEEP_SUFFIX_ON_WORKFLOW";
				if(empty($refsuffix) && !empty($origin) && !empty($conf->global->$glovar))
				{
					include_once __DIR__ . '/../../lib/customref.lib.php';
					$refsuffix = getSuffixFromOriginRef($origin, $originid);
				}

				print '<script type="text/javascript">
					$(document).ready(function() {

							var ori = $("div.fiche form:first table:first tr:first");

							$(ori).replaceWith("<tr><td class=\"fieldrequired\">'.$langs->trans("Ref").'</td><td colspan=\"2\">'.$nextref.'</td><input type=\"hidden\" name=\"ref1\" value=\"'.$nextref.'\"></tr>");';

				$glovar = "CUSTOMREF_".strtoupper($element)."_SUFFIX_ON_CREATE";
				if (!empty($conf->global->$glovar))
					$maxchars = $conf->global->DOLITOOLS_MAX_LENGTH_FOR_CUSTOMREF ? $conf->global->DOLITOOLS_MAX_LENGTH_FOR_CUSTOMREF : 30 - strlen($nextref);
					print ' $("form input[name=\"ref1\"]").prev("td").append("<input type=\"text\" size=\"20\" id=\"ref2\" name=\"ref2\" value=\"'.$refsuffix.'\" maxlength=\"'.$maxchars.'\" />");
							$("form").submit(function() {
								var ref1 = $("form input[name=\"ref1\"]");
								if ($("#ref2").val().trim() != "")
								{
									if ($("#ref2").val().substr(0,'.$lensep.') == "'.$sep.'")
										ref1.val(ref1.val()+$("#ref2").val());
									else
										ref1.val(ref1.val()+"'.$sep.'"+$("#ref2").val());
								}
							});';
				print '		});
					</script>';


				return 0;
			}

		}
