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