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