Solution for item editable description
[fa-stable.git] / includes / ui / ui_view.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 include_once($path_to_root . "/admin/db/voiding_db.inc");
13 include_once($path_to_root . "/includes/types.inc");
14
15 //--------------------------------------------------------------------------------------
16
17 function get_supplier_trans_view_str($type, $trans_no, $label="", $icon=false, 
18         $class='', $id='')
19 {
20         $viewer = "purchasing/view/";
21         if ($type == ST_PURCHORDER)
22                 $viewer .= "view_po.php";
23         elseif ($type == ST_SUPPINVOICE)
24                 $viewer .= "view_supp_invoice.php";
25         elseif ($type == ST_SUPPCREDIT)
26                 $viewer .= "view_supp_credit.php";
27         elseif ($type == ST_SUPPAYMENT)
28                 $viewer .= "view_supp_payment.php";
29         elseif ($type == ST_SUPPRECEIVE)
30                 $viewer .= "view_grn.php";
31         else
32                 return null;
33         $viewer .= "?trans_no=$trans_no";
34
35         if ($label == "")
36                 $label = $trans_no;
37
38         return viewer_link($label, $viewer, $class, $id,  $icon);
39 }
40
41 //--------------------------------------------------------------------------------------
42
43 function get_gl_view_str($type, $trans_no, $label="", $force=false, $class='', $id='')
44 {
45         if (!$force && !user_show_gl_info())
46                 return "";
47
48         $icon = false;
49         if ($label == "")
50         {
51                 $label = _("GL");
52                 $icon = ICON_GL;
53         }
54         $url = ($type == ST_WORKORDER) ? "manufacturing/view/wo_costs_view.php?trans_no=$trans_no"
55                 : "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no";
56
57         return viewer_link($label, $url, $class, $id, $icon);
58 }
59
60 //--------------------------------------------------------------------------------------
61
62 function get_gl_view_str_cell($type, $trans_no, $label="")
63 {
64         $str = get_gl_view_str($type, $trans_no, $label);
65         if ($str != "")
66                 return "<td>$str</td>";
67 }
68
69 //--------------------------------------------------------------------------------------
70
71 function get_customer_trans_view_str($type, $trans_no, $label="", $icon=false, 
72         $class='', $id='')
73 {
74         $viewer = "sales/view/";
75
76         if ($type == ST_SALESINVOICE)
77                 $viewer .= "view_invoice.php";
78         elseif ($type == ST_CUSTCREDIT)
79                 $viewer .= "view_credit.php";
80         elseif ($type == ST_CUSTPAYMENT)
81                 $viewer .= "view_receipt.php";
82         elseif ($type == ST_CUSTDELIVERY)
83                 $viewer .= "view_dispatch.php";
84         elseif ($type == ST_SALESORDER || $type == ST_SALESQUOTE)
85                 $viewer .= "view_sales_order.php";
86         else
87                 return null;
88
89   if(!is_array($trans_no)) $trans_no = array($trans_no);
90
91   $lbl = $label;
92   $preview_str = '';
93
94   foreach($trans_no as $trans) {
95         if ($label == "")
96                 $lbl = $trans;
97         if($preview_str!='') $preview_str .= ',';
98
99         $preview_str .= viewer_link($lbl, $viewer."?trans_no=$trans&trans_type=$type", 
100                 $class, $id, $icon);
101
102   }
103   return $preview_str;
104 }
105
106 //--------------------------------------------------------------------------------------
107
108 function get_banking_trans_view_str($type, $trans_no, $label="", 
109         $icon=false, $class='', $id='')
110 {
111         if ($label == "")
112                 $label = $trans_no;
113
114         if ($type == ST_BANKTRANSFER)
115                 $viewer = "bank_transfer_view.php";
116         elseif ($type == ST_BANKPAYMENT)
117                 $viewer = "gl_payment_view.php";
118         elseif ($type == ST_BANKDEPOSIT)
119                 $viewer = "gl_deposit_view.php";
120         else
121                 return null;
122
123         return viewer_link($label, "gl/view/$viewer?trans_no=$trans_no", 
124                 $class, $id,  $icon);
125 }
126
127 //--------------------------------------------------------------------------------------
128
129 function get_inventory_trans_view_str($type, $trans_no, $label="", 
130         $icon=false, $class='', $id='')
131 {
132         $viewer = "inventory/view/";
133
134         if ($type == ST_INVADJUST)
135                 $viewer .= "view_adjustment.php";
136         elseif ($type == ST_LOCTRANSFER)
137                 $viewer .= "view_transfer.php";
138         else
139                 return null;
140         $viewer .= "?trans_no=$trans_no";
141
142         if ($label == "")
143                 $label = $trans_no;
144
145         return viewer_link($label, $viewer, $class, $id,  $icon);
146 }
147
148 //--------------------------------------------------------------------------------------
149
150 function get_manufacturing_trans_view_str($type, $trans_no, $label="", 
151         $icon=false, $class='', $id='')
152 {
153         $viewer = "manufacturing/view/";
154
155         if ($type == ST_MANUISSUE)
156                 $viewer .= "wo_issue_view.php";
157         elseif ($type == ST_MANURECEIVE)
158                 $viewer .= "wo_production_view.php";
159         elseif ($type == ST_WORKORDER)
160                 $viewer .= "work_order_view.php";
161         else
162                 return null;
163
164         $viewer .= "?trans_no=$trans_no";
165
166         if ($label == "")
167                 $label = $trans_no;
168
169         return viewer_link($label, $viewer, $class, $id,  $icon);
170 }
171
172 //--------------------------------------------------------------------------------------
173
174 function get_dimensions_trans_view_str($type, $trans_no, $label="", $icon=false, 
175         $class='', $id='')
176 {
177         if ($type == ST_DIMENSION)
178                 $viewer = "dimensions/view/view_dimension.php?trans_no=$trans_no";
179         else
180                 return null;
181
182         if ($label == "")
183                 $label = $trans_no;
184
185         return viewer_link($label, $viewer, $class, $id,  $icon);
186 }
187 /*
188         Journal entry or cost update postings link
189 */
190 function get_journal_trans_view_str($type, $trans_no, $label="", $icon=false, 
191         $class='', $id='')
192 {
193         if ($type == ST_JOURNAL || $type == ST_COSTUPDATE)
194                 $viewer = "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no";
195         else
196                 return null;
197
198         if ($label == "")
199                 $label = $trans_no;
200
201         return viewer_link($label, $viewer, $class, $id,  $icon);
202 }
203
204 //--------------------------------------------------------------------------------------
205
206 function get_package_view_str($pkg, $label="", $icon=false, $class='', $id='')
207 {
208         if ($label == "")
209         {
210                 $label = _("Info");
211 //              $icon = ICON_GL;
212         }
213         return viewer_link($label, "admin/view/view_package.php?id=$pkg", $class, $id, $icon);
214 }
215
216
217 //--------------------------------------------------------------------------------------
218
219 function get_trans_view_str($type, $trans_no, $label="", $icon=false, 
220         $class='', $id='')
221 {
222         $view_str = get_customer_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
223         if ($view_str != null)
224                 return $view_str;
225
226         $view_str = get_supplier_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
227         if ($view_str != null)
228                 return $view_str;
229
230         $view_str = get_banking_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
231         if ($view_str != null)
232                 return $view_str;
233
234         $view_str = get_inventory_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
235         if ($view_str != null)
236                 return $view_str;
237
238         $view_str = get_manufacturing_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
239         if ($view_str != null)
240                 return $view_str;
241
242         $view_str = get_dimensions_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
243         if ($view_str != null)
244                 return $view_str;
245
246         $view_str = get_journal_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
247         if ($view_str != null)
248                 return $view_str;
249
250         return null;
251 }
252
253 /*
254         Helper for ui drawing functions.
255         Checks whether any of input function parameters has changed or page is called with GET method (first page display).
256         $name - context
257 */
258 function check_ui_refresh($name=null)
259 {
260         $bt = debug_backtrace();
261         if (!$name)
262                 $name = $bt[1]['function'];
263         $old = @$_SESSION['ui_context'][$name];
264         $new = $_SESSION['ui_context'][$name] = $bt[1]['args'];
265         return ($new != $old);
266 }
267
268 //--------------------------------------------------------------------------------------
269 // Displays currency exchange rate for given date.
270 // When there is no exrate for today, 
271 // gets it form ECB and stores in local database.
272 //
273 function exchange_rate_display($from_currency, $to_currency, $date_, $force_edit=false)
274 {
275     global $Ajax, $SysPrefs;
276
277         $readonly = false;
278
279         if ($from_currency != $to_currency)
280         {
281                 $rate = input_num('_ex_rate');
282                 if (check_ui_refresh() || !$rate) { // readonly or ui context changed
283                         $comp_currency = get_company_currency();
284                         if ($from_currency == $comp_currency)
285                                 $currency = $to_currency;
286                         else
287                                 $currency = $from_currency;
288
289                         $rate = get_date_exchange_rate($currency, $date_); // try local
290
291                         if ($rate)
292                                 $readonly = true; // if we have already local exrate keep it unchanged 
293
294                         if (!$rate) {   // retry from remote service
295                                 $row = get_currency($currency);
296
297                                 if ($row['auto_update']) // autoupdate means use remote service & store exrate on first transaction.
298                                 {
299                                         $rate = retrieve_exrate($currency, $date_);
300                                         if (!$rate)
301                                                 display_warning(sprintf(_("Cannot retrieve exchange rate for currency %s. Please adjust approximate rate if needed."), $currency));
302                                         elseif ($SysPrefs->xr_provider_authoritative) {
303                                                 // if the remote exrate is considered authoritative we can store the rate here,
304                                                 // otherwise exrate will be stored during transaction write
305                                                 $readonly = true;
306                                                 add_new_exchange_rate($currency, $date_, $rate);
307                                         }
308                                 }
309                         }
310                         if (!$rate)     {       // get and edit latest available
311                                 $rate = get_exchange_rate_from_home_currency($currency, $date_);
312                         }
313                         if ($from_currency != $comp_currency)
314                                 $rate = 1 / ($rate / get_exchange_rate_from_home_currency($to_currency, $date_));
315                         $Ajax->activate('_ex_rate_span');
316                 }
317
318                 $rate = number_format2($rate, user_exrate_dec());
319
320                 if ($force_edit || !$readonly)
321                         $ctrl = "<input type=\"text\" name=\"_ex_rate\" size=\"8\" maxlength=\"8\" value=\"$rate\">";
322             else
323                 $ctrl = "<span id=\"_ex_rate\">$rate</span>";
324
325                 label_row(_("Exchange Rate:"), $span = "<span style='vertical-align:top;' id='_ex_rate_span'>$ctrl $from_currency = 1 $to_currency</span>" );
326
327                 $Ajax->addUpdate('_ex_rate_span', '_ex_rate_span', $span);
328         }
329 }
330
331 //--------------------------------------------------------------------------------------
332
333 function is_voided_display($type, $id, $label)
334 {
335         $void_entry = get_voided_entry($type, $id);
336
337         if ($void_entry == null)
338                 return false;
339
340         start_table(TABLESTYLE, "width='50%'");
341         echo "<tr><td align=center><font color=red>$label</font><br>";
342         echo "<font color=red>" . _("Date Voided:") . " " . sql2date($void_entry["date_"]) . "</font><br>";
343         if (strlen($void_entry["memo_"]) > 0)
344                 echo "<center><font color=red>" . _("Memo:") . " " . $void_entry["memo_"] . "</font></center><br>";
345         echo "</td></tr>";
346         end_table(1);
347
348         return true;
349 }
350
351 //--------------------------------------------------------------------------------------
352
353 function comments_display_row($type, $id)
354 {
355         $comments = get_comments($type, $id);
356         if ($comments and db_num_rows($comments))
357         {
358                 echo "<tr><td colspan=15>";
359         while ($comment = db_fetch($comments))
360         {
361                 echo nl2br($comment["memo_"]) . "<br>";
362         }
363                 echo "</td></tr>";
364         }
365 }
366
367 //--------------------------------------------------------------------------------------
368
369 function get_comments_string($type, $type_no)
370 {
371         $str_return = "";
372         $result = get_comments($type, $type_no);
373         while ($comment = db_fetch($result))
374         {
375                 if (strlen($str_return))
376                         $str_return = $str_return . " \n";
377                 $str_return = $str_return . $comment["memo_"];
378         }
379         return $str_return;
380 }
381
382 //--------------------------------------------------------------------------------------
383
384 function view_stock_status($stock_id, $description=null, $echo=true)
385 {
386         global $path_to_root;
387         if ($description)
388                 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id&popup=1' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >". (user_show_codes()?$stock_id . " - ":"") . $description."</a>";
389         else
390                 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id&popup=1' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >$stock_id</a>";
391         if($echo)
392                 echo $preview_str;
393         return $preview_str;
394 }
395
396 function view_stock_status_cell($stock_id, $description=null)
397 {
398         echo "<td>";
399         view_stock_status($stock_id, $description);
400         echo "</td>";
401 }
402
403 //--------------------------------------------------------------------------------------
404
405 function display_debit_or_credit_cells($value, $bold=false)
406 {
407         $value = round2($value, user_price_dec());
408         if ($value >= 0)
409         {
410                 amount_cell($value, $bold);
411                 label_cell("");
412         }
413         elseif ($value < 0)
414         {
415                 label_cell("");
416                 amount_cell(abs($value), $bold);
417         }
418 }
419
420 //--------------------------------------------------------------------------------------
421
422 function display_customer_trans_tax_details($tax_items, $columns)
423 {
424         global $SysPrefs;
425
426         $first = true;
427     while ($tax_item = db_fetch($tax_items))
428     {
429         if (!$tax_item['amount'])
430                 continue;
431
432         $tax = number_format2($tax_item['amount'],user_price_dec());
433                 if ($SysPrefs->suppress_tax_rates() == 1)
434                         $tax_type_name = $tax_item['tax_type_name'];
435                 else
436                         $tax_type_name = $tax_item['tax_type_name']." (".$tax_item['rate']."%) ";
437         if ($tax_item['included_in_price'])
438         {
439                         if ($SysPrefs->alternative_tax_include_on_docs() == 1)
440                         {
441                                 if ($first)
442                                         label_row(_("Total Tax Excluded"), number_format2($tax_item['net_amount'], user_price_dec()),
443                                                 "colspan=$columns align=right", "align=right");
444                         label_row($tax_type_name, $tax, "colspan=$columns align=right", "align=right");
445                         $first = false;
446                 }
447                 else
448                         label_row(_("Included") . " " . $tax_type_name
449                                 . ": $tax", "", "colspan=$columns align=right", "align=right");
450         }                       
451         else
452                 label_row($tax_type_name, $tax, "colspan=$columns align=right", "align=right");
453     }
454 }
455
456 //--------------------------------------------------------------------------------------
457
458 function display_supp_trans_tax_details($tax_items, $columns)
459 {
460     while ($tax_item = db_fetch($tax_items))
461     {
462         if (!$tax_item['amount'])
463                 continue;
464
465         $tax = number_format2(abs($tax_item['amount']),user_price_dec());
466         if ($tax_item['included_in_price'])
467                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) "
468                         . ": $tax", '', "colspan=$columns align=right", "align=right");
469         else
470                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
471                         $tax, "colspan=$columns align=right", "align=right");
472     }
473 }
474
475 //--------------------------------------------------------------------------------------
476
477 function display_edit_tax_items($taxes, $columns, $tax_included, $rightspan=0, $editable=false)
478 {
479         $total = 0;
480
481     foreach ($taxes as $taxitem)
482         {
483                 $amount = isset($taxitem['Override']) ? $taxitem['Override'] : $taxitem['Value'];
484                 if ($taxitem['Value'] != 0){
485                         if ($editable) {
486                                 if (!isset($_POST['mantax['.$taxitem['tax_type_id'].']']))
487                                         $_POST['mantax['.$taxitem['tax_type_id'].']'] = price_format($amount);
488                                 start_row();
489                                 if ($tax_included) {
490                                         $colspan = $columns-1;
491                                         label_cell(_("Included") . " " . $taxitem['tax_type_name'].":",
492                                                 "colspan={$colspan} align='right'");
493                                         amount_cells(null, 'mantax['.$taxitem['tax_type_id'].']',
494                                                 null, "colspan=$columns align=right", '<td></td>', user_price_dec());
495                                 } else {
496                                         label_cell($taxitem['tax_type_name'], "colspan=$columns align='right'");
497                                         amount_cells(null, 'mantax['.$taxitem['tax_type_id'].']',
498                                                 null, "colspan=$columns align=right", null, user_price_dec());
499                                         $total +=  round2($amount, user_price_dec());
500                                 }
501                                 if ($rightspan)
502                                         label_cell('', "colspan ='$rightspan'");
503                                 end_row();
504                         } else {
505                                 $value = number_format2($taxitem['Value'],user_price_dec());
506                                 if ($tax_included)
507                                 {
508                                         label_row(_("Included") . " " . $taxitem['tax_type_name']
509                                                 . " " . $value , "", "colspan=$columns align=right", "align=right", $rightspan);
510                                 }
511                                 else
512                                 {
513                                         label_row($taxitem['tax_type_name'],
514                                                 $value, "colspan=$columns align=right", "align=right", $rightspan);
515                                         $total +=  round2($taxitem['Value'], user_price_dec());
516                                 }
517                         }
518                 }
519         }
520         return $total;
521 }
522
523 //--------------------------------------------------------------------------------------
524
525 function display_footer_exit($space=2)
526 {
527         if ($space)
528                 br($space);
529         end_page(false, false, true);
530         exit;
531 }
532
533 //--------------------------------------------------------------------------------------
534
535 function display_allocations($alloc_result, $total, $title, $show_summary=true)
536 {
537         global $systypes_array;
538
539         if (!$alloc_result || db_num_rows($alloc_result) == 0)
540                 return;
541
542     display_heading2($title);
543
544     start_table(TABLESTYLE, "width='80%'");
545
546     $th = array( _("Type"), _("Number"), _("Date"), _("Total Amount"),
547         _("Left to Allocate"), _("This Allocation"));
548         table_header($th);
549     $k = $total_allocated = 0;
550
551     while ($alloc_row = db_fetch($alloc_result))
552     {
553         alt_table_row_color($k);
554
555         label_cell($systypes_array[$alloc_row['type']]);
556         label_cell(get_trans_view_str($alloc_row['type'],$alloc_row['trans_no']));
557         label_cell(sql2date($alloc_row['tran_date']));
558         $alloc_row['Total'] = round2($alloc_row['Total'], user_price_dec());
559         $alloc_row['amt'] = round2($alloc_row['amt'], user_price_dec());
560         if ($alloc_row['type'] == ST_SUPPAYMENT || $alloc_row['type'] == ST_BANKPAYMENT || $alloc_row['type'] == ST_SUPPCREDIT)
561                 $alloc_row['Total'] = -$alloc_row['Total'];
562         amount_cell($alloc_row['Total']);
563                 amount_cell($alloc_row['Total'] - $alloc_row['amt']);
564         amount_cell($alloc_row['amt']);
565         end_row();
566
567         $total_allocated += $alloc_row['amt'];
568     }
569     start_row();
570         label_cell(_("Total Allocated:"), "align=right colspan=5");
571         amount_cell($total_allocated);
572         end_row();
573         if ($show_summary)
574         {
575                 start_row();
576             label_cell(_("Left to Allocate:"), "align=right colspan=5");
577             $total = round2($total, user_price_dec());
578         amount_cell($total - $total_allocated);
579         end_row();
580         }
581     end_table(1);
582 }
583
584 //--------------------------------------------------------------------------------------
585
586 function display_allocations_from($person_type, $person_id, $type, $type_no, $total)
587 {
588         switch ($person_type)
589         {
590                 case PT_CUSTOMER :
591                         $alloc_result = get_allocatable_to_cust_transactions($person_id, $type_no, $type);
592                         display_allocations($alloc_result, $total, _("Allocations"));
593                         return;
594                 case PT_SUPPLIER :
595                         $alloc_result = get_allocatable_to_supp_transactions($person_id, $type_no, $type);
596                         display_allocations($alloc_result, $total, _("Allocations"));
597                         return;
598         }
599 }
600
601 //--------------------------------------------------------------------------------------
602
603 function display_allocations_to($person_type, $person_id, $type, $type_no, $total)
604 {
605         switch ($person_type)
606         {
607                 case PT_CUSTOMER :
608                         $alloc_result = get_allocatable_from_cust_transactions($person_id, $type_no, $type);
609                         display_allocations($alloc_result, $total, $type == ST_SALESORDER ? _("Pre-Payments") : _("Payments"), false);
610                         return;
611                 case PT_SUPPLIER :
612                         $alloc_result = get_allocatable_from_supp_transactions($person_id, $type_no, $type);
613                         display_allocations($alloc_result, $total, $type == ST_PURCHORDER ? _("Pre-Payments") : _("Payments"), false);
614                         return;
615         }
616 }
617
618 //--------------------------------------------------------------------------------------
619 //
620 //      Expands selected quick entry $id into GL posings and adds to cart.
621 //              returns calculated amount posted to bank GL account.
622 //
623 function display_quick_entries(&$cart, $id, $base, $type, $descr='')
624 {
625         $bank_amount = 0;
626
627         if (!isset($id) || $id == null || $id == "")
628         {
629                 display_error( _("No Quick Entries are defined."));
630                 set_focus('totamount');
631         }
632         else
633         {
634                 if ($type == QE_DEPOSIT)
635                         $base = -$base;
636                 if ($type != QE_SUPPINV && $type != QE_JOURNAL) // only one quick entry on journal/bank transaction
637                         $cart->clear_items();
638
639                 // as for now tax_group is passed only in QE_SUPPINV
640                 $qe_lines = quickentry_calculate($base, $id, @$cart->tax_group_id, $cart->tran_date);
641
642                 if ($qe_lines === 0)
643                 {
644                         display_error( _("No Quick Entry lines are defined."));
645                         set_focus('totamount');
646                         return 0;
647                 } elseif ($qe_lines === -1)
648                 {
649                         display_error(_("Cannot post to GL account used by more than one tax type."));
650                         return 0;
651                 }
652                 foreach($qe_lines as $qe_line)
653                 {
654                         if ($descr != '') $qe_line['descr'] .= ': '.$descr;
655                         if ($type != QE_SUPPINV)
656                                 $cart->add_gl_item($qe_line['code'], $qe_line['dim1'],
657                                         $qe_line['dim2'], $qe_line['amount'], $qe_line['descr']);
658                         else 
659                         {
660                                 $acc_name = get_gl_account_name($qe_line['code']);
661                                 $cart->add_gl_codes_to_trans($qe_line['code'], 
662                                         $acc_name, $qe_line['dim1'], 
663                                         $qe_line['dim2'], $qe_line['amount'], $qe_line['descr']);
664                         }
665                 }
666         }
667         return $bank_amount;
668 }
669
670 //--------------------------------------------------------------------------------------
671
672 function quickentry_calculate($base, $id, $taxgroup=null, $date=null)
673 {
674                 $gl_entries = array();
675                 $qe = get_quick_entry($id);
676                 $type = $qe['type'];
677                 $total = $base;
678                 // quick entry made on account balance is special case.
679                 if ($qe['bal_type'] == 1) // if this is quick entry based on balance - calculate it
680                 {
681                         // Note, that this is ugly hack overriding standard field usage 
682                         // just to make the feature available between major FA releases!
683                         $gl_code = $qe['base_desc'];
684                         $monthly = $qe['base_amount'] == 1.0;
685
686                         if (!isset($date))
687                                 $date = Today();
688
689                         if ($monthly) // marked as monthly
690                                 $begin = begin_month($date);
691                         else
692                         {
693                                 if (is_account_balancesheet($gl_code)) // total
694                                         $begin = "";
695                                 else
696                                         $begin = begin_fiscalyear(); // from fiscalyear begin
697                         }
698                         $base = get_gl_trans_from_to($begin, $date, $gl_code);
699
700                 }
701
702                 $result = get_quick_entry_lines($id);
703                 if (db_num_rows($result) == 0)
704                 {
705                         return 0;
706                 }
707
708                 // first calculate total rate in case more than one tax is used
709                 $totrate = 0;
710                 while ($row = db_fetch($result))
711                 {
712                         $qe_lines[] = $row;
713
714                         switch (strtolower($row['action'])) {
715                                 case "t": // post taxes calculated on base amount
716                                 case "t+": // ditto & increase base amount
717                                 case "t-": // ditto & reduce base amount
718                                         if (substr($row['action'], 0, 1) != 'T') 
719                                                 $totrate += get_tax_type_rate($row['dest_id']);
720                         }
721                 }
722                 $first = true;
723                 $taxbase = 0;
724                 foreach($qe_lines as $qe_line)
725                 {
726                         $gl_code = $qe_line['dest_id'];
727                         switch (strtolower($qe_line['action'])) {
728                                 case "=": // post current base amount to GL account
729                                         $part = $base;
730                                         break;
731                                 case "a": // post amount to GL account and reduce base
732                                         $part = $qe_line['amount'];
733                                         break;
734                                 case "a+": // post amount to GL account and increase base
735                                         $part = $qe_line['amount']; $base += $part;
736                                         break;
737                                 case "a-": // post amount to GL account and reduce base
738                                         $part = $qe_line['amount']; $base -= $part;
739                                         break;
740                                 case "%":       // store acc*amount% to GL account
741                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
742                                         break;
743                                 case "%+":      // ditto & increase base amount
744                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
745                                         $base += $part;
746                                         break;
747                                 case "%-":      // ditto & reduce base amount
748                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
749                                         $base -= $part;
750                                         break;
751                                 case "t": // post taxes calculated on base amount
752                                 case "t+": // ditto & increase base amount
753                                 case "t-": // ditto & reduce base amount
754                                         if ($first)
755                                         {
756                                                 $taxbase = $base/($totrate+100);
757                                                 $first = false;
758                                         }
759
760                                         if (substr($qe_line['action'],0,1) != 'T') 
761                                                 $part = $taxbase;
762                                         else
763                                                 $part = $base/100;
764
765                                         $item_tax = get_tax_type($qe_line['dest_id']);
766                                         //if ($type == QE_SUPPINV && substr($qe_line['action'],0,1) != 'T')
767                                         if ($type == QE_SUPPINV)
768                                         {
769                                                 $rates = 0;
770                                                 $res = get_tax_group_rates($taxgroup);
771                                                 while ($row = db_fetch($res))
772                                                         $rates += $row['rate'];
773                                                 if ($rates == 0)
774                                                         continue 2;
775                                         }
776                                         $tax = round2($part * $item_tax['rate'],  user_price_dec());
777                                         if ($tax == 0) continue 2;
778                                         $gl_code = ($type == QE_DEPOSIT || ($type == QE_JOURNAL && $base < 0)) 
779                                                 ? $item_tax['sales_gl_code'] : $item_tax['purchasing_gl_code'];
780                                         if (!is_tax_gl_unique($gl_code)) {
781                                                 return -1; // more than one taxtype used with this GL account
782                                         }
783
784                                         $part = $tax;
785                                         if (strpos($qe_line['action'], '+'))
786                                                 $base += $tax;
787                                         elseif (strpos($qe_line['action'], '-'))
788                                                 $base -= $tax;
789                                 }
790                                 $gl_entries[] = array(
791                                         'code' => $gl_code, 
792                                         'name' => get_gl_account_name($gl_code),
793                                         'dim1' => $qe_line['dimension_id'], 
794                                         'dim2' => $qe_line['dimension2_id'], 
795                                         'amount' => $part, 
796                                         'descr' => $qe_line['memo']
797                                 );
798                         }
799         return $gl_entries;
800 }
801
802
803 //--------------------------------------------------------------------------------------
804 //
805 //      Simple English version of number to words conversion.
806 //
807 function _number_to_words($number) 
808
809     $Bn = floor($number / 1000000000); /* Billions (giga) */ 
810     $number -= $Bn * 1000000000; 
811     $Gn = floor($number / 1000000);  /* Millions (mega) */ 
812     $number -= $Gn * 1000000; 
813     $kn = floor($number / 1000);     /* Thousands (kilo) */ 
814     $number -= $kn * 1000; 
815     $Hn = floor($number / 100);      /* Hundreds (hecto) */ 
816     $number -= $Hn * 100; 
817     $Dn = floor($number / 10);       /* Tens (deca) */ 
818     $n = $number % 10;               /* Ones */
819
820     $res = ""; 
821
822     if ($Bn) 
823         $res .= _number_to_words($Bn) . " Billion"; 
824     if ($Gn) 
825         $res .= (empty($res) ? "" : " ") . _number_to_words($Gn) . " Million"; 
826     if ($kn) 
827         $res .= (empty($res) ? "" : " ") . _number_to_words($kn) . " Thousand"; 
828     if ($Hn) 
829         $res .= (empty($res) ? "" : " ") . _number_to_words($Hn) . " Hundred"; 
830
831     $ones = array("", "One", "Two", "Three", "Four", "Five", "Six", 
832         "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", 
833         "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", 
834         "Nineteen"); 
835     $tens = array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", 
836         "Seventy", "Eighty", "Ninety"); 
837
838     if ($Dn || $n) 
839     { 
840         if (!empty($res)) 
841             $res .= " and "; 
842         if ($Dn < 2) 
843             $res .= $ones[$Dn * 10 + $n]; 
844         else 
845         { 
846             $res .= $tens[$Dn]; 
847             if ($n) 
848                 $res .= "-" . $ones[$n]; 
849         } 
850     } 
851
852     if (empty($res)) 
853         $res = "zero"; 
854     return $res; 
855
856
857 function price_in_words($amount, $document=0)
858 {
859         // use local price_in_words() if the hook is defined
860         $price = hook_price_in_words($amount, $document);
861         if ($price) 
862                 return $price;
863
864         // Only usefor Remittance and Receipts as default
865         if (!($document == ST_SUPPAYMENT || $document == ST_CUSTPAYMENT || $document == ST_CHEQUE))
866                 return "";
867         if ($amount < 0 || $amount > 999999999999)
868                 return "";
869         $dec = user_price_dec();
870         if ($dec > 0)
871         {
872                 $divisor = pow(10, $dec);
873         $frac = round2($amount - floor($amount), $dec) * $divisor;
874                 $frac = sprintf("%0{$dec}d", round2($frac, 0));
875                 $and = _("and");
876         $frac = " $and $frac/$divisor";
877     }
878     else
879         $frac = "";
880     return _number_to_words(intval($amount)) . $frac;
881 }
882
883 function get_js_open_window($width, $height)
884 {
885         $js ="function openWindow(url, title)\n"
886                 . "{\n"
887                 . " var left = (screen.width - $width) / 2;\n"
888                 . " var top = (screen.height - $height) / 2;\n"
889                 . " return window.open(url, title, 'width=$width,height=$height,left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=no,scrollbars=yes');\n"
890                 . "}\n";
891         $js .= get_js_lookup_window();
892         return $js;
893 }
894
895 function get_js_lookup_window() {
896         $js = "function lookupWindow(url, title) {
897         var u = url.split('#');
898         if (u.length == 2) {
899                 var element = document.getElementById(u[1]);
900                 var options = element.options;
901                 url = u[0] + '&' + u[1] + '=' + options[element.selectedIndex].value;
902         }
903         openWindow(url, title);
904         }";
905         return $js;
906 }
907
908 function get_js_select_combo_item() {
909         $js = "function selectComboItem(doc, client_id, value){
910         var element = doc.getElementById(client_id);
911                 if (typeof(element) != 'undefined' && element != null && element.tagName === 'SELECT' ){
912                         var options = element.options;
913                         for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
914                                 if (options[i].value == value) {
915                                         element.selectedIndex = i;
916                                 element.onchange();
917                                 }
918                         }
919                 } else {                        
920                         var stock_element = doc.getElementsByName('stock_id');
921                 if( stock_element.length > 0) {
922                                 stock_element.value = value;    
923                                 var stock_id = doc.getElementById('_stock_id_edit'); 
924                                 stock_id.value=value;
925                                 stock_id.onblur();              
926                         }
927                 }                       
928                 window.close();
929         }";
930         return $js;
931 }
932 /* for space search option */
933 function get_js_set_combo_item() {
934         $js = "function setComboItem(doc, client_id, value, text){
935         var element = doc.getElementById(client_id);
936                 if(typeof(element) != 'undefined' && element != null && element.tagName === 'SELECT') {
937                         var options = element.options;
938                         options.length = 0;
939                         var option = doc.createElement('option');
940                         option.value = value;
941                         option.text = text;
942                         element.add(option, 0);
943                         element.selectedIndex = 0;
944                 element.onchange();
945             } else {
946                         var stock_element = doc.getElementsByName('stock_id');
947                 if( stock_element.length > 0) {
948                                 stock_element[0].value = value; 
949                                 var stock_id = doc.getElementById('_stock_id_edit'); 
950                                 stock_id.value=value;
951                                 stock_id.onblur();                                      
952                         }
953                 }
954                 window.close();
955         }";
956         return $js;
957 }
958
959 /*
960   Setting focus on element $name in $form.
961   If $form<0 $name is element id.
962 */
963 function set_focus($name, $form_no=0) {
964   global $Ajax;
965         $Ajax->addFocus(true, $name);
966     $_POST['_focus'] = $name;
967 }
968 //
969 //      Set default focus on first field $name if not set yet
970 //      Returns unique name if $name=null
971 //      
972 function default_focus($name=null, $form_no=0) {
973         static $next; 
974         if ($name==null) 
975                 $name = uniqid('_el',true);
976     if (!isset($_POST['_focus'])) {
977           set_focus($name);
978     }
979         return $name;
980 }
981 /*
982         Reset focus to next control element (e.g. link).
983 */
984 function reset_focus()
985 {
986         unset($_POST['_focus']);
987 }
988
989 function get_js_date_picker()
990 {
991     global $SysPrefs, $tmonths;
992
993     $fpath = user_js_cache().'/'.'date_picker.js';
994
995     if (!file_exists($fpath) || $SysPrefs->go_debug) {
996
997         $date_system = $SysPrefs->date_system;
998         $dateseps = $SysPrefs->dateseps;
999         $how = user_date_format();                              // 0 = us/ca, 1 = eu, au, nz, 2 = jp, sw
1000         $sep = $dateseps[user_date_sep()];              // date separator
1001         $wstart = (($date_system == 1 || $date_system == 2 || $date_system == 3) ? 6 : ($how == 0 || $how == 3 ? 0 : 1));       // weekstart (sun = 0, mon = 1)
1002         $months = array(_("January"),_("February"),_("March"),_("April"),_("May"),_("June"),_("July"),_("August"),_("September"),_("October"),_("November"),_("December"));
1003         $wdays = array(_("Su"),_("Mo"),_("Tu"),_("We"),_("Th"),_("Fr"),_("Sa"));
1004         $wno = _("W"); // week no
1005         $back = _("Back");
1006         if ($date_system == 1)
1007                 list($cyear, $cmon, $cday) = gregorian_to_jalali(date("Y"), date("n"), date("j"));
1008         elseif ($date_system == 2)
1009                 list($cyear, $cmon, $cday) = gregorian_to_islamic(date("Y"), date("n"), date("j"));
1010
1011
1012         $js = "
1013 function positionInfo(object) {
1014   var p_elm = object;
1015   this.getElementLeft = getElementLeft;
1016   function getElementLeft() {
1017     var x = 0;
1018     var elm;
1019     if(typeof(p_elm) == 'object'){
1020       elm = p_elm;
1021     } else {
1022       elm = document.getElementById(p_elm);
1023     }
1024     while (elm != null) {
1025       x+= elm.offsetLeft;
1026       elm = elm.offsetParent;
1027     }
1028     return parseInt(x);
1029   }
1030   this.getElementWidth = getElementWidth;
1031   function getElementWidth(){
1032     var elm;
1033     if(typeof(p_elm) == 'object'){
1034       elm = p_elm;
1035     } else {
1036       elm = document.getElementById(p_elm);
1037     }
1038     return parseInt(elm.offsetWidth);
1039   }
1040   this.getElementRight = getElementRight;
1041   function getElementRight(){
1042     return getElementLeft(p_elm) + getElementWidth(p_elm);
1043   }
1044   this.getElementTop = getElementTop;
1045   function getElementTop() {
1046     var y = 0;
1047     var elm;
1048     if(typeof(p_elm) == 'object'){
1049       elm = p_elm;
1050     } else {
1051       elm = document.getElementById(p_elm);
1052     }
1053     while (elm != null) {
1054       y+= elm.offsetTop;
1055       elm = elm.offsetParent;
1056     }
1057     return parseInt(y);
1058   }
1059   this.getElementHeight = getElementHeight;
1060   function getElementHeight(){
1061     var elm;
1062     if(typeof(p_elm) == 'object'){
1063       elm = p_elm;
1064     } else {
1065       elm = document.getElementById(p_elm);
1066     }
1067     return parseInt(elm.offsetHeight);
1068   }
1069   this.getElementBottom = getElementBottom;
1070   function getElementBottom(){
1071     return getElementTop(p_elm) + getElementHeight(p_elm);
1072   }
1073 }
1074 function CC() {
1075   var calendarId = 'CC';
1076   var currentYear = 0;
1077   var currentMonth = 0;
1078   var currentDay = 0;
1079   var selectedYear = 0;
1080   var selectedMonth = 0;
1081   var selectedDay = 0;
1082   var months = ['$months[0]','$months[1]','$months[2]','$months[3]','$months[4]','$months[5]','$months[6]','$months[7]','$months[8]','$months[9]','$months[10]','$months[11]'];
1083   var wdays = ['$wdays[0]', '$wdays[1]', '$wdays[2]', '$wdays[3]', '$wdays[4]', '$wdays[5]', '$wdays[6]'];
1084   var tmonths = ['$tmonths[0]','$tmonths[1]','$tmonths[2]','$tmonths[3]','$tmonths[4]','$tmonths[5]','$tmonths[6]','$tmonths[7]','$tmonths[8]','$tmonths[9]','$tmonths[10]','$tmonths[11]','$tmonths[12]'];
1085   var dateField = null;
1086   function getProperty(p_property){
1087     var p_elm = calendarId;
1088     var elm = null;
1089     if(typeof(p_elm) == 'object'){
1090       elm = p_elm;
1091     } else {
1092       elm = document.getElementById(p_elm);
1093     }
1094     if (elm != null){
1095       if(elm.style){
1096         elm = elm.style;
1097         if(elm[p_property]){
1098           return elm[p_property];
1099         } else {
1100           return null;
1101         }
1102       } else {
1103         return null;
1104       }
1105     }
1106   }
1107   function setElementProperty(p_property, p_value, p_elmId){
1108     var p_elm = p_elmId;
1109     var elm = null;
1110     if(typeof(p_elm) == 'object'){
1111       elm = p_elm;
1112     } else {
1113       elm = document.getElementById(p_elm);
1114     }
1115     if((elm != null) && (elm.style != null)){
1116       elm = elm.style;
1117       elm[ p_property ] = p_value;
1118     }
1119   }
1120   function setProperty(p_property, p_value) {
1121     setElementProperty(p_property, p_value, calendarId);
1122   }
1123   function getDaysInMonth(year, month) {
1124 ";
1125         if ($date_system == 1)
1126                 $js .= "
1127     return [31,31,31,31,31,31,30,30,30,30,30,(((((((year - ((year > 0) ? 474 : 473)) % 2820) + 474) + 38) * 682) % 2816) < 682 ? 30 : 29)][month-1];
1128 ";
1129         elseif ($date_system == 2)
1130                 $js .= "
1131     return [30,29,30,29,30,29,30,29,30,29,30,(((((11 * year) + 14) % 30) < 11) ? 30 : 29)][month-1];
1132 ";
1133         else
1134                 $js .= "
1135     return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
1136 ";
1137         $js .= "
1138   }
1139   function getDayOfWeek(year, month, day) {
1140 ";
1141         if ($date_system == 1 || $date_system == 2)
1142         {
1143                 $js .= "
1144         function mod(a, b)
1145         {
1146             return a - (b * Math.floor(a / b));
1147         }
1148         function jwday(j)
1149         {
1150             return mod(Math.floor((j + 1.5)), 7);
1151         }
1152 ";
1153         if ($date_system == 1)
1154                 $js .= "
1155     var epbase, epyear, t;
1156     epbase = year - ((year >= 0) ? 474 : 473);
1157     epyear = 474 + mod(epbase, 2820);
1158     t = day + ((month <= 7) ? ((month - 1) * 31) : (((month - 1) * 30) + 6)) +
1159       Math.floor(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 +
1160       Math.floor(epbase / 2820) * 1029983 + (1948320.5 - 1);
1161 ";
1162         elseif ($date_system == 2)
1163                 $js .= "
1164         var t;
1165         t = Math.floor((11 * year + 3) / 30) + 354 * year + 30 * month -
1166           Math.floor((month - 1) / 2) + day + 1948440 - 385;
1167 ";
1168         $js .= "
1169     return jwday(t);
1170 ";
1171         }
1172         else
1173                 $js .= "
1174     var date = new Date(year,month-1,day)
1175     return date.getDay();
1176 ";
1177         $js .= "
1178   }
1179   this.clearDate = clearDate;
1180   function clearDate() {
1181     dateField.value = '';
1182     hide();
1183   }
1184   this.getWeek = getWeek;
1185   function getWeek(year, month, day) {
1186 ";
1187         if ($how == 0 || $how == 3)
1188                 $js .= "  day++;";
1189         $js .= "
1190     var date = new Date(year,month-1,day);
1191     var D = date.getDay();
1192     if(D == 0) D = 7;
1193     date.setDate(date.getDate() + (4 - D));
1194     var YN = date.getFullYear();
1195     var ZBDoCY = Math.floor((date.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
1196     var WN = 1 + Math.floor(ZBDoCY / 7);
1197     return WN;
1198   }
1199   this.setDate = setDate;
1200   function setDate(year, month, day) {
1201     if (dateField){
1202 ";
1203         if ($how < 3)
1204                 $js .= "
1205       if (month < 10) {month = '0' + month;}
1206       if (day < 10) {day = '0' + day;}
1207 ";
1208         else
1209                 $js .= "
1210       month = tmonths[month];
1211 ";
1212         if ($how == 0 || $how == 3)
1213                 $js .= "
1214       var dateString = month+'$sep'+day+'$sep'+year;
1215 ";
1216         elseif ($how == 1 || $how == 4)
1217                 $js .= "
1218       var dateString = day+'$sep'+month+'$sep'+year;
1219 ";
1220         elseif ($how == 2 || $how == 5)
1221                 $js .= "
1222       var dateString = year+'$sep'+month+'$sep'+day;
1223 ";
1224         $js .= "
1225       dateField.value = dateString;
1226           setFocus(dateField.name);
1227         if(dateField.getAttribute('aspect')=='cdate')
1228       setElementProperty('color', (dateField.value==user.date ? 'black':'red'), dateField);
1229           if (dateField.className=='searchbox')
1230                 dateField.onblur();
1231       hide();
1232     }
1233     return;
1234   }
1235   this.changeMonth = changeMonth;
1236   function changeMonth(change) {
1237     currentMonth += change;
1238     currentDay = 0;
1239     if(currentMonth > 12) {
1240       currentMonth = 1;
1241       currentYear++;
1242     } else if(currentMonth < 1) {
1243       currentMonth = 12;
1244       currentYear--;
1245     }
1246     calendar = document.getElementById(calendarId);
1247     calendar.innerHTML = calendarDrawTable();
1248   }
1249   this.changeYear = changeYear;
1250   function changeYear(change) {
1251     currentYear += change;
1252     currentDay = 0;
1253     calendar = document.getElementById(calendarId);
1254     calendar.innerHTML = calendarDrawTable();
1255   }
1256   function getCurrentYear() {
1257     var year = new Date().getYear();
1258     if(year < 1900) year += 1900;
1259     return year;
1260   }
1261   function getCurrentMonth() {
1262     return new Date().getMonth() + 1;
1263   }
1264   function getCurrentDay() {
1265     return new Date().getDate();
1266   }
1267   function calendarDrawTable() {
1268     var dayOfMonth = 1;
1269     var wstart = $wstart;
1270     var wno = '&nbsp;$wno&nbsp;';
1271     var validDay = 0;
1272     var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
1273     var daysInMonth = getDaysInMonth(currentYear, currentMonth);
1274     var css_class = null; //CSS class for each day
1275     var table = \"<table cellspacing='0' cellpadding='0' border='0'>\";
1276     table += \"<tr class='header'>\";
1277     table += \"  <td colspan='2' class='previous'><a href='javascript:changeCCMonth(-1);'>&lt;</a><br><a href='javascript:changeCCYear(-1);'>&laquo;</a></td>\";
1278     table += \"  <td colspan='4' class='title'>\" + months[currentMonth-1] + \"<br>\" + currentYear + \"</td>\";
1279     table += \"  <td colspan='2' class='next'><a href='javascript:changeCCMonth(1);'>&gt;</a><br><a href='javascript:changeCCYear(1);'>&raquo;</a></td>\";
1280     table += \"</tr>\";
1281     table += \"<tr>\";
1282     table += \"<th class='weekno'>\"+wno+\"</th>\";
1283     for (var n=0; n<7; n++)
1284         table += \"<th>\" + wdays[(wstart+n)%7]+\"</th>\";
1285     table += \"</tr>\";
1286     for(var week=0; week < 6; week++) {
1287       table += \"<tr>\";
1288       for(var n=0; n < 7; n++) {
1289         dayOfWeek = (wstart+n)%7;
1290         if(week == 0 && startDayOfWeek == dayOfWeek) {
1291           validDay = 1;
1292         } else if (validDay == 1 && dayOfMonth > daysInMonth) {
1293           validDay = 0;
1294         }
1295         if (n==0)
1296         {
1297                 if (dayOfMonth > daysInMonth)
1298                         table += \"<td class='empty'>&nbsp;</td>\";
1299                 else
1300                         table += \"<td class='weekno'>\"+getWeek(currentYear, currentMonth, dayOfMonth)+\"</td>\";
1301         }
1302         if(validDay) {
1303           if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
1304             css_class = 'current';
1305 ";
1306         if ($date_system == 1 || $date_system == 2 || $date_system == 3)
1307                 $js .= "
1308           } else if (dayOfWeek == 5) {
1309 ";
1310         else
1311                 $js .= "
1312           } else if (dayOfWeek == 0 || dayOfWeek == 6) {
1313 ";
1314                 $js .= "
1315             css_class = 'weekend';
1316           } else {
1317             css_class = 'weekday';
1318           }
1319           table += \"<td><a class='\"+css_class+\"' href=\\\"javascript:setCCDate(\"+currentYear+\",\"+currentMonth+\",\"+dayOfMonth+\")\\\">\"+dayOfMonth+\"</a></td>\";
1320           dayOfMonth++;
1321         } else {
1322           table += \"<td class='empty'>&nbsp;</td>\";
1323         }
1324       }
1325       table += \"</tr>\";
1326     }
1327     table += \"<tr class='header'><th colspan='8' style='padding: 3px;text-align:center;'><a href='javascript:hideCC();'>$back</a></td></tr>\";
1328     table += \"</table>\";
1329     return table;
1330   }
1331   this.show = show;
1332   function show(field) {
1333     can_hide = 0;
1334     if (dateField == field) {
1335       return;
1336     } else {
1337       dateField = field;
1338     }
1339     if(dateField) {
1340       try {
1341         var dateString = new String(dateField.value);
1342         var dateParts = dateString.split('$sep');
1343 ";
1344         if ($how == 0)
1345                 $js .= "
1346         selectedMonth = parseInt(dateParts[0],10);
1347         selectedDay = parseInt(dateParts[1],10);
1348         selectedYear = parseInt(dateParts[2],10);
1349 ";
1350         elseif ($how == 1)
1351                 $js .= "
1352         selectedDay = parseInt(dateParts[0],10);
1353         selectedMonth = parseInt(dateParts[1],10);
1354         selectedYear = parseInt(dateParts[2],10);
1355 ";
1356         elseif ($how == 2)
1357                 $js .= "
1358         selectedYear = parseInt(dateParts[0],10);
1359         selectedMonth = parseInt(dateParts[1],10);
1360         selectedDay = parseInt(dateParts[2],10);
1361 ";
1362         elseif ($how == 3)
1363                 $js .= "
1364         selectedDay = parseInt(dateParts[1],10);
1365         selectedMonth = parseInt(tmonths.indexOf(dateParts[0]),10);
1366         selectedYear = parseInt(dateParts[2],10);
1367 ";
1368         elseif ($how == 4)
1369                 $js .= "
1370         selectedDay = parseInt(dateParts[0],10);
1371         selectedMonth = parseInt(tmonths.indexOf(dateParts[1]),10);
1372         selectedYear = parseInt(dateParts[2],10);
1373 ";
1374         else
1375                 $js .= "
1376         selectedYear = parseInt(dateParts[0],10);
1377         selectedMonth = parseInt(tmonths.indexOf(dateParts[1]),10);
1378         selectedDay = parseInt(dateParts[2],10);
1379 ";
1380         $js .= "
1381       } catch(e) {}
1382     }
1383     if (!(selectedYear && selectedMonth && selectedDay)) {
1384 ";
1385         if ($date_system == 1 || $date_system == 2)
1386         {
1387                 $js .= "
1388       selectedMonth = $cmon;
1389       selectedDay = $cday;
1390       selectedYear = $cyear;
1391 ";
1392         }
1393         else
1394         {
1395                 $js .= "
1396       selectedMonth = getCurrentMonth();
1397       selectedDay = getCurrentDay();
1398       selectedYear = getCurrentYear();
1399 ";
1400         }
1401         $js .= "
1402     }
1403     currentMonth = selectedMonth;
1404     currentDay = selectedDay;
1405     currentYear = selectedYear;
1406     if(document.getElementById){
1407       calendar = document.getElementById(calendarId);
1408       calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);
1409       var fieldPos = new positionInfo(dateField);
1410       var calendarPos = new positionInfo(calendarId);
1411       var x = fieldPos.getElementLeft();
1412       var y = fieldPos.getElementBottom();
1413       setProperty('left', x + 'px');
1414       setProperty('top', y + 'px');
1415       setProperty('display', 'block');
1416       if (document.all) {
1417         setElementProperty('left', x + 'px', 'CCIframe');
1418         setElementProperty('top', y + 'px', 'CCIframe');
1419         setElementProperty('width', calendarPos.getElementWidth() + 'px', 'CCIframe');
1420         setElementProperty('height', calendarPos.getElementHeight() + 'px', 'CCIframe');
1421         setElementProperty('display', 'block', 'CCIframe');
1422       }
1423     }
1424   }
1425   this.hide = hide;
1426   function hide() {
1427     if(dateField) {
1428       setProperty('display', 'none');
1429       setElementProperty('display', 'none', 'CCIframe');
1430       dateField = null;
1431     }
1432   }
1433   this.visible = visible;
1434   function visible() {
1435     return dateField
1436   }
1437   this.can_hide = can_hide;
1438   var can_hide = 0;
1439 }
1440 var cC = new CC();
1441 function date_picker(textField) {
1442   cC.show(textField);
1443 }
1444 function hideCC() {
1445   if (cC.visible()) {
1446     cC.hide();
1447   }
1448 }
1449 function setCCDate(year, month, day) {
1450   cC.setDate(year, month, day);
1451 }
1452 function changeCCYear(change) {
1453   cC.changeYear(change);
1454 }
1455 function changeCCMonth(change) {
1456   cC.changeMonth(change);
1457 }
1458 document.write(\"<iframe id='CCIframe' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>\");
1459 document.write(\"<div id='CC'></div>\");";
1460
1461      cache_js_file($fpath, $js);
1462     }
1463     add_js_ufile($fpath);
1464
1465  return '';
1466 }
1467
1468 function alert($msg)
1469 {
1470         echo "\n<script type=\"text/javascript\">\n"
1471                 . "<!--\n"
1472                 . "alert('$msg');\n"
1473                 . "-->\n"
1474                 . "</script>\n";
1475 }
1476
1477 if (!function_exists('_vd'))
1478 {
1479         function _vd($mixed, $title = '', $exit = false)
1480         {
1481         $str = (!empty($title) ? ($title .':') : '') .'<pre>';
1482         $str .= print_r($mixed, true); //var_dump($mixed);
1483         $str .= "</pre>\n";
1484                 display_notification('<table><tr><td>'.$str.'</td></tr></table>');
1485         if ($exit)
1486                 exit;
1487         }
1488 }
1489
1490 function _vl($mixed, $title = '', $exit = false)
1491 {
1492         error_log((!empty($title) ? ($title .':') : '') . var_export($mixed, true));
1493         if ($exit)
1494                 exit;
1495 }
1496
1497 function display_backtrace($cond=true, $msg='') {
1498         if ($cond) {
1499                 if ($msg) 
1500                         $str = "<center><span class='headingtext'>$msg</span></center>\n";
1501                 else
1502                         $str = '';
1503                 $str .= get_backtrace(true);
1504                 display_error($str);
1505         }
1506 }
1507
1508 //
1509 // FIXME: $payment_services array will be moved to bank_accounts in 2.4.x
1510 //
1511 if (!isset($payment_services))
1512 {
1513         $payment_services = array(
1514                 'PayPal' => "https://www.paypal.com/xclick?business=<company_email>&item_name=<comment>&amount=<amount>&currency_code=<currency>",
1515         );
1516 }
1517 /*
1518 *       Payment link generation. Options provided during invoice generation:
1519 *       company_email, comment, amount, currency
1520 */
1521 function payment_link($name, $options)
1522 {
1523         global $payment_services;
1524
1525         $link = @$payment_services[$name];
1526
1527         if (!$link) return null;
1528
1529         $patterns = array();
1530         foreach ($options as $id => $option)
1531                 $patterns['<'.$id.'>'] = urlencode($options[$id]);
1532
1533         return strtr($link, $patterns);
1534 }
1535
1536 function trans_editor_link($type, $trans_no)
1537 {
1538         global $path_to_root;
1539
1540         $editor_url = array(
1541                 ST_JOURNAL => "/gl/gl_journal.php?ModifyGL=Yes&trans_no=%d&trans_type=%d",
1542                 ST_BANKPAYMENT => "/gl/gl_bank.php?ModifyPayment=Yes&trans_no=%d&trans_type=%d",
1543                 ST_BANKDEPOSIT => "/gl/gl_bank.php?ModifyDeposit=Yes&trans_no=%d&trans_type=%d",
1544             ST_BANKTRANSFER => "/gl/bank_transfer.php?ModifyTransfer=Yes&trans_no=%d&trans_type=%d",
1545         ST_SALESINVOICE => "/sales/customer_invoice.php?ModifyInvoice=%d",
1546                 ST_CUSTCREDIT => "/sales/credit_note_entry.php?ModifyCredit=%d", // only for free hand credit notes (debtors_trans.order_==0)
1547                 ST_CUSTPAYMENT => "/sales/customer_payments.php?trans_no=%d",
1548                 ST_CUSTDELIVERY => "/sales/customer_delivery.php?ModifyDelivery=%d",
1549 //   16=> Location Transfer,
1550 //   17=> Inventory Adjustment,
1551                 ST_SUPPINVOICE => "/purchasing/supplier_invoice.php?ModifyInvoice=%d",
1552                 ST_SUPPCREDIT =>  "/purchasing/supplier_credit.php?ModifyCredit=%d",
1553 //   21=> Supplier Credit Note,
1554 //   22=> Supplier Payment,
1555 //   25=> Purchase Order Delivery,
1556                 ST_PURCHORDER => "/purchasing/po_entry_items.php?ModifyOrderNumber=%d",
1557 //   28=> Work Order Issue,
1558 //   29=> Work Order Production",
1559                 ST_WORKORDER => "/manufacturing/work_order_entry.php?trans_no=%d",
1560                 ST_SALESORDER => "/sales/sales_order_entry.php?ModifyOrderNumber=%d",
1561                 ST_SALESQUOTE => "/sales/sales_order_entry.php?ModifyQuotationNumber=%d",
1562         //   35=> Cost Update,
1563         );
1564
1565         return !isset($editor_url[$type]) ? '' :
1566                 (is_closed_trans($type, $trans_no) ? set_icon(ICON_CLOSED, _('Closed')) :
1567                         pager_link(_("Edit"), sprintf($editor_url[$type], $trans_no, $type), ICON_EDIT));
1568 }