/* javascript functions used by the prod_simple.pm module */

function showCalendar( tableName, inputName, formName, sRemoteTableContent )
{
  // le code JS qui vient du remote doit être "réinjecté" dans le contexte de la fenetre window
  if (sRemoteTableContent)
  {
      sRemoteTableContent += "; window.calendar" + getInputValue( inputName, formName )+" = calendar" + getInputValue( inputName, formName );
  }
  var tableContent = sRemoteTableContent != null
                  ? eval( sRemoteTableContent )
                  : eval( 'window.calendar' + getInputValue( inputName, formName ) );
  
  if( tableContent )
  {
    setTableContent( tableName, tableContent );
    updateTable( tableName );
  }
  else
  {
    if( tableContents[ tableName ] != null )
    {
      storeTable( tableName );
      emptyTable( tableName );
    }
  }
}

function updateProdSimpleCalendar( sCalendarName, sCalendarCodeInputName, sFormName,nSimpleProductID,p_sMode)
{	
  g_pCalendarFields = new Array();
  
  try
  {
    var sCalendarCode = getInputValue( sCalendarCodeInputName, sFormName );
    var sCalendarTableContent = remoteCall( 'custom::remote::prod_simple_calendar', 'getProdSimpleCalendar', sCalendarCode,sFormName,nSimpleProductID,p_sMode );
    if( sCalendarTableContent )
    {
      showCalendar( sCalendarName, sCalendarCodeInputName, sFormName, sCalendarTableContent );
    }
  }
  catch(ex)
  {
    if(ex.showUser)
      ex.showUser();
    else
    throw ex;	
  }
}

function initCalendar( tableName, inputName, formName )
{
  if( getTableContent( tableName ) != null )
  {
    var tableContent = getTableContent( tableName );
    //alert( tableContent );
    setTableContent( tableName, tableContent );
    
    updateTable( tableName );
  }
  else
  {
    showCalendar( tableName, inputName, formName );
  }
}

function updateProrated( productName, formName )
{
  var periodic = ( getInputValue( productName + '_step', formName ) > 1 ) ? true : false;
  if( periodic == true )
  {
    showLayer( 'prorated_layer' );
  }
  else
  {
    hideLayer( 'prorated_layer' );
  }
}

function setDureePrestation(sName, sDurationObj, sDeltaMoinsObj, sFormName)
{
  var nDuration = getInputValue( sDurationObj, sFormName );
  if(nDuration != 0 && nDuration)
  {
    setInputValue(sDeltaMoinsObj, '0', sFormName);
    setFormObjectProperty( sDeltaMoinsObj, sFormName, 'disabled', true );
  }
  else setFormObjectProperty( sDeltaMoinsObj, sFormName, 'disabled', false );
}

function setDeltaPrestationMoins(sName, sDeltaMoinsObj, sDurationObj, sFormName)
{
  var nDeltaMoins = getInputValue( sDeltaMoinsObj, sFormName );
  if(nDeltaMoins != 0 && nDeltaMoins)
  {
    setInputValue(sDurationObj, '0', sFormName);
    setFormObjectProperty( sDurationObj, sFormName, 'disabled', true );
  }
  else setFormObjectProperty( sDurationObj, sFormName, 'disabled', false );
}

function updatePerPerson( productName, formName )
{
  var per_person = getInputValue( productName + '_per_person', formName );
  //alert( per_person );
  if( per_person == false )
  {
    if( getInputValue( productName + '_pax', formName ) <= 0 )
    {
      setInputValue( productName + '_pax', 1, formName );
    }
    if( getLayerDisplayed( 'duplicate_settings_layer' ) )
    {
      enableInputChecker( productName + '_pax' );
    }
    showLayer( 'pax_layer' );
  }
  else
  {
    setInputValue( productName + '_pax', 0, formName );
    //alert( 'disableInputChecker( ' + productName + ')' );
    disableInputChecker( productName + '_pax' );
    hideLayer( 'pax_layer' );
  }
}

function updateGenericForSale( productName, formName )
{
  var genericForSale = getInputValue( productName + '_generic_for_sale', formName );
  // nothing to do with this flag
  //  specific for sale could be used, even if the product is globally not for sale
  //if( genericForSale == false )
  //{
  //  setInputValue( productName + '_specific_for_sale', false, formName );
  //  getFormObject( productName + '_specific_for_sale', formName ).disabled = true;
  //}
  //else
  //{
  //  getFormObject( productName + '_specific_for_sale', formName ).disabled = false;
  //}
}

function hideAge()
{
  hideLayer( 'age_layer' );
}

function hideStayDuration()
{
  disableInputChecker( productName + '_stay_duration' );
  hideLayer( 'stay_duration_layer' );
}

function showDuplicate()
{
  showLayer( 'duplicate_settings_layer' );
}

function hideDuplicate( productName, formName )
{
  disableInputChecker( productName + '_stay_duration' );
  disableInputChecker( productName + '_age_from' );
  disableInputChecker( productName + '_age_to' );
}

function genCalInputHTML( HTMLTemplate, name )
{
  var sRet = HTMLTemplate;

  return sRet.replace( /templateName/g, name );
}

function setAmountValue( inputName, value, formName, myDocument )
{
  if( getFormObject( inputName, formName ) != null )
  {
    var field_name = new String( getInputValue( inputName + '_field_name', formName ) );
    
    if( !( new String( getFormObject( inputName, formName ).onblur ) ).match( /copyAmounts/ ) )
    {
      //alert( inputName );
      if( field_name.match( /^DI|CO/ ) )
      {
        copyInputChecker( 'amount_pct_checker', inputName );
      }
      else
      {
        copyInputChecker( 'amount_checker', inputName );
      }
    }
  }

  setInputValue( inputName, value, formName, myDocument );

  formatAmount( inputName, formName );
}

/*
  Returns an array or null if there is no such product at all:
  0 - productCode (echoed from input)
  1 - etabNum (echoed from input)
  2 - productType (1 if simple product or 2 for a compound product)
  3 - exists (1 if this product already exists in this etab else 0)
  4 - productID
  5 - heading code (if applicable)
  6 - tax code (if applicable)
*/
function getRemoteProduct( productCode, etabNum, nNumMor )
{
  return remoteCall( 'custom::remote::prod', productCode, etabNum, nNumMor );
}

function checkProduct( inputName, formName )
{
  var productCode = getInputValue( inputName, formName );

  if( productCode == '' )
  {
    return true;
  }

  var etabNum = getInputValue( 'etab', formName );
  var nNumMor = getInputValue( 'rmethod_id', formName );

  var ret = getRemoteProduct( productCode, etabNum, nNumMor );
  if( ret == '' || ret == null)
  {
    return true;
  }
  else
  {
    if( ret[ 3 ] == '1' )
    {
      var productType = getInputValue( 'prod_product_type', formName );

      //alert( ret[ 2 ] + '==' + productType );
      if( ret[ 2 ] == productType )
      {
        if( !confirm( LANG_product_already_exists ) )
        {
          setInputValue( inputName, '', formName );
          focusObject( getFormObject( inputName, formName ) );
        }
        else
        {
          startPleaseWait();
          document.location = duplicateURL + 'prod_product_id=' + ret[4];
        }
      }
      else
      {
        alert( LANG_exists_as_other_product );
        setInputValue( inputName, '', formName );
        focusObject( getFormObject( inputName, formName ) );
      }
      return false;
    }
    else
    {
      return true;
    }
  }
}

function findProductRow( tableName, productCode )
{
  var rows = getRows( tableName );

  for( var i = 1 ; i < rows.length ; i++ )
  {
    if( rows[ i ][ 1 ][ 1 ] == productCode )
    {
      return ( i - 1 );
    }
  }

  return null;
}

function findHeadingRow( tableName, headingCode )
{
  var rows = getRows( tableName );

  if( rows.length <= 1 )
  {
    return 1;
  }

  if( headingCode >= rows[ rows.length - 1 ][ 4 ][ 1 ] )
  {
    return rows.length - 1;
  }

  for( var i = ( rows.length - 1 ) ; i > 1  ; i-- )
  {
    if( headingCode >= rows[ i - 1 ][ 4 ][ 1 ] &&
        headingCode <= rows[ i ][ 4 ][ 1 ] )
    {
      return ( i - 1 );
    }
  }

  return null;
}

function checkProductCode( productName, formName )
{
  var productCode = getInputValue( productName + '_comp_product_code', formName );

  var nRowNumber = findProductRow( 'composition', productCode );
  if( nRowNumber != null )
  {
    editProduct( 'prod', nRowNumber, formName );
    return true;
  }

  if( productCode != '' )
  {
    if( !checkInput( productName + '_comp_product_code', formName ) )
    {
      return false;
    }
  }
  else
  {
    return true;
  }

  var etabNum = getInputValue( 'etab', formName );
  var nNumMor = getInputValue( 'rmethod_id', formName );

  var ret = getRemoteProduct( productCode, etabNum, nNumMor );

  if( ret == null || ret == '' )
  {
    alert( LANG_product_does_not_exist );
    setInputValue( productName + '_comp_product_code', '', formName );
    focusObject( getFormObject( productName + '_comp_product_code', formName ) );
    return false;
  }
  else
  {
    if( ret[ 2 ] != '1' ) // product is not a simple product
    {
      alert( LANG_product_is_not_simple_product );
      setInputValue( productName + '_comp_product_code', '', formName );
      focusObject( getFormObject( productName + '_comp_product_code', formName ) );
      return false;
    }

    if( ret[ 3 ] != '1' ) // product is not a simple product
    {
      alert( LANG_product_does_not_exist_in_etab );
      setInputValue( productName + '_comp_product_code', '', formName );
      focusObject( getFormObject( productName + '_comp_product_code', formName ) );
      return false;
    }

    // Prefill the form

    setCodeSelectInputValue( productName + '_comp_heading_code', ret[5], formName );
    setCodeSelectInputValue( productName + '_comp_tax_code', ret[6], formName );
    setInputValue( productName + '_comp_product_label', ret[7], formName );
    setInputValue( productName + '_comp_meal_type', ret[8], formName );
    setInputValue( productName + '_comp_meal_label', ret[9], formName );

    if( hasPivotProduct( ) )
    {
      getFormObject( productName + '_comp_pivot', formName ).disabled = true;
    }
    if( isPivotProduct( productCode ) )
    {
      getFormObject( productName + '_comp_pivot', formName ).disabled = false;
    }
    else
    {
      setInputValue( productName + '_comp_pivot', isPivotProduct( productCode ) ? true : false, formName );
    }

    updateTimeSlots( productName, productCode, formName );
  }
}

function updateTimeSlots( productName, productCode, formName )
{
  try
  {
    var pTimeSlots = getFormObject( productName + '_comp_time_slot_select', formName );
    var aTimeSlots = remoteCall( 'custom::remote::timeslot', productCode );
    for( var i = ( pTimeSlots.options.length - 1 ); i >= 0 ; i-- )
    {
      pTimeSlots.options[ i ] = null;
    }
    //alert( aTimeSlots );
    if( aTimeSlots && aTimeSlots.length > 0 )
    {
      // show time slots
      getLayer( 'timeslot_layer' ).style.display='inline';
      for( var i = 0 ; i < aTimeSlots.length ; i++ )
      {
        pTimeSlots.options[ i ] = new Option( aTimeSlots[ i ][ 1 ], aTimeSlots[ i ][ 0 ] );
      }
      enableInputChecker( productName + '_comp_time_slot_select' );
      setCodeSelectInputValue( productName + '_comp_time_slot', aTimeSlots[ 0 ][ 0 ], formName );
    }
    else
    {
      hideLayer( 'timeslot_layer' );
      disableInputChecker( productName + '_comp_time_slot' );
    }
  }
  catch(ex)
  {
    if(ex instanceof CheckerException)
      ex.showUser();
    else
      throw ex;
  }
}

function updateProduct( productName, formName )
{
  if( !validateAction( formName, 'UPDATE_PRODUCT' ) )
  {
    return;
  }

  var productCode = getInputValue( productName + '_comp_product_code', formName );
  var productLabel = getInputValue( productName + '_comp_product_label', formName );
  var headingCode = getInputValue( productName + '_comp_heading_code', formName );
  var headingLabel = getFormObject( productName + '_comp_heading_code_select', formName ).options[ getFormObject( productName + '_comp_heading_code_select', formName ).selectedIndex ].text;
  var taxCode = getInputValue( productName + '_comp_tax_code', formName );
  var taxLabel = getFormObject( productName + '_comp_tax_code_select', formName ).options[ getFormObject( productName + '_comp_tax_code_select', formName ).selectedIndex ].text;
  var quantity = getInputValue( productName + '_comp_quantity', formName );
  var price = getInputValue( productName + '_comp_price', formName );
  var step = getInputValue( productName + '_comp_step', formName );
  var offered_free = getInputValue( productName + '_comp_offered_free', formName );
  var offered_free_label = (getFormObject( productName + '_comp_offered_free', formName ).selectedIndex != 0) ? getFormObject( productName + '_comp_offered_free', formName ).options[ getFormObject( productName + '_comp_offered_free', formName ).selectedIndex ].text : '';
  var pivot = (getInputValue( productName + '_comp_pivot', formName ) ? '1' : '0');
  var mealType = getInputValue( productName + '_comp_meal_type', formName );
  var mealLabel = getInputValue( productName + '_comp_meal_label', formName );
  var timeSlotCode = getInputValue( productName + '_comp_time_slot', formName );

  var row = new Array();
  row[0] = new Array( rowModels_composition[0][0][0], quantity, rowModels_composition[0][0][1] );
  row[1] = new Array( rowModels_composition[0][1][0], productCode, rowModels_composition[0][1][1] );
  row[2] = new Array( rowModels_composition[0][2][0], productLabel, rowModels_composition[0][2][1] );
  row[3] = new Array( rowModels_composition[0][3][0], price, rowModels_composition[0][3][1] );
  row[4] = new Array( rowModels_composition[0][4][0], headingCode, rowModels_composition[0][4][1] );
  row[5] = new Array( rowModels_composition[0][5][0], headingLabel, rowModels_composition[0][5][1] );
  row[6] = new Array( rowModels_composition[0][6][0], taxCode, rowModels_composition[0][6][1] );
  row[7] = new Array( rowModels_composition[0][7][0], taxLabel, rowModels_composition[0][7][1] );
  row[8] = new Array( rowModels_composition[0][8][0], step, rowModels_composition[0][8][1] );
  row[9] = new Array( rowModels_composition[0][9][0], pivot, rowModels_composition[0][9][1] );
  row[10] = new Array( rowModels_composition[0][10][0], offered_free, rowModels_composition[0][10][1] );
  row[11] = new Array( rowModels_composition[0][11][0], (offered_free_label != '') ? offered_free_label : '&nbsp;', rowModels_composition[0][11][1] );
  row[12] = new Array( rowModels_composition[0][12][0], mealType, rowModels_composition[0][12][1] );
  row[13] = new Array( rowModels_composition[0][13][0], mealLabel, rowModels_composition[0][13][1] );
  row[14] = new Array( rowModels_composition[0][14][0], timeSlotCode, rowModels_composition[0][14][1] );
  row[15] = new Array( rowModels_composition[0][15][0], productCode, rowModels_composition[0][15][1] );

  var i = findProductRow( 'composition', productCode );

  if( i != null )
  {
    deleteRow( 'composition', i );
  }

  if( isPivotProduct( productCode ) || pivot == '1' )
  {
    i = 1;
  }
  else
  {
    i = findHeadingRow( 'composition', headingCode );

    if( i <= 1 && hasPivotProduct() && !isPivotProduct( productCode ) )
    {
      i = 2;
    }
  }

  setBoldRow( row,( pivot == '1' ) ? true : false );

  insertRow( 'composition', row, i );

  clearAddProduct( productName, formName );
}

function editProduct( productName, nRowNumber, formName )
{
  //var row = getRowContents( 'composition', getRowNumberFromID( 'composition', nRowNumber) );
  var row = getRow( 'composition', nRowNumber );
  var productCode = row[1][1];

  setInputValue( productName + '_comp_quantity', row[0][1], formName );
  setInputValue( productName + '_comp_product_code', productCode, formName );
  setInputValue( productName + '_comp_product_label', row[2][1], formName );
  setInputValue( productName + '_comp_price', row[3][1], formName );
  setCodeSelectInputValue( productName + '_comp_heading_code', row[4][1], formName );
  setInputValue( productName + '_comp_heading_label', row[5][1], formName );
  setCodeSelectInputValue( productName + '_comp_tax_code', row[6][1], formName );
  setInputValue( productName + '_comp_tax_label', row[7][1], formName );
  setInputValue( productName + '_comp_step', row[8][1], formName );
  setInputValue( productName + '_comp_pivot', isPivotProduct( productCode ) ? true : false, formName );
  setInputValue( productName + '_comp_offered_free', row[10][1], formName );
  setInputValue( productName + '_comp_meal_type', row[12][1], formName );
  setInputValue( productName + '_comp_meal_label', row[13][1], formName );

  updateTimeSlots( productName, productCode, formName );

  if( hasPivotProduct( ) )
  {
    getFormObject( productName + '_comp_pivot', formName ).disabled = true;
  }
  if( isPivotProduct( productCode ) )
  {
    getFormObject( productName + '_comp_pivot', formName ).disabled = false;
  }

  updateOfferedFree( productName, formName );
  updatePivot( productName, formName );
}

function deleteProduct( productName, nRowNumber, formName )
{
  deleteRow( 'composition', nRowNumber );

  clearAddProduct( productName, formName );
}

function clearAddProduct( productName, formName )
{
  setInputValue( productName + '_comp_product_code', '', formName );
  setCodeSelectInputValue( productName + '_comp_heading_code', '', formName );
  setCodeSelectInputValue( productName + '_comp_tax_code', '', formName );
  setInputValue( productName + '_comp_quantity', '', formName );
  setInputValue( productName + '_comp_price', '', formName );
  setInputValue( productName + '_comp_step', '0', formName );
  setInputValue( productName + '_comp_pivot', false, formName );
  if( hasPivotProduct() )
  {
    getFormObject( productName + '_comp_pivot', formName ).disabled = true;
  }
  else
  {
    getFormObject( productName + '_comp_pivot', formName ).disabled = false;
  }
  setSelectInputValue( productName + '_comp_offered_free', '0', formName );
  setCodeSelectInputValue( productName + '_comp_time_slot', '', formName );

  updateOfferedFree( productName, formName );
  updatePivot( productName, formName );
}

function hasPivotProduct()
{
  var rows = getRows( 'composition' );

  for( var i = 1 ; i < rows.length ; i++ )
  {
    if( rows[ i ][ 9 ][ 1 ] == '1' )
    {
      return true;
    }
  }

  return false;
}

function isPivotProduct( productCode )
{
  var rows = getRows( 'composition' );

  for( var i = 1 ; i < rows.length ; i++ )
  {
    if( rows[ i ][ 9 ][ 1 ] == '1' && rows[ i ][ 1 ][ 1 ] == productCode )
    {
      return true;
    }
  }

  return false;
}

function setBoldRow( row, bool )
{
  var foundMatch = false;

  //alert( 'setBoldRow(' + row + ', ' + bool + ')' );

  for( var i = 0 ; i < row.length ; i++ )
  {
    if( bool )
    {
      row[ i ][ 2 ] = row[ i ][ 2 ].replace( /listrow1/, 'pivotclass' );
    }
    else
    {
      row[ i ][ 2 ] = row[ i ][ 2 ].replace( /listrow1/, '' );
    }
  }
}

function updatePivot( productName, formName )
{
  var pivot = getInputValue( productName + '_comp_pivot', formName );

  if( pivot )
  {
    setSelectInputValue( productName + '_comp_offered_free', '0', formName );
    getFormObject( productName + '_comp_offered_free', formName ).disabled = true;
    setInputValue( productName + '_comp_price', '0.00', formName );
    getFormObject( productName + '_comp_price', formName ).disabled = true;
  }
  else
  {
    getFormObject( productName + '_comp_offered_free', formName ).disabled = false;
    getFormObject( productName + '_comp_price', formName ).disabled = false;
  }

  updateOfferedFree( productName, formName );
}

function updateOfferedFree( productName, formName )
{
  var pivot = getInputValue( productName + '_comp_pivot', formName );

  var offered_free = getInputValue( productName + '_comp_offered_free', formName );
  //alert( 'offered_free=' + offered_free + ' cond=' + (offered_free != '0') );
  if( offered_free != '0' || pivot )
  {
    setInputValue( productName + '_comp_price', '0.00', formName );
    getFormObject( productName + '_comp_price', formName ).disabled = true;
  }
  else
  {
    getFormObject( productName + '_comp_price', formName ).disabled = false;
  }
}

function checkComposition( inputName, formName )
{
  //alert( 'checkComposition' );
  if( !hasPivotProduct() )
  {
    alert( LANG_missing_pivot_product );
    focusObject( getFormObject( 'prod_comp_product_code', formName ) );
    return false;
  }
  else
  {
    return true;
  }
}

function formatAmount( inputName, formName )
{
  var val = new String( getInputValue( inputName, formName ) );
  if( val != '-' )
  {
    if( val.match( /\%/ ) )
    {
      val = val.replace( /\%/, '' );

      setInputValue( inputName, formatDecAmount( val, 2 ) + '%', formName );
    }
    else
    {
      setInputValue( inputName, formatDecAmount( val, 2 ), formName );
    }
  }
}

function formatSignedAmount( inputName, formName )
{
  var val = new String( getInputValue( inputName, formName ) );

  if( val.match( /\+/ ) )
  {
    val = val.replace( /\+/, '' );

    setInputValue( inputName, val, formName );
    formatAmount( inputName, formName );
    setInputValue( inputName, '+' + getInputValue( inputName, formName ), formName );
  }
  else if( val.match( /\-/ ) )
  {
    val = val.replace( /\-/, '' );

    setInputValue( inputName, val, formName );
    formatAmount( inputName, formName );
    setInputValue( inputName, '-' + getInputValue( inputName, formName ), formName );
  }
  else
  {
    setInputValue( inputName, formatDecAmount( val, 2 ), formName );
  }
}

function checkAmount( inputName, formName )
{

  if( getInputValue( inputName, formName ) == '-' )
  {
    return true;
  }

  formatAmount( inputName, formName );

  if( !checkInput( inputName, formName ) )
  {
    focusObject( getFormObject( inputName, formName ) );
    return false;
  }

  //alert( 'input format is fine' );

  var fieldName = getInputValue( inputName + '_field_name', formName );

  ( new String( inputName ) ).match( /(.*[^\d])(\d+)_(\d+)$/ );

  var cellname = RegExp.$1;
  var i = RegExp.$2;
  var j = RegExp.$3;

  if( ( new String( fieldName ) ).match( /^DI/ ) )
  {
    i--;
  }
  if( ( new String( fieldName ) ).match( /^CO/ ) )
  {
    i--;i--;
  }
  if( ( new String( fieldName ) ).match( /^PN/ ) )
  {
    i--;i--;i--;
  }

  //alert( 'middle 1' );

  var unit_price = getInputValue( cellname + i + '_' + j, formName );
  var discount = ( getFormObject( cellname + (i+1) + '_' + j, formName ) != null ) ? getInputValue( cellname + (i+1) + '_' + j, formName ) : 0;
  var commission = ( getFormObject( cellname + (i+2) + '_' + j, formName ) != null ) ? getInputValue( cellname + (i+2) + '_' + j, formName ) : 0;
  var net_price = ( getFormObject( cellname + (i+3) + '_' + j, formName ) != null ) ? getInputValue( cellname + (i+3) + '_' + j, formName ) : 0;

  if( unit_price == '-' )
  {
    return true;
  }

  //alert( 'middle 2 unit_price=' + unit_price + ' discount=' + discount + ' commission=' + commission + ' net_price=' + net_price );

  var total = unit_price;
  discount = new String( discount );
  if( discount.match( /%/ ) )
  {
    discount = discount.replace( /%/, '' );
    total -= discount * total / 100;
  }
  else
  {
    total -= discount;
  }
  commission = new String( commission );
  if( commission.match( /%/ ) )
  {
    commission = commission.replace( /%/, '' );
    total -= commission * total / 100;
  }
  else
  {
    total -= commission;
  }

  return true;
}

function copyAmounts( inputName, formName )
{
  if( !checkAmount( inputName, formName ) )
  {
    return false;
  }

  var fieldName = getInputValue( inputName + '_field_name', formName );
  var value = getInputValue( inputName, formName );

  ( new String( inputName ) ).match( /(.*[^\d])(\d+)_(\d+)$/ );

  var cellName = RegExp.$1;
  var i = RegExp.$2;
  var j = RegExp.$3;

  var height = getInputValue( 'calendar_table_height', formName );
  var width = getInputValue( 'calendar_table_width', formName );

  // Si il n'a pas plusieurs champs, ne pas demander au client si il souhaite
  //  répliquer la donnée saisie dans d'autres champs.
  if( width > 1 )
  {
    if( !confirm( LANG_copy_amounts ) )
    {
      return;
    }
  }
  else
  {
    return;
  }

  var field_type = ( new String( fieldName ) ).substring( 0, 2 );
  var focusObj = null;
  for( var j=0 ; j<width ; j++ )
  {
    for( var i=0 ; i<height ; i++ )
    {
      if( getFormObject( cellName + i + '_' + j + '_field_name', formName ) != null )
      {
        var tmpFieldName = getInputValue( cellName + i + '_' + j + '_field_name', formName );
        if( (new String( tmpFieldName )).substring( 0, 2 ) == field_type )
        {
          if( j == 1 )
          {
            if( focusObj == null )
            {
              focusObj = getFormObject( cellName + i + '_' + j, formName );
            }
          }
          setInputValue( cellName + i + '_' + j, value, formName );
          if( !checkAmount( cellName + i + '_' + j, formName ) )
          {
            return;
          }
        }
      }
    }
  }
  //alert( focusObj + ' ' + focusObj.name );
  if( focusObj != null )
  {
    focusObject( focusObj );
  }
}

function checkAgeInterval()
{
  var formName = 'prod_form';
  var productName = 'prod';
  var ageFrom = getInputValue( productName + '_age_from', formName );
  var ageTo = getInputValue( productName + '_age_to', formName );

  if( ageFrom == '' && ageTo == '' )
  {
    return true;
  }
  if( ageFrom == '' && ageTo != '' )
  {
    alert( LANG_age_check_from_error );
    focusObject( getFormObject( productName + '_age_from', formName ) );
    return false;
  }
  if( ageFrom != '' && ageTo == '' )
  {
    alert( LANG_age_check_to_error );
    focusObject( getFormObject( productName + '_age_to', formName ) );
    return false;
  }
  if( parseFloat( ageFrom ) >= parseFloat( ageTo ) )
  {
    alert( LANG_age_from_greater_than_age_to );
    focusObject( getFormObject( productName + '_age_from', formName ) );
    return false;
  }

  return true;
}

function launchProductFinderLookup(sName, sFormName)
{
  var sProduct = modal(sProductFinderProductLookupURL, 'products', 'directories=no,fullscreen=no,height=600,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,width=800' );
  if( sProduct )
  {
    var pInput = getFormObject( sName, sFormName)
    pInput.value = sProduct;
    if( pInput.onchange )
      pInput.onchange();
  }
}

function setProductCodeSelectInputValues( inputName, inputValue, formName, nProductPricingSellingMode )
{
  //alert( inputName + ' ' + inputValue );

  inputValue = ( new String( inputValue ) ).toUpperCase();

  var nEtabID = getFormObject( 'etab', formName ) != null ? getInputValue( 'etab', formName ) : getInputValue( 'owner_etab_num', formName );
  
  var nRMethodID = getInputValue( 'nNumMor', formName ); // si pas défini, ira chercher parmi les produits de base
  
  updateProductCodeSelectInputValues( inputName, inputValue, formName, nEtabID, nRMethodID, nProductPricingSellingMode );

}

function updateProductCodeSelectInputValues( inputName, inputValue, formName, nEtabID, nRMethodID, nProductPricingSellingMode )
{
  // dans tous les cas d'utilisation du product finder, on pioche dans les prestations de base, et non
  //  pas dans les prestations d'une convention
  // c'est vrai AUSSI pour les conditions minimum de facturation
  //  car cela pose des problèmes dans le cas suivant:
  //    - Pas de produit dans la convention lors de la saisie des cond min.
  //    - on pioche dans les produits de la conv master
  //    - Par la suite on recopie des prestations dans la conv spé.
  //    - Le produit initialement selectionné n'est plus disponible
  
  var val;
  if( inputValue )
  {
    val = remoteCall( 'custom::remote::product_finder', 'getProducts', inputValue, nEtabID, nRMethodID, nProductPricingSellingMode );
  }
  var aOptions = new Array();
  if( val )
  {
    for( var j = 0 ; j < val.length ; j++ )
      aOptions.push(new Option( val[j][1], val[j][0] ));
  }
  setSelectOptions(inputName + '_select', formName, aOptions);
  if( val && val.length == 2 )
    setSelectInputValue(inputName + '_select', val[1][0], formName);
}

function updateCampaignCode( campaignInputName, inputName, formName,nSimpleProductID,p_sMode )
{
  var sCampaignCode = getInputValue( campaignInputName, formName );
  var sCalendarCode = aCampaign2Calendar[ sCampaignCode ];

  setCodeSelectInputValue( inputName, sCalendarCode, formName );

  if (nSimpleProductID && p_sMode)
  {
    updateProdSimpleCalendar('calendar_table',inputName, formName, nSimpleProductID, p_sMode); 
  }
  else
  {
    showCalendar( 'calendar_table', inputName, formName );
  }
}

function prodOverclassUpdatePPricingLists(bOriginal)
{
  var nEtabID = getInputValue('object_etab_id', 'object_form');
  if(nEtabID)
  {
    var sProductCode = getInputValue(bOriginal ? 'object_original_product_code' : 'object_product_code', 'object_form');
    if(sProductCode)
    {
      try
      {
        prodOverclassUpdatePPricingList(bOriginal ? 'object_original_product_pricing' : 'object_product_pricing',remoteCall( 'custom::remote::product_finder', 'getProducts', sProductCode, nEtabID, null ));
      }
      catch(ex)
      {
        if(ex.showUser)
          ex.showUser();
      }
    }
  }
}

function prodOverclassUpdatePPricingList(sFieldName, aPPricings)
{
  var aOptions = new Array();
  if(aPPricings)
  {
    for(var i=0;i<aPPricings.length;i++)
      aOptions.push(new Option(aPPricings[i][1],aPPricings[i][0]));
  }
  setSelectOptions(sFieldName, 'object_form', aOptions);
}


function updateBillContentNewLineItemProductPricing()
{
  var formName = 'search_form';
  var sProductID = '';

  // MAJ du libellé
  var pProductPricingSelect = getFormObject('product_pricing_select', formName);
  if( pProductPricingSelect )
  {
    var sLabel = '';
    if( pProductPricingSelect.selectedIndex > 0)
    {
      sLabel = pProductPricingSelect.options[pProductPricingSelect.selectedIndex].text;
      sProductID = pProductPricingSelect.options[pProductPricingSelect.selectedIndex].value;
    }
    setInputValue( 'label', sLabel, formName);
  }
  
  // MAJ du prix unitaire
  if ( sProductID )
  {
    var pUnitPrice = getFormObject('unit_price', formName);
    if( pUnitPrice )
    {
      var sProductCode = '';
      var sDate = '';
      
      var pProductPricing = getFormObject('product_pricing', formName);
      if( pProductPricing )
        sProductCode = pProductPricing.value;
      var pDate = getFormObject('date', formName);
      if( pDate )
        sDate = pDate.value;
      var sCampaignCode = getInputValue('campaign_code_for_unit_price', formName);
      
      var val = remoteCall( 'custom::remote::product_finder', 'getUnitPrice', sProductCode, null, null, null, sProductID, sDate, sCampaignCode );
      if( val )
      {
        val = formatDecAmount( val, 2);
        setInputValue( 'unit_price', val, formName);
      }
    }
  }
  var nCount=0;
  for (nIndex in cheque_like_products)
  {
  	if (cheque_like_products[nIndex]==sProductCode)
  	{
  	  showLayer( 'start_number_value' );
  	  showLayer( 'difference_value' );
  	  showLayer( 'end_number_value' );
  	  showLayer( 'start_number_label' );
  	  showLayer( 'difference_label' );
  	  showLayer( 'end_number_label' );
  	  nCount++;
  	}
  }
  if (nCount==0)
  {
  	hideLayer( 'start_number_value' );
  	hideLayer( 'difference_value' );
  	hideLayer( 'end_number_value' );
  	hideLayer( 'start_number_label' );
  	hideLayer( 'difference_label' );
  	hideLayer( 'end_number_label' );
  }
}

function checkPriceCalendarTable(inputName, formName)
{
  if( !getInputValue( inputName, formName ) )
  {
    return confirmUserMessage('LANG_confirm_save_product_with_no_calendar');
  }
  return true;
}