Source

Selador / merchant / merchants_calculations.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
<?php
//supermarket ("grosshandel")
if ($f ==4)
{
    if (isset ($_REQUEST['ok']))
    {
        //ueberpruefe: wurden alle felder eingegeben?
        if (!isset($_REQUEST['offerkind']))
            $merchant_err = "Fehlende Eingabe: Was willst du denn eintauschen?<br>";
        else
        {
            if (!isset($_REQUEST['offersize']))
                $merchant_err = "Fehlende Eingabe: Wieviel willst du denn eintauschen?<br>";
            else
            {
                if (!isset($_REQUEST['searchkind']))
                    $merchant_err = "Fehlende Eingabe: Was suchst du denn?<br>";

                //*******ueberall wurde was eingetragen... aber auch das richtige?!?
                else
                {
                    $offerkind = abs ((int) $_REQUEST['offerkind']);
                    $offersize = abs ((int) $_REQUEST['offersize']);
                    $searchkind = (int) $_REQUEST['searchkind'];

                    if (!$me->activevillage->can_spend_type ($offerkind, $offersize))
                        $merchant_err = "Fehler: Netter Versuch. Aber so viele Rohstoffe haben wir nicht.";
                    else
                    {
                        switch ($searchkind)
                        {
                            case 1:
                            case 2:
                            case 3:
                                $min_amount = 2;
                                break;
                            case 4:
                                $min_amount = 5;
                                break;
                        }

                        if ($offersize < $min_amount)
                            $merchant_err = "Fehler: Du musst mindestens ".$min_amount." Rohstoffe eintauschen.";
                        else
                        {
                            $old_value = $me->activevillage->ress[$offerkind]; //fuers debuggen
                            $offersize -= ($offersize % $min_amount);
                            $me->activevillage->spend_type ($offerkind, $offersize);
                            $new_value = $me->activevillage->ress[$offerkind];
                            if ($searchkind != 4)
                            {
                                $me->activevillage->spend_type ($searchkind, -(floor ($offersize/2)));
                                $got = floor ($offersize/2);
                            }
                            else
                            {
                                $me->activevillage->spend_type ($searchkind, -(floor ($offersize/5)));
                                $got = floor ($offersize/5);
                            }

                            if (1 == $offerkind)
                                    $offerkind = "Holz";
                            if (2 == $offerkind)
                                    $offerkind = "Stein";
                            if (3 == $offerkind)
                                    $offerkind = "Eisen";
                            if (4 == $offerkind)
                                    $offerkind = "Gold";

                            if (1 == $searchkind)
                                    $searchkind = "Holz";
                            if (2 == $searchkind)
                                    $searchkind = "Stein";
                            if (3 == $searchkind)
                                    $searchkind = "Eisen";
                            if (4 == $searchkind)
                                    $searchkind = "Gold";
                            $merchant_success = "Erfolgreich eingetauscht: " . $offersize . " " . $offerkind . " gegen " . $got. " " . $searchkind;
                            log_debug("Grosshaendler: ".$offersize." ".$offerkind." eingetauscht gegen ".$got." ".$searchkind.". Rohstoffe vorher: ".$old_value." ".$offerkind.", nachher: ".$new_value);
                        }
                    }
                }
            }
        }
    }
}





//send ressources
if ($f == 1)
{
    $step = 1;
    //wurde soeben der schicken-Button oder der "wirklich schicken"-button gedrueckt?
    //EIngaben ueberpruefen!
    if ((isset ($_REQUEST['schicken']) || (isset ($_REQUEST['really']))) && (!$me->activeoutpostid))
    {
            $holz = (int)abs ($_REQUEST['holz']);
            $stein = (int)abs ($_REQUEST['stein']);
            $eisen = (int)abs ($_REQUEST['eisen']);
            $gold = (int)abs ($_REQUEST['gold']);
            $counter = (int)abs ($_REQUEST['counter']);

        if ($holz == 0 && $stein == 0 && $eisen == 0 && $gold == 0)
            $merchant_err = "Wenn du nichts verschicken willst, bleib ich einfach zu Hause?!";
        else
        {
            $enoughcash = $me->activevillage->can_spend_single ($holz, $stein, $eisen, $gold);
            //too much wood
            if (!$enoughcash[1])
            {
              $merchant_err = "Dein H&auml;ndler sagt: Soviel Holz haben wir nicht. Sollen wir noch schnell welches hacken gehen?";
            }
            //too much stone
            else
            {
                if (!$enoughcash[2])
                {
                    $merchant_err = "Dein H&auml;ndler sagt: Soviel Stein haben wir nicht. Aber ich habe geh&ouml;rt, B&auml;cker M&uuml;ller hat noch etwas Brot von letzter Woche.";
                }
            //too much stone
                else
                {
                    if (!$enoughcash[3])
                    {
                        $merchant_err = "Dein H&auml;ndler sagt: Soviel Eisen haben wir nicht. Wir k&ouml;nnten stattdessen einfach unsere R&uuml;stungen einschmelzen .";
                    }
          //too much gold
                    else
                    {
                        if (!$enoughcash[4])
                        {
                            $merchant_err = "Dein H&auml;ndler sagt: Soviel Gold haben wir nicht. Wir sind hier ja nicht im Wunderland.";
                        }
          //non-existing coordinates
                        else
                        {
                            if (isset ($_REQUEST['x']) && isset ($_REQUEST['y']) && is_numeric ($_REQUEST['x']) && is_numeric ($_REQUEST['y']) && ($_REQUEST['x'] != 0) && ($_REQUEST['y'] != 0))
                            {
                                $x = $_REQUEST['x'];
                                $y = $_REQUEST['y'];
                                $query_villages = "select name,uid,villageid,outpost_of from village where x=".$x." and y=".$y;

                                if ($result_villages = mysql_query($query_villages))
                                {
                                    if (!($villagerow = mysql_fetch_array ($result_villages)))
                                        $merchant_err =  "Dein H&auml;ndler sagt: Dort gibt es keine Stadt. Ohne Empfangsquittung gebe ich nirgends meine Waren ab.";
                                    else
                                    {
                                        if ($me->sat_by)
                                        {
                                            if ($villagerow['uid'] != $me->uid)
                                            {
                                                $merchant_err = "Als Sitter darfst du nur innerhalb deiner eigenen St&auml;dte handeln. ";
                                            }
                                        }
                                    }
                                    mysql_free_result ($result_villages);
                                }
                                else
                                {
                                    $merchant_err = "Es ist leider ein DB-Fehler aufgetreten. Bitte nochmal probieren.";
                                    log_err ("handel.php: Cannot find village by coordinates. Query: ".$query.", ".mysql_error ());
                                }
                            }
                            else
                            {
                                if (isset ($_REQUEST['villagedd']) && $_REQUEST['villagedd'] != "")
                                {
                                    $query = "select * from village where villageid=".(int)$_REQUEST['villagedd'];

                                    if (!($res = mysql_query ($query)))
                                    {
                                        $merchant_err = "Leider ist ein DB-Fehler aufgetreten. Bitte nochmal probieren";
                                        log_err ("Error while trying to find village that was given by villagedd. Query: ".$query.", ".mysql_error ());
                                    }
                                    else
                                    {
                                        if (mysql_num_rows ($res))
                                        {
                                            $villagerow = mysql_fetch_array ($res);
                                            $x = $_REQUEST['x'] = $villagerow['x'];
                                            $y = $_REQUEST['y'] = $villagerow['y'];
                                        }
                                        else
                                        {
                                            $merchant_err = "Diese Stadt wurde nicht gefunden??";
                                            log_err ("Cannot find village ".$_REQUEST['villagedd']." given by villagedd. Query: ".$query);
                                        }
                                    }
                                }
                                else
                                {
                                    if (isset ($_REQUEST['vname']))
                                    {
                                        $vsearch = village_byname ($_REQUEST['vname']);

                                        if (!$vsearch)
                                            $merchant_err = "Es wurde leider keine Stadt mit diesem Namen gefunden";
                                        else
                                        {
                                            // If the result is a two-dimensional array, we have to create the
                                            // drop-down menu
                                            if (is_array ($vsearch) && is_array (reset ($vsearch)))
                                            {
                                                // But only if there is more than one item
                                                if (count ($vsearch) == 1)
                                                {
                                                    $firstv = reset ($vsearch);
                                                    $villagerow = $firstv;
                                                    $_REQUEST['vname'] = $firstv['name'];
                                                    $x = $_REQUEST['x'] = $firstv['x'];
                                                    $y = $_REQUEST['y'] = $firstv['y'];
                                                }
                                                else
                                                {
                                                    $dd = "<select name=\"villagedd\" size=\"1\">";
                                                    foreach ($vsearch as $vidx => $thisv)
                                                    {
                                                        $dd .= "<option value=\"".$thisv['villageid']."\">".$thisv['name']." (".$thisv['x']."|".$thisv['y'].") von ".$thisv['user']."</option>";
                                                    }
                                                    $dd .= "</select>\n";
                                                }
                                            }
                                            else
                                            {
                                                if (is_array ($vsearch))
                                                {
                                                    $villagerow = $vsearch;
                                                    $_REQUEST['vname'] = $vsearch['name'];
                                                    $x = $_REQUEST['x'] = $vsearch['x'];
                                                    $y = $_REQUEST['y'] = $vsearch['y'];
                                                }
                                                else
                                                    $merchant_err = "Es wurde leider keine Stadt mit diesem Namen gefunden";
                                            }
                                        }
                                    }
                                }
                            }

                            if (!isset ($dd))
                            {
                                if ($villagerow['outpost_of'] > 0)
                                    $merchant_err = "Ich kann keine Au&szlig;enposten beliefern, nur St&auml;dte.";
                                else
                                {
                                    if ($villagerow['villageid'] == $me->activevillageid)
                                        $merchant_err = "Na das ist ja nicht soo weit, da lass ich den Wagen daheim.";
                                    else
                                    {
                                        $allinall = $holz + $stein + $eisen + $gold;
                                        $merchants_needed = ceil ($allinall / ($me->merchant_cap));
                                        calcMerchants();
                                        if ($merchants_needed > (($me->activevillage->merchants)-$merchants_gone))
                                            $merchant_err = "So viele H&auml;ndler sind wir nicht.";
                                        else
                                        {
                                            if (!isset ($merchant_err))
                                                $step = 2;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //if all is ok, we search for the name and the owner of the village
        if (2 == $step)
        {
            $query_owner = "select user from user where uid=".$villagerow['uid'].";";

            if ($result_owner = mysql_query($query_owner))
            {
                 if ($row_owner = mysql_fetch_array ($result_owner))
                {
                    //calculate the distance
                    $start_x = $me->activevillage->x;
                    $start_y = $me->activevillage->y;
                    $distance_a = ($x - $start_x) * ($x - $start_x);
                    $distance_b = ($y - $start_y) * ($y - $start_y);
                    $distance = sqrt ($distance_a + $distance_b);

                    //calculate duration
                    $time = $distance / ($me->merchant_speed * WORLD_MERCH_SPEED);

                    $timestring = calcDuration($distance, $me);
                }
            }
            else
            {
                log_err ("handel.php: Cannot find target user. Query: ".$query.", ".mysql_error ());
                $merchant_err = "Leider ist ein DB-Fehler aufgetreten";
            }

            if (isset ($_REQUEST['really']))
            {
                if ($_REQUEST['counter'] == $me->reload_counter)
                {
                    require_once ("php/event.php");


                    // Wirklich abschicken, Tests wurden ja abgeschlossen :)
                    $query_transport = "insert into transport values (NULL,".$holz.",".$stein.",".$eisen.",".$gold.",".$me->activevillageid.",".$villagerow['villageid'].",0,".$merchants_needed.",'".mysql_real_escape_string (strip_tags (trim ($_REQUEST['trade_msg'])))."')";

                    if (!mysql_query ($query_transport))
                    {
                        log_err ("Cannot send merchants. Query: ".$query_transport.", ".mysql_error ());
                        $merchant_err = "<b>Leider k&ouml;nnen die H&auml;dler wegen eines Datenbankfehlers gerade nicht abgeschickt werden :(<br>Bitte sp&auml;ter nochmal probieren</b>";
                    }
                    else
                    {
                        $transportid = mysql_insert_id ();
                        $query = "insert into event (uid1, village1, uid2, village2, type, param, param2, timestamp, flag) values (".$me->uid.", ".$me->activevillageid.", ".$villagerow['uid'].", ".$villagerow['villageid'].", ".TRANSPORT.", ".$transportid.", ".(int)($time*3600).", addtime(now(), sec_to_time(".(int)($time*3600).")), 1)";

                        // echo $query;
                        if (!mysql_query ($query))
                        {
                            log_err ("Cannot send merchants. Query: ".$query.", ".mysql_error ());
                            $merchant_err = "<b>Leider k&ouml;nnen die H&auml;dler wegen eines Datenbankfehlers gerade nicht abgeschickt werden :(<br>Bitte sp&auml;er nochmal probieren</b>";
                        }

                        $me->reload_counter++;
                        // echo $query_transport;
                        $step = 3;
                        unset ($_REQUEST['x']);
                        unset ($_REQUEST['y']);
                        unset ($_REQUEST['vname']);




                    // Händler unterwegs neu berechnen FIXME: This could be optimized
                    $query_transport = "select A.*, B.name as from_vill, B.x as from_x, B.y as from_y, C.name as to_vill, C.x as to_x, C.y as to_y from transport A join village B on (A.village1=B.villageid) join village C on (A.village2=C.villageid) where A.village1=".$me->activevillageid." or (A.village2=".$me->activevillageid." and A.flag=0);";

                    if ($result_transport = mysql_query($query_transport))
                    {
                        while (($transportrow = mysql_fetch_array ($result_transport)))
                        {
                            if ($transportrow['village1'] == $me->activevillageid)
                            {
                                $mymerchants[$transportrow['merchantid']] = $transportrow;
                                //$merchants_gone += $transportrow['merchants'];
                            }
                            else
                                $othermerchants[$transportrow['merchantid']] = $transportrow;
                        }
                        mysql_free_result($result_transport);
                    }

                    //echo '<h1>gone: </h1>'.$merchants_gone;
                    $merchants_gone += $merchants_needed;
                    //echo '<h1>gone after: </h1>'.$merchants_gone;

                    //calcMerchants();

                    //FIXME merchants don't refresh immediately


                    // Nun fehlt noch die Zeit f&uuml;r den gerade losgeschickten Händler, der ja erst vom Eventhandler
                    // eingesetzt werden w&uuml;rde
                    $gui->my_transports[$transportid] = (int)($time*3600);
                    $gui->all_transports[$transportid] = (int)($time*3600);

                    // Rohstoffe werden ausgegeben - hah!
                    $me->activevillage->spend ($holz, $stein, $eisen, $gold);

                    unset ($holz);
                    unset ($gold);
                    unset ($eisen);
                    unset ($stein);
                }
            }
            else
                $_REQUEST['schicken'] = "bla";	// Evil hack to prevent redisplay of target dialog
            }
        }
    }
}


//buy offer from market
//buy offer
if ($f == 2)
{
    if (isset ($_REQUEST['o']))
    {
        //$offerid = (int)$_REQUEST['o'];
        $offerid = (int)key($_POST['o']);
        $query = "select A.*, B.x, B.y from offers A join village B on (A.villageid=B.villageid) where A.offerid=".$offerid;



        if (!($res = mysql_query ($query)))
        {
            log_err ("Cannot fetch offer when accepting. Query: ".$query.", ".mysql_error());
        }
        else
        {
            if (!($row = mysql_fetch_array ($res)))
            {
                log_err ("No rows found when accepting offer. Query: ".$query);
            }
            else
            {
                calcMerchants();
                $number_on_market = (int)$row['number'];
                $number_tmp = $_POST['number'];
                $number_wanted = $number_tmp[$offerid];
                if (!$me->activevillage->can_spend_type ($row['searchkind'], $row['searchsize'] * $number_wanted))
                    $merchant_err = "<b>Nicht gen&uuml;gend Rohstoffe hier</b>";
                else
                {
                    if ($row['searchsize'] *$number_wanted > $merchants_here * $me->merchant_cap)
                        $merchant_err = "<b>Nicht gen&uuml;gend H&auml;ndler hier - Cheater ;)</b>";
                    else
                    {

                                        //echo '<h1>yeahi!</h1>'.$query;

                        $merchants_needed = ceil ($row['searchsize'] * $number_wanted / $me->merchant_cap); // diese Haendler werden insgesamt gebraucht!
                        $merchant_per_offer = ceil ($row['searchsize'] / $me->merchant_cap);

                        //calculate the distance
                            $start_x = $me->activevillage->x;
                            $start_y = $me->activevillage->y;
                            $distance_a = ($row['x'] - $start_x) * ($row['x'] - $start_x);
                            $distance_b = ($row['y'] - $start_y) * ($row['y'] - $start_y);
                            $distance = sqrt ($distance_a + $distance_b);

                                //calculate duration
                            $time = $distance /($me->merchant_speed) / WORLD_MERCH_SPEED;


                        //CHECKME is this really necessary?
                        $mhours = (int) $time;
                        $rest = $time - $mhours;
                        $mminutes = (int) ($rest * 60);
                        $rest2 = ($rest*60) - $mminutes;
                        $mseconds = round ($rest2 * 60);

                        $mminutes += (int)($mseconds/60);
                        $mseconds = ($mseconds % 60);

                        if ($mhours < 10)
                                $mhours = "0".$mhours;
                        if ($mminutes < 10)
                                $mminutes = "0".$mminutes;
                        if ($mseconds < 10)
                                $mseconds = "0".$mseconds;

                        require_once ("php/event.php");
                        $query_transport = "";


                        // Wirklich abschicken, Tests wurden ja abgeschlossen :)
                        //for ($helpme=0;$helpme < $number_wanted;$helpme++)
                        {
                        $query_transport = "insert into transport values (NULL, ".offer_query ($row['searchkind'], ($row['searchsize'] * $number_wanted))." ,".$me->activevillageid.",".$row['villageid'].",0,".($merchant_per_offer * $number_wanted) .", '');";

                        if (!mysql_query ($query_transport))
                        {
                            log_err ("Cannot send merchants for offer from target. Query: ".$query_transport.", ".mysql_error ());
                            $merchant_err = "<b>Leider k&ouml;nnen die H&auml;dler wegen eines Datenbankfehlers gerade nicht abgeschickt werden :(<br>Bitte sp&auml;ter nochmal probieren</b>";
                        }
                        else
                        {
                            $transportid = mysql_insert_id ();
                            $query = "insert into event (uid1, village1, uid2, village2, type, param, param2, timestamp, flag) values (".$me->uid.", ".$me->activevillageid.", ".$row['uid'].", ".$row['villageid'].", ".TRANSPORT.", ".$transportid.", ".(int)($time*3600).", addtime(now(), sec_to_time(".(int)($time*3600).")), 1)";
                            if (!mysql_query ($query))
                            {
                                log_err ("Cannot send merchants for offer from target. Query: ".$query.", ".mysql_error ());
                                $merchant_err = "<b>Leider k&ouml;nnen die H&auml;dler wegen eines Datenbankfehlers gerade nicht abgeschickt werden :(<br>Bitte sp&auml;er nochmal probieren</b>";
                            }
                            else
                            {
                                // Wirklich abschicken, Tests wurden ja abgeschlossen :)
                                $query_transport = "insert into transport values (NULL, ".offer_query ($row['offerkind'], ($row['offersize']*$number_wanted))." , ".$row['villageid'].", ".$me->activevillageid.", 0, ".($row['merchants']*$number_wanted).", '')";

                                // echo $query_transport;
                                if (!mysql_query ($query_transport))
                                {
                                    log_err ("Cannot send merchants for offer from receiver. Query: ".$query_transport.", ".mysql_error ());
                                    $merchant_err = "<b>Leider k&ouml;nnen die H&auml;dler wegen eines Datenbankfehlers gerade nicht abgeschickt werden :(<br>Bitte sp&auml;ter nochmal probieren</b>";
                                }
                                else
                                {
                                    $transportid = mysql_insert_id ();
                                    $query = "insert into event (uid1, village1, uid2, village2, type, param, param2, timestamp, flag) values (".$row['uid'].", ".$row['villageid'].", ".$me->uid.", ".$me->activevillageid.", ".TRANSPORT.", ".$transportid.", ".(int)($time*3600).", addtime(now(), sec_to_time(".(int)($time*3600).")), 1)";

                                    // echo $query;
                                    if (!mysql_query ($query))
                                    {
                                        log_err ("Cannot send merchants for offer from receiver. Query: ".$query.", ".mysql_error ());
                                        $merchant_err = "<b>Leider k&ouml;nnen die H&auml;dler wegen eines Datenbankfehlers gerade nicht abgeschickt werden :(<br>Bitte sp&auml;er nochmal probieren</b>";
                                    }
                                    else
                                    {
                                        if ($already_visited == false)
                                        {
                                            //wenn alle angebote angenommen wurden, wird das angebot geloescht
                                            //ansonsten nur erniedrigt
                                            if ($number_wanted >= $number_on_market)
                                                $query = "delete from offers where offerid=".$offerid;
                                            else
                                                $query = "update offers set number=number-".$number_wanted." where offerid=".$offerid;
                                            if (!mysql_query ($query))
                                            {
                                                log_err ("Cannot delete offer entry when accepting offer. Query: ".$query.", ".mysql_error());
                                            }
                                        }
                                    /*	else
                                        {*/
                                            $me->reload_counter++;
                                            $already_visited = true;
                                            // Händler unterwegs neu berechnen FIXME: This could be optimized
                                            $merchants_gone = 0;
                                            $query_transport = "select A.*, B.name as from_vill, B.x as from_x, B.y as from_y, C.name as to_vill, C.x as to_x, C.y as to_y from transport A join village B on (A.village1=B.villageid) join village C on (A.village2=C.villageid) where A.village1=".$me->activevillageid." or (A.village2=".$me->activevillageid." and A.flag=0);";

                                            if ($result_transport = mysql_query($query_transport))
                                            {
                                                while (($transportrow = mysql_fetch_array ($result_transport)))
                                                {
                                                    if ($transportrow['village1'] == $me->activevillageid)
                                                    {
                                                        $mymerchants[$transportrow['merchantid']] = $transportrow;
                                                        $merchants_gone += $transportrow['merchants'];
                                                    }
                                                    else
                                                        $othermerchants[$transportrow['merchantid']] = $transportrow;
                                                }
                                                mysql_free_result($result_transport);
                                            }

                                            // Rohstoffe werden ausgegeben - hah!
                                            $tmp_costs = array (0, 0, 0, 0, 0, 0);
                                            $tmp_costs[$row['searchkind']] = $row['searchsize']*$number_wanted;
                                            $me->activevillage->spend_array ($tmp_costs);
                                            $merchants_here = $me->activevillage->merchants - $merchants_gone;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}



//create new offers
if (isset ($_REQUEST['ok']) && $f < 4)
{
//ueberpruefe: wurden alle felder eingegeben?
	    if (!isset($_REQUEST['offerkind']))
		$merchant_err = "Fehlende Eingabe: Was willst du denn verkaufen?<br>";
	else
	{
		if ((int)$_POST['offersize']== 0)
			$merchant_err = "Fehlende Eingabe: Wieviel willst du denn verkaufen?<br>";
		else
		{
			if (!isset($_REQUEST['searchkind']))
				$merchant_err = "Fehlende Eingabe: Was suchst du denn?<br>";
			else
			{
				if ((int)$_POST['searchsize']== 0)
					$merchant_err = "Fehlende Eingabe: Wieviel suchst du denn?<br>";
				//*******ueberall wurde was eingetragen... aber auch das richtige?!?
				else
				{
					if ((int) $_REQUEST['how_many_offers'] > 0)
					{
						$num_offers = (int)abs ($_REQUEST['how_many_offers']);
						$offerkind = (int)abs ($_REQUEST['offerkind']);
						$offersize = (int)abs ($_REQUEST['offersize']);
						$searchkind = (int)abs ($_REQUEST['searchkind']);
						$searchsize = (int)abs ($_REQUEST['searchsize']);

						//FIXME refresh $merchants_gone
						$merchants_here = $me->activevillage->merchants - $merchants_gone;

						$number_merchants = ceil ($offersize / $me->merchant_cap);

						if (!$me->activevillage->can_spend_type ($offerkind, ($offersize * $num_offers)))
							$merchant_err = "Netter Versuch. Aber so viele Rohstoffe haben wir nicht.";
						else
						{
							if (0 == $merchants_here)
								$merchant_err = "Keine H&auml;ndler vorhanden!";
							else
							{
                                calcMerchants();
								if (($number_merchants * $num_offers) > $merchants_here)
								{
									$merchant_err = "Wir sind zu wenige f&uuml;r den ganzen Kram!";
								}
								else
								{
									//stimmt das verhältnis zeischen suchen/bieten?
									if ((($offerkind != 4) && ($searchsize > (5 * $offersize))) ||  (($offerkind == 4) && ($searchsize > (20 * $offersize))))
										$merchant_err = "Das ist Wucher, so etwas akzeptieren wir hier nicht!! ;)<br>(Max. Handelsverh&auml;ltnis: 1:5, Gold: 1:20)";
									else
									{
										if ((($searchkind != 4) && ($offersize > (5 * $searchsize))) || (($searchkind == 4) && ($offersize > (20 * $searchsize))))
											$merchant_err = "Na, na, verkauf deine Ware doch mal nicht so unter Wert ;)<br> (Max. Handelsverh&auml;ltnis: 1:5, Gold:1:20)";
										else
										{
											if ($searchkind == $offerkind)
											{
												$merchant_err = "Ung&uuml;tiges Angebot";
											}
											else
											{
												if ($offersize < 20 || $searchsize < 20)
												{
													$merchant_err = "Ung&uuml;tiges Angebot: Die Mindestmenge ist 20.";
												}
												else
												{
													$trading_partner = (int)$_POST['hab'] | (int)$_POST['bnd'] | (int)$_POST['own'] | (int)$_POST['meta'];
												//jetzt wissen wir, dass alles ok eingegeben wurden. also schreiben wirs in die datenbank!
													$query_offer = "insert into offers values ";
													$query_offer.=  "(NULL,".$me->activevillageid.",".$offersize.",".$offerkind.",".$searchsize.",".$searchkind.",".$number_merchants.", ".$me->uid.", ".$num_offers.", ".(int) $trading_partner.")";


													$me->activevillage->spend_type ($offerkind, $offersize * $num_offers);

													if (!mysql_query ($query_offer))
													{
														log_err ("Cannot insert offer. Query: ".$query_offer.", ".mysql_error ());
														$merchant_err = "<b>Leider k&ouml;nnen die H&auml;ndler wegen eines Datenbankfehlers gerade nicht eingestellt werden :(<br>Bitte sp&auml;ter nochmal probieren</b>";
													}
													$merchants_gone += $number_merchants * $num_offers;
												}
											}
										}
									}
								}
							}
						}
					}
					else
					{
						$merchant_err = "Bitte mindestens 1 Angebot erstellen";
					}
				}
			}
		}
	}
}



//delete existing offers
if (isset ($_REQUEST['c']))
{
	$offerid = (int)$_REQUEST['c'];

	$query = "select * from offers where offerid=".$offerid;

	if (!($res = mysql_query ($query)))
	{
		log_err ("Cannot read offer while aborting it. Query: ".$query.", ".mysql_error());
	}
	else
	{
		if (!($row = mysql_fetch_array ($res)))
		{
			log_err ("Row empty while aborting offer. Query: ".$query.", ".mysql_error ());
		}
		else
		{
			$me->activevillage->spend_type ($row['offerkind'], -$row['offersize']*$row['number']);

			$query = "delete from offers where offerid=".$offerid." and villageid=".$me->activevillageid;

			if (!mysql_query ($query))
			{
				$me->activevillage->spend_type ($row['offerkind'], +$row['offersize']*$row['number']);
				log_err ("Cannot abort offer. Query: ".$query.", ".mysql_error ());
			}
		}
	}
}




//edit offers
if (isset($_POST['hidden_offerid']) && isset($_POST['change_number']))
{
	$query = "select * from offers where offerid=".(int)$_POST['hidden_offerid'];

	if ($res = mysql_query($query))
	{
		if ($row = mysql_fetch_array($res))
		{
			if ($row['uid'] == $me->uid)
			{
				$former_number = $row['number'];
				$new_number = max(1, min(99, (int)$_POST['new_number']));

				$spend = array (0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0);
				$spend[$row['offerkind']] = ($row['offersize']*$new_number)-($row['offersize']*$former_number);
				$former_merchants = ceil (($row['offersize']*$former_number) / $me->merchant_cap);
				if ($former_number != $new_number)
				{
					//if ($former_number < $new_number)
					{
						if ($me->activevillage->can_spend_array ($spend))
						{
							calcMerchants();
							//FIXME check for enough merchants
							$number_merchants = ceil ($row['offersize'] * $new_number / $me->merchant_cap) ;
							//echo '<h1>number: '.$number_merchants.', here: '.$merchants_here.', former: '.$former_merchants.'</h1>';
							if ($number_merchants > ($merchants_here+$former_merchants))
							{
								$merchant_err = 'So viele H&auml;ndler hast du nicht. ';
							}
							else
							{
								$query = "update offers set number=".$new_number." where offerid=".(int)$_POST['hidden_offerid'];
								if (mysql_query($query))
								{
									$me->activevillage->spend_type ($row['offerkind'], -($row['offersize'] * ($former_number - $new_number)));
								}
							}
						}
						else
						{
							$merchant_err = 'So viele Rohstoffe hast du nicht.';
						}
					}
				}
			}
		}
	}
}

calcMerchants();


?>