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