Save/retrieve last document date.
[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 == systypes::po())
22                 $viewer .= "view_po.php";
23         elseif ($type == 20)
24                 $viewer .= "view_supp_invoice.php";
25         elseif ($type == 21)
26                 $viewer .= "view_supp_credit.php";
27         elseif ($type == 22)
28                 $viewer = "view_supp_payment.php";
29         elseif ($type == 25)
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
55         return viewer_link($label, 
56                 "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no", 
57                 $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 == 10)
77                 $viewer .= "view_invoice.php";
78         elseif ($type == 11)
79                 $viewer .= "view_credit.php";
80         elseif ($type == 12)
81                 $viewer .= "view_receipt.php";
82         elseif ($type == 13)
83                 $viewer .= "view_dispatch.php";
84         elseif ($type == 30)
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", 
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 == 4)
115                 $viewer = "bank_transfer_view.php";
116         elseif ($type == 1)
117                 $viewer = "gl_payment_view.php";
118         elseif ($type == 2)
119                 $viewer = "gl_deposit_view.php";
120         elseif ($type == 0)
121                 return $label;
122         else
123                 return null;
124
125         return viewer_link($label, "gl/view/$viewer?trans_no=$trans_no", 
126                 $class, $id,  $icon);
127 }
128
129 //--------------------------------------------------------------------------------------
130
131 function get_inventory_trans_view_str($type, $trans_no, $label="", 
132         $icon=false, $class='', $id='')
133 {
134         $viewer = "inventory/view/";
135
136         if ($type == systypes::inventory_adjustment())
137                 $viewer .= "view_adjustment.php";
138         elseif ($type == systypes::location_transfer())
139                 $viewer .= "view_transfer.php";
140         else
141                 return null;
142         $viewer .= "?trans_no=$trans_no";
143
144         if ($label == "")
145                 $label = $trans_no;
146
147         return viewer_link($label, $viewer, $class, $id,  $icon);
148 }
149
150 //--------------------------------------------------------------------------------------
151
152 function get_manufacturing_trans_view_str($type, $trans_no, $label="", 
153         $icon=false, $class='', $id='')
154 {
155         $viewer = "manufacturing/view/";
156
157         if ($type == 28)
158                 $viewer .= "wo_issue_view.php";
159         elseif ($type == 29)
160                 $viewer .= "wo_production_view.php";
161         elseif ($type == systypes::work_order())
162                 $viewer .= "work_order_view.php";
163         else
164                 return null;
165
166         $viewer .= "?trans_no=$trans_no";
167
168         if ($label == "")
169                 $label = $trans_no;
170
171         return viewer_link($label, $viewer, $class, $id,  $icon);
172 }
173
174 //--------------------------------------------------------------------------------------
175
176 function get_dimensions_trans_view_str($type, $trans_no, $label="", $icon=false, 
177         $class='', $id='')
178 {
179         if ($type == 40)
180                 $viewer = "dimensions/view_dimension.php?trans_no=$trans_no";
181         else
182                 return null;
183
184         if ($label == "")
185                 $label = $trans_no;
186
187         return viewer_link($label, $viewer, $class, $id,  $icon);
188 }
189
190 //--------------------------------------------------------------------------------------
191
192 function get_trans_view_str($type, $trans_no, $label="", $icon=false, 
193         $class='', $id='')
194 {
195         $view_str = get_customer_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
196         if ($view_str != null)
197                 return $view_str;
198
199         $view_str = get_supplier_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
200         if ($view_str != null)
201                 return $view_str;
202
203         $view_str = get_banking_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
204         if ($view_str != null)
205                 return $view_str;
206
207         $view_str = get_inventory_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
208         if ($view_str != null)
209                 return $view_str;
210
211         $view_str = get_manufacturing_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
212         if ($view_str != null)
213                 return $view_str;
214
215         $view_str = get_dimensions_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
216         if ($view_str != null)
217                 return $view_str;
218
219         return null;
220 }
221
222 //--------------------------------------------------------------------------------------
223 // Displays currency exchange rate for given date.
224 // When there is no exrate for today, 
225 // gets it form ECB and stores in local database.
226 //
227 function exchange_rate_display($from_currency, $to_currency, $date_, $edit_rate=false)
228 {
229     global $Ajax;
230
231         if ($from_currency != $to_currency)
232         {
233                 $comp_currency = get_company_currency();
234                 if ($from_currency == $comp_currency)
235                         $currency = $to_currency;
236                 else
237                         $currency = $from_currency;
238                 $rate = 0;
239                 if ($date_ == Today()) {
240                         $rate = get_date_exchange_rate($currency, $date_);
241                         if (!$rate) {
242                                 $rate = get_ecb_rate($currency);
243                                 if ($rate) 
244                                         add_exchange_rate($currency, $date_, $rate, $rate);
245                         }
246                 }
247                 if (!$rate)
248                         $rate = get_exchange_rate_from_home_currency($currency, $date_);
249                 if ($from_currency != $comp_currency)
250                         $rate = 1 / ($rate / get_exchange_rate_from_home_currency($to_currency, $date_));
251
252                 $rate = number_format2($rate, user_exrate_dec());
253                 if ($edit_rate)
254                         text_row(_("Exchange Rate:"), '_ex_rate', $rate, 8, 8, null, "", " $from_currency = 1 $to_currency"); 
255                 else
256                 label_row(_("Exchange Rate:"),"<span id='_ex_rate'>$rate</span> $from_currency = 1 $to_currency" );
257                 $Ajax->addUpdate('_ex_rate','_ex_rate', $rate);
258         }
259 }
260
261 //--------------------------------------------------------------------------------------
262
263 function is_voided_display($type, $id, $label)
264 {
265         global $table_style;
266         $void_entry = get_voided_entry($type, $id);
267
268         if ($void_entry == null)
269                 return false;
270
271         start_table("width=50% $table_style");
272         echo "<tr><td align=center><font color=red>$label</font><br>";
273         echo "<font color=red>" . _("Date Voided:") . " " . sql2date($void_entry["date_"]) . "</font><br>";
274         if (strlen($void_entry["memo_"]) > 0)
275                 echo "<center><font color=red>" . _("Memo:") . " " . $void_entry["memo_"] . "</font></center><br>";
276         echo "</td></tr>";
277         end_table(1);
278
279         return true;
280 }
281
282 //--------------------------------------------------------------------------------------
283
284 function comments_display_row($type, $id)
285 {
286         $comments = get_comments($type, $id);
287         if ($comments and db_num_rows($comments))
288         {
289                 echo "<tr><td colspan=15>";
290         while ($comment = db_fetch($comments))
291         {
292                 echo $comment["memo_"] . "<br>";
293         }
294                 echo "</td></tr>";
295         }
296 }
297
298 //--------------------------------------------------------------------------------------
299
300 function get_comments_string($type, $type_no)
301 {
302         $str_return = "";
303         $result = get_comments($type, $type_no);
304         while ($comment = db_fetch($result))
305         {
306                 if (strlen($str_return))
307                         $str_return = $str_return . " \n";
308                 $str_return = $str_return . $comment["memo_"];
309         }
310         return $str_return;
311 }
312
313 //--------------------------------------------------------------------------------------
314
315 function view_stock_status($stock_id, $description=null, $echo=true)
316 {
317         global $path_to_root;
318         if ($description)
319                 //hyperlink_params_separate($path_to_root . "/inventory/inquiry/stock_status.php", (user_show_codes()?$stock_id . " - ":"") . $description, "stock_id=$stock_id");
320                 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >". (user_show_codes()?$stock_id . " - ":"") . $description."</a>";
321         else
322                 //hyperlink_params_separate($path_to_root . "/inventory/inquiry/stock_status.php", $stock_id, "stock_id=$stock_id");
323                 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >$stock_id</a>";
324         if($echo)
325                 echo $preview_str;
326         return $preview_str;
327 }
328
329 function view_stock_status_cell($stock_id, $description=null)
330 {
331         echo "<td>";
332         view_stock_status($stock_id, $description);
333         echo "</td>";
334 }
335
336 //--------------------------------------------------------------------------------------
337
338 function display_debit_or_credit_cells($value)
339 {
340         if ($value > 0)
341         {
342                 amount_cell($value);
343                 label_cell("");
344         }
345         elseif ($value < 0)
346         {
347                 label_cell("");
348                 amount_cell(abs($value));
349         }
350         else
351         {
352                 //label_cell("");
353                 amount_cell(0);
354                 label_cell("");
355         }
356 }
357
358 //--------------------------------------------------------------------------------------
359
360 function display_customer_trans_tax_details($tax_items, $columns)
361 {
362     while ($tax_item = db_fetch($tax_items))
363     {
364         $tax = number_format2($tax_item['amount'],user_price_dec());
365         if ($tax_item['included_in_price'])
366                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
367                         _("Amount") . ": $tax", "", "colspan=$columns align=right", "align=right");
368         else
369                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
370                         $tax, "colspan=$columns align=right", "align=right");
371     }
372 }
373
374 //--------------------------------------------------------------------------------------
375
376 function display_supp_trans_tax_details($tax_items, $columns)
377 {
378     while ($tax_item = db_fetch($tax_items))
379     {
380         $tax = number_format2(abs($tax_item['amount']),user_price_dec());
381         if ($tax_item['included_in_price'])
382                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
383                         _("Amount") . ": $tax", "colspan=$columns align=right", "align=right");
384         else
385                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
386                         $tax, "colspan=$columns align=right", "align=right");
387     }
388 }
389
390 //--------------------------------------------------------------------------------------
391
392 function display_edit_tax_items($taxes, $columns, $tax_included, $leftspan=0)
393 {
394         $total = 0;
395
396     foreach ($taxes as $taxitem)
397     {
398         if ($tax_included)
399         {
400                 label_row(_("Included") . " " . $taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%) " .
401                         _("Amount:") . " " . number_format2($taxitem['Value'],user_price_dec()), "", "colspan=$columns align=right", "align=right",$leftspan);
402         }
403         else
404         {
405                 label_row($taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%)",
406                         number_format2($taxitem['Value'],user_price_dec()), "colspan=$columns align=right", "align=right",$leftspan);
407                 $total +=  round2($taxitem['Value'], user_price_dec());
408         }
409     }
410
411     return $total;
412 }
413
414 //--------------------------------------------------------------------------------------
415
416 function display_footer_exit()
417 {
418         br(2);
419         end_page();
420         exit;
421 }
422
423 //--------------------------------------------------------------------------------------
424
425 function display_allocations($alloc_result, $total)
426 {
427         global $table_style;
428
429         if (!$alloc_result || db_num_rows($alloc_result) == 0)
430                 return;
431
432     display_heading2(_("Allocations"));
433
434     start_table("$table_style width=80%");
435
436     $th = array( _("Type"), _("Number"), _("Date"), _("Total Amount"),
437         _("Left to Allocate"), _("This Allocation"));
438         table_header($th);
439     $k = $total_allocated = 0;
440
441     while ($alloc_row = db_fetch($alloc_result))
442     {
443
444         alt_table_row_color($k);
445
446         label_cell(systypes::name($alloc_row['type']));
447         label_cell(get_trans_view_str($alloc_row['type'],$alloc_row['trans_no']));
448         label_cell(sql2date($alloc_row['tran_date']));
449         $alloc_row['Total'] = round2($alloc_row['Total'], user_price_dec());
450         $alloc_row['amt'] = round2($alloc_row['amt'], user_price_dec());
451         amount_cell($alloc_row['Total']);
452         //amount_cell($alloc_row['Total'] - $alloc_row['PrevAllocs'] - $alloc_row['amt']);
453         amount_cell($alloc_row['Total'] - $alloc_row['amt']);
454         amount_cell($alloc_row['amt']);
455         end_row();
456
457         $total_allocated += $alloc_row['amt'];
458     }
459     start_row();
460         label_cell(_("Total Allocated:"), "align=right colspan=5");
461         amount_cell($total_allocated);
462         end_row();
463         start_row();
464     label_cell(_("Left to Allocate:"), "align=right colspan=5");
465     $total = round2($total, user_price_dec());
466     amount_cell($total - $total_allocated);
467     end_row();
468
469     end_table(1);
470 }
471
472 //--------------------------------------------------------------------------------------
473
474 function display_allocations_from($person_type, $person_id, $type, $type_no, $total)
475 {
476         switch ($person_type)
477         {
478                 case payment_person_types::customer() :
479                         $alloc_result = get_allocatable_to_cust_transactions($person_id, $type_no, $type);
480                         display_allocations($alloc_result, $total);
481                         return;
482                 case payment_person_types::supplier() :
483                         $alloc_result = get_allocatable_to_supp_transactions($person_id, $type_no, $type);
484                         display_allocations($alloc_result, $total);
485                         return;
486         }
487 }
488
489 //--------------------------------------------------------------------------------------
490 //
491 //      Expands selected quick entry $id into GL posings and adds to cart.
492 //              returns calculated amount posted to bank GL account.
493 //
494 function display_quick_entries(&$cart, $id, $base, $type, $descr='')
495 {
496         $bank_amount = 0;
497         
498         if (!isset($id) || $id == null || $id == "")
499         {
500                 display_error( _("No Quick Entries are defined."));
501                 set_focus('totamount');
502         }
503         else
504         {
505                 if ($type == QE_DEPOSIT)
506                         $base = -$base;
507                 if ($type != QE_SUPPINV)        // only one quick entry on journal/bank transaction
508                         $cart->clear_items();
509                 $qe = get_quick_entry($id);
510                 if ($descr != '') $qe['description'] .= ': '.$descr;
511                 $qe_lines = get_quick_entry_lines($id);
512                 while ($qe_line = db_fetch($qe_lines))
513                 {
514                         switch (strtolower($qe_line['action'])) {
515                                 case "=": // post current base amount to GL account
516                                         $part = $base;
517                                         break;
518                                 case "a": // post amount to GL account and reduce base
519                                         $part = $qe_line['amount'];
520                                         break;
521                                 case "a+": // post amount to GL account and increase base
522                                         $part = $qe_line['amount']; $base += $part;
523                                         break;
524                                 case "a-": // post amount to GL account and reduce base
525                                         $part = $qe_line['amount']; $base -= $part;
526                                         break;
527                                 case "%":       // store acc*amount% to GL account
528                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
529                                         break;
530                                 case "%+":      // ditto & increase base amount
531                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
532                                         $base += $part;
533                                         break;
534                                 case "%-":      // ditto & reduce base amount
535                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
536                                         $base -= $part;
537                                         break;
538                                 case "t": // post taxes calculated on base amount
539                                 case "t+": // ditto & increase base amount
540                                 case "t-": // ditto & reduce base amount
541                                         $taxes = get_taxes_for_item_tax($qe_line['dest_id']);
542                                         $tax_total = 0;
543                                         foreach ($taxes as $index => $item_tax) {
544                                                 if(substr($qe_line['action'],0,1) != 'T')
545                                                         $tax = round2($base * $item_tax['rate'] 
546                                                                 / ($item_tax['rate'] + 100),  user_price_dec());
547                                                 else
548                                                         $tax = round2($base * $item_tax['rate'] / 100,  user_price_dec());
549
550                                                 $gl_code = ($type == QE_DEPOSIT || ($type == QE_JOURNAL && $base < 0)) 
551                                                         ? $item_tax['sales_gl_code'] : $item_tax['purchasing_gl_code'];
552                                                 $tax_total += $tax;
553                                                 if ($type != QE_SUPPINV)
554                                                         $cart->add_gl_item($gl_code, 
555                                                                 $qe_line['dimension_id'], $qe_line['dimension2_id'], 
556                                                                 $tax, $qe['description']);
557                                                 else 
558                                                 {
559                                                         $acc_name = get_gl_account_name($gl_code);
560                                                         $cart->add_gl_codes_to_trans($gl_code, 
561                                                                 $acc_name, $qe_line['dimension_id'], 
562                                                                 $qe_line['dimension2_id'], $tax, $qe['description']);
563                                                 }
564                                         }
565                                         if (strpos($qe_line['action'], '+'))
566                                                 $base += $tax_total;
567                                         elseif (strpos($qe_line['action'], '-'))
568                                                 $base -= $tax_total;
569                                         continue 2;
570                         }
571                         if ($type != QE_SUPPINV)
572                                 $cart->add_gl_item($qe_line['dest_id'], $qe_line['dimension_id'],
573                                         $qe_line['dimension2_id'], $part, $qe['description']);
574                         else 
575                         {
576                                 $acc_name = get_gl_account_name($qe_line['dest_id']);
577                                 $cart->add_gl_codes_to_trans($qe_line['dest_id'], 
578                                         $acc_name, $qe_line['dimension_id'], 
579                                         $qe_line['dimension2_id'], $part, $qe['description']);
580                         }
581                 }
582         }       
583         return $bank_amount;
584 }
585
586
587 function get_js_open_window($width, $height)
588 {
589         $js = "\n<script type=\"text/javascript\">\n"
590                 . "<!--\n"
591                 . "function openWindow(url, title)\n"
592                 . "{\n"
593                 . " var left = (screen.width - $width) / 2;\n"
594                 . " var top = (screen.height - $height) / 2;\n"
595                 . " return window.open(url, title, 'width=$width,height=$height,left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=no,scrollbars=yes');\n"
596                 . "}\n"
597                 . "-->\n"
598                 . "</script>\n";
599         return $js;
600 }
601
602 /*
603   Setting focus on element $name in $form.
604   If $form<0 $name is element id.
605 */
606 function set_focus($name, $form_no=0) {
607   global $Ajax;
608         $Ajax->addFocus(true, $name);
609     $_POST['_focus'] = $name;
610 }
611 //
612 //      Set default focus on first field $name if not set yet
613 //      Returns unique name if $name=null
614 //      
615 function default_focus($name=null, $form_no=0) {
616         if ($name==null) 
617                 $name = uniqid('_el');
618     if (!isset($_POST['_focus'])) {
619           set_focus($name);
620     }
621         return $name;
622 }
623
624 function get_js_png_fix()
625 {
626         $js = "<script type=\"text/javascript\">\n"
627                 . "function fixPNG(myImage)\n"
628                 . "{\n"
629                 . " var arVersion = navigator.appVersion.split(\"MSIE\")\n"
630                 . " var version = parseFloat(arVersion[1])\n"
631         . " if ((version >= 5.5) && (version < 7) && (document.body.filters))\n"
632         . " {\n"
633         . "  var imgID = (myImage.id) ? \"id='\" + myImage.id + \"' \" : \"\"\n"
634                 . "  var imgClass = (myImage.className) ? \"class='\" + myImage.className + \"' \" : \"\"\n"
635                 . "  var imgTitle = (myImage.title) ?\n"
636                 . "    \"title='\" + myImage.title  + \"' \" : \"title='\" + myImage.alt + \"' \"\n"
637                 . "  var imgStyle = \"display:inline-block;\" + myImage.style.cssText\n"
638                 . "  var strNewHTML = \"<span \" + imgID + imgClass + imgTitle\n"
639         . "    + \" style=\\\"\" + \"width:\" + myImage.width\n"
640         . "    + \"px; height:\" + myImage.height\n"
641         . "    + \"px;\" + imgStyle + \";\"\n"
642         . "    + \"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader\"\n"
643         . "    + \"(src=\'\" + myImage.src + \"\', sizingMethod='scale');\\\"></span>\"\n"
644                 . "  myImage.outerHTML = strNewHTML\n"
645         . " }\n"
646                 . "}\n"
647                 . "</script>\n";
648         return $js;
649 }
650
651 function get_js_date_picker()
652 {
653     global $comp_path, $go_debug;
654     $fpath = $comp_path.'/'.user_company().'/js_cache/'.'date_picker.js';
655
656     if (!file_exists($fpath) || $go_debug) {
657
658         global $dateseps, $date_system;
659
660         $how = user_date_format();                              // 0 = us/ca, 1 = eu, au, nz, 2 = jp, sw
661         $sep = $dateseps[user_date_sep()];              // date separator
662         $wstart = (($date_system == 1 || $date_system == 2) ? 6 : ($how == 0 ? 0 : 1));                 // weekstart (sun = 0, mon = 1)
663         $months = array(_("January"),_("February"),_("March"),_("April"),_("May"),_("June"),_("July"),_("August"),_("September"),_("October"),_("November"),_("December"));
664         $wdays = array(_("Su"),_("Mo"),_("Tu"),_("We"),_("Th"),_("Fr"),_("Sa"));
665         $wno = _("W"); // week no
666         $back = _("Back");
667         if ($date_system == 1)
668                 list($cyear, $cmon, $cday) = gregorian_to_jalali(date("Y"), date("n"), date("j"));
669         else if ($date_system == 2)
670                 list($cyear, $cmon, $cday) = gregorian_to_islamic(date("Y"), date("n"), date("j"));
671
672
673         $js = "
674 function positionInfo(object) {
675   var p_elm = object;
676   this.getElementLeft = getElementLeft;
677   function getElementLeft() {
678     var x = 0;
679     var elm;
680     if(typeof(p_elm) == 'object'){
681       elm = p_elm;
682     } else {
683       elm = document.getElementById(p_elm);
684     }
685     while (elm != null) {
686       x+= elm.offsetLeft;
687       elm = elm.offsetParent;
688     }
689     return parseInt(x);
690   }
691   this.getElementWidth = getElementWidth;
692   function getElementWidth(){
693     var elm;
694     if(typeof(p_elm) == 'object'){
695       elm = p_elm;
696     } else {
697       elm = document.getElementById(p_elm);
698     }
699     return parseInt(elm.offsetWidth);
700   }
701   this.getElementRight = getElementRight;
702   function getElementRight(){
703     return getElementLeft(p_elm) + getElementWidth(p_elm);
704   }
705   this.getElementTop = getElementTop;
706   function getElementTop() {
707     var y = 0;
708     var elm;
709     if(typeof(p_elm) == 'object'){
710       elm = p_elm;
711     } else {
712       elm = document.getElementById(p_elm);
713     }
714     while (elm != null) {
715       y+= elm.offsetTop;
716       elm = elm.offsetParent;
717     }
718     return parseInt(y);
719   }
720   this.getElementHeight = getElementHeight;
721   function getElementHeight(){
722     var elm;
723     if(typeof(p_elm) == 'object'){
724       elm = p_elm;
725     } else {
726       elm = document.getElementById(p_elm);
727     }
728     return parseInt(elm.offsetHeight);
729   }
730   this.getElementBottom = getElementBottom;
731   function getElementBottom(){
732     return getElementTop(p_elm) + getElementHeight(p_elm);
733   }
734 }
735 function CC() {
736   var calendarId = 'CC';
737   var currentYear = 0;
738   var currentMonth = 0;
739   var currentDay = 0;
740   var selectedYear = 0;
741   var selectedMonth = 0;
742   var selectedDay = 0;
743   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]'];
744   var wdays = ['$wdays[0]', '$wdays[1]', '$wdays[2]', '$wdays[3]', '$wdays[4]', '$wdays[5]', '$wdays[6]'];
745   var dateField = null;
746   function getProperty(p_property){
747     var p_elm = calendarId;
748     var elm = null;
749     if(typeof(p_elm) == 'object'){
750       elm = p_elm;
751     } else {
752       elm = document.getElementById(p_elm);
753     }
754     if (elm != null){
755       if(elm.style){
756         elm = elm.style;
757         if(elm[p_property]){
758           return elm[p_property];
759         } else {
760           return null;
761         }
762       } else {
763         return null;
764       }
765     }
766   }
767   function setElementProperty(p_property, p_value, p_elmId){
768     var p_elm = p_elmId;
769     var elm = null;
770     if(typeof(p_elm) == 'object'){
771       elm = p_elm;
772     } else {
773       elm = document.getElementById(p_elm);
774     }
775     if((elm != null) && (elm.style != null)){
776       elm = elm.style;
777       elm[ p_property ] = p_value;
778     }
779   }
780   function setProperty(p_property, p_value) {
781     setElementProperty(p_property, p_value, calendarId);
782   }
783   function getDaysInMonth(year, month) {
784 ";
785         if ($date_system == 1)
786                 $js .= "
787     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];
788 ";
789         else if ($date_system == 2)
790                 $js .= "
791     return [30,29,30,29,30,29,30,29,30,29,30,(((((11 * year) + 14) % 30) < 11) ? 30 : 29)][month-1];
792 ";
793         else
794                 $js .= "
795     return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
796 ";
797         $js .= "
798   }
799   function getDayOfWeek(year, month, day) {
800 ";
801         if ($date_system == 1 || $date_system == 2)
802         {
803                 $js .= "
804         function mod(a, b)
805         {
806             return a - (b * Math.floor(a / b));
807         }
808         function jwday(j)
809         {
810             return mod(Math.floor((j + 1.5)), 7);
811         }
812 ";
813         if ($date_system == 1)
814                 $js .= "
815     var epbase, epyear, t;
816     epbase = year - ((year >= 0) ? 474 : 473);
817     epyear = 474 + mod(epbase, 2820);
818     t = day + ((month <= 7) ? ((month - 1) * 31) : (((month - 1) * 30) + 6)) +
819       Math.floor(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 +
820       Math.floor(epbase / 2820) * 1029983 + (1948320.5 - 1);
821 ";
822         else if ($date_system == 2)
823                 $js .= "
824         var t;
825         t = Math.floor((11 * year + 3) / 30) + 354 * year + 30 * month -
826           Math.floor((month - 1) / 2) + day + 1948440 - 385;
827 ";
828         $js .= "
829     return jwday(t);
830 ";
831         }
832         else
833                 $js .= "
834     var date = new Date(year,month-1,day)
835     return date.getDay();
836 ";
837         $js .= "
838   }
839   this.clearDate = clearDate;
840   function clearDate() {
841     dateField.value = '';
842     hide();
843   }
844   this.getWeek = getWeek;
845   function getWeek(year, month, day) {
846 ";
847         if ($how == 0)
848                 $js .= "  day++;";
849         $js .= "
850     var date = new Date(year,month-1,day);
851     var D = date.getDay();
852     if(D == 0) D = 7;
853     date.setDate(date.getDate() + (4 - D));
854     var YN = date.getFullYear();
855     var ZBDoCY = Math.floor((date.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
856     var WN = 1 + Math.floor(ZBDoCY / 7);
857     return WN;
858   }
859   this.setDate = setDate;
860   function setDate(year, month, day) {
861     if (dateField) {
862       if (month < 10) {month = '0' + month;}
863       if (day < 10) {day = '0' + day;}
864 ";
865         if ($how == 0)
866                 $js .= "
867       var dateString = month+'$sep'+day+'$sep'+year;
868 ";
869         else if ($how == 1)
870                 $js .= "
871       var dateString = day+'$sep'+month+'$sep'+year;
872 ";
873         else
874                 $js .= "
875       var dateString = year+'$sep'+month+'$sep'+day;
876 ";
877         $js .= "
878       dateField.value = dateString;
879           setFocus(dateField.name);
880         if(dateField.getAttribute('aspect')=='cdate')
881       setElementProperty('color', (dateField.value==user.date ? 'black':'red'), dateField);
882           if (dateField.className=='searchbox')
883                 dateField.onblur();
884       hide();
885     }
886     return;
887   }
888   this.changeMonth = changeMonth;
889   function changeMonth(change) {
890     currentMonth += change;
891     currentDay = 0;
892     if(currentMonth > 12) {
893       currentMonth = 1;
894       currentYear++;
895     } else if(currentMonth < 1) {
896       currentMonth = 12;
897       currentYear--;
898     }
899     calendar = document.getElementById(calendarId);
900     calendar.innerHTML = calendarDrawTable();
901   }
902   this.changeYear = changeYear;
903   function changeYear(change) {
904     currentYear += change;
905     currentDay = 0;
906     calendar = document.getElementById(calendarId);
907     calendar.innerHTML = calendarDrawTable();
908   }
909   function getCurrentYear() {
910     var year = new Date().getYear();
911     if(year < 1900) year += 1900;
912     return year;
913   }
914   function getCurrentMonth() {
915     return new Date().getMonth() + 1;
916   }
917   function getCurrentDay() {
918     return new Date().getDate();
919   }
920   function calendarDrawTable() {
921     var dayOfMonth = 1;
922     var wstart = $wstart;
923     var wno = '&nbsp;$wno&nbsp;';
924     var validDay = 0;
925     var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
926     var daysInMonth = getDaysInMonth(currentYear, currentMonth);
927     var css_class = null; //CSS class for each day
928     var table = \"<table cellspacing='0' cellpadding='0' border='0'>\";
929     table += \"<tr class='header'>\";
930     table += \"  <td colspan='2' class='previous'><a href='javascript:changeCCMonth(-1);'>&lt;</a><br><a href='javascript:changeCCYear(-1);'>&laquo;</a></td>\";
931     table += \"  <td colspan='4' class='title'>\" + months[currentMonth-1] + \"<br>\" + currentYear + \"</td>\";
932     table += \"  <td colspan='2' class='next'><a href='javascript:changeCCMonth(1);'>&gt;</a><br><a href='javascript:changeCCYear(1);'>&raquo;</a></td>\";
933     table += \"</tr>\";
934     table += \"<tr>\";
935     table += \"<th class='weekno'>\"+wno+\"</th>\";
936     for (var n=0; n<7; n++)
937         table += \"<th>\" + wdays[(wstart+n)%7]+\"</th>\";
938     table += \"</tr>\";
939     for(var week=0; week < 6; week++) {
940       table += \"<tr>\";
941       for(var n=0; n < 7; n++) {
942         dayOfWeek = (wstart+n)%7;
943         if(week == 0 && startDayOfWeek == dayOfWeek) {
944           validDay = 1;
945         } else if (validDay == 1 && dayOfMonth > daysInMonth) {
946           validDay = 0;
947         }
948         if (n==0)
949         {
950                 if (dayOfMonth > daysInMonth)
951                         table += \"<td class='empty'>&nbsp;</td>\";
952                 else
953                         table += \"<td class='weekno'>\"+getWeek(currentYear, currentMonth, dayOfMonth)+\"</td>\";
954         }
955         if(validDay) {
956           if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
957             css_class = 'current';
958 ";
959         if ($date_system == 1 || $date_system == 2)
960                 $js .= "
961           } else if (dayOfWeek == 5) {
962 ";
963         else
964                 $js .= "
965           } else if (dayOfWeek == 0 || dayOfWeek == 6) {
966 ";
967                 $js .= "
968             css_class = 'weekend';
969           } else {
970             css_class = 'weekday';
971           }
972           table += \"<td><a class='\"+css_class+\"' href=\\\"javascript:setCCDate(\"+currentYear+\",\"+currentMonth+\",\"+dayOfMonth+\")\\\">\"+dayOfMonth+\"</a></td>\";
973           dayOfMonth++;
974         } else {
975           table += \"<td class='empty'>&nbsp;</td>\";
976         }
977       }
978       table += \"</tr>\";
979     }
980     table += \"<tr class='header'><th colspan='8' style='padding: 3px;text-align:center;'><a href='javascript:hideCC();'>$back</a></td></tr>\";
981     table += \"</table>\";
982     return table;
983   }
984   this.show = show;
985   function show(field) {
986     can_hide = 0;
987     if (dateField == field) {
988       return;
989     } else {
990       dateField = field;
991     }
992     if(dateField) {
993       try {
994         var dateString = new String(dateField.value);
995         var dateParts = dateString.split('$sep');
996 ";
997         if ($how == 0)
998                 $js .= "
999         selectedMonth = parseInt(dateParts[0],10);
1000         selectedDay = parseInt(dateParts[1],10);
1001         selectedYear = parseInt(dateParts[2],10);
1002 ";
1003         else if ($how == 1)
1004                 $js .= "
1005         selectedDay = parseInt(dateParts[0],10);
1006         selectedMonth = parseInt(dateParts[1],10);
1007         selectedYear = parseInt(dateParts[2],10);
1008 ";
1009         else
1010                 $js .= "
1011         selectedYear = parseInt(dateParts[0],10);
1012         selectedMonth = parseInt(dateParts[1],10);
1013         selectedDay = parseInt(dateParts[2],10);
1014 ";
1015         $js .= "
1016       } catch(e) {}
1017     }
1018     if (!(selectedYear && selectedMonth && selectedDay)) {
1019 ";
1020         if ($date_system == 1 || $date_system == 2)
1021         {
1022                 $js .= "
1023       selectedMonth = $cmon;
1024       selectedDay = $cday;
1025       selectedYear = $cyear;
1026 ";
1027         }
1028         else
1029         {
1030                 $js .= "
1031       selectedMonth = getCurrentMonth();
1032       selectedDay = getCurrentDay();
1033       selectedYear = getCurrentYear();
1034 ";
1035         }
1036         $js .= "
1037     }
1038     currentMonth = selectedMonth;
1039     currentDay = selectedDay;
1040     currentYear = selectedYear;
1041     if(document.getElementById){
1042       calendar = document.getElementById(calendarId);
1043       calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);
1044       var fieldPos = new positionInfo(dateField);
1045       var calendarPos = new positionInfo(calendarId);
1046       var x = fieldPos.getElementLeft();
1047       var y = fieldPos.getElementBottom();
1048       setProperty('left', x + 'px');
1049       setProperty('top', y + 'px');
1050       setProperty('display', 'block');
1051       if (document.all) {
1052         setElementProperty('left', x + 'px', 'CCIframe');
1053         setElementProperty('top', y + 'px', 'CCIframe');
1054         setElementProperty('width', calendarPos.getElementWidth() + 'px', 'CCIframe');
1055         setElementProperty('height', calendarPos.getElementHeight() + 'px', 'CCIframe');
1056         setElementProperty('display', 'block', 'CCIframe');
1057       }
1058     }
1059   }
1060   this.hide = hide;
1061   function hide() {
1062     if(dateField) {
1063       setProperty('display', 'none');
1064       setElementProperty('display', 'none', 'CCIframe');
1065       dateField = null;
1066     }
1067   }
1068   this.visible = visible;
1069   function visible() {
1070     return dateField
1071   }
1072   this.can_hide = can_hide;
1073   var can_hide = 0;
1074 }
1075 var cC = new CC();
1076 function date_picker(textField) {
1077   cC.show(textField);
1078 }
1079 function hideCC() {
1080   if (cC.visible()) {
1081     cC.hide();
1082   }
1083 }
1084 function setCCDate(year, month, day) {
1085   cC.setDate(year, month, day);
1086 }
1087 function changeCCYear(change) {
1088   cC.changeYear(change);
1089 }
1090 function changeCCMonth(change) {
1091   cC.changeMonth(change);
1092 }
1093 document.write(\"<iframe id='CCIframe' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>\");
1094 document.write(\"<div id='CC'></div>\");";
1095
1096      cache_js_file($fpath, $js);
1097     }
1098     add_js_ufile($fpath);
1099
1100  return '';
1101 }
1102
1103 function alert($msg)
1104 {
1105         echo "\n<script type=\"text/javascript\">\n"
1106                 . "<!--\n"
1107                 . "alert('$msg');\n"
1108                 . "-->\n"
1109                 . "</script>\n";
1110 }
1111
1112 if (!function_exists('_vd'))
1113 {
1114         function _vd($mixed, $title = '', $exit = false)
1115         {
1116         // Only the site admin is able to proceed here.
1117         $str = (!empty($title) ? ($title .':') : '') .'<pre>';
1118         $str .= print_r($mixed, true); //var_dump($mixed);
1119         $str .= "</pre>\n";
1120                 display_error('<table><tr><td>'.$str.'</td></tr></table>');
1121         if ($exit)
1122                 exit;
1123         }
1124 }
1125
1126 function display_backtrace($cond=true, $msg='') {
1127
1128         if ($cond) {
1129                 if ($msg) 
1130                         $str = "<center><span class='headingtext'>$msg</span></center>\n";
1131                 else
1132                         $str = '';
1133                 $str .= '<table border=0>';
1134         $trace = debug_backtrace();
1135                 foreach($trace as $trn => $tr) {
1136                         if (!$trn) continue;
1137                         $str .= '<tr><td>';
1138                         $str .= $tr['file'].':'.$tr['line'].': ';
1139                         $str .= '</td><td>';
1140                         if (isset($tr['type'])) {
1141                                 if($tr['type'] == '::') {
1142                                         $str .= $tr['class'].'::';
1143                                 } else if($tr['type'] == '->') {
1144                                         $str .= '('.$tr['class'].' Object)'.'->';
1145                                 }
1146                         }
1147                         foreach($tr['args'] as $n=>$a) {
1148                                 if (is_object($tr['args'][$n]))
1149                                         $tr['args'][$n] = "(".get_class($tr['args'][$n])." Object)";
1150                                 if (is_array($tr['args'][$n]))
1151                                         $tr['args'][$n] = "(Array[".count($tr['args'][$n])."])";
1152                                 else
1153                                         $tr['args'][$n] = "'".$tr['args'][$n]."'";
1154                         }
1155                         $str .= $tr['function'].'('. implode(',',$tr['args']).')</td>';
1156
1157                         $str .= '</tr>';
1158                 }
1159                 
1160                 $str .= '</table>';
1161         display_error($str);
1162         }
1163 }
1164
1165 ?>