CREATE PROCEDURE dbo.PostDays @ReferenceNumber int, @GuestNumber SmallInt, @Dayproduct Bit, @PostFromDateStr Char(8), @PostToDateStr Char(8), @UserIDNumber Int, @FK_TurnoverDepartment INT, @ChargeAllDayProducts Bit = 0, @ChargeCancellationFee BIT = 0, @ChargeTables BIT = 0 AS
SET NOCOUNT ON

/*
  Changes:
 KJ 20170323: Bug: Fix for "Hall linies with no price is sometimes sold". Case #CR122724
 KJ 20160127: Bug: Fix for "Error converting the varchar value Manuell to data type int" 
 KJ 20150924: Bug: Fix for "Package not charged when hall is set to charge per type". Case #CR092616
 KJ 20150827: Bug: Fix for "Handle bill and account provision". Case #CR091633
 KJ 20150727: Bug: Fix for "Account provision not posted". Case #CR090345
 KJ 20150727: Bug: Fix for "Provision posted two times". Case #CR090484
 KJ 20150612: Bug: Fix for "Package posted multiple times when charge packet department enabled and multiple hall lines on same day and use tolerance time is disabled". Case #CR088649
 KJ 20150611: Bug: Fix for "Sometimes provion is not posted". Case #CR088922
 KJ 20150520: Bug: Fix for "New reservations (reservations not related to a main course reservation) isn't charged"
 KJ 20150511: Bug: Fix for "Provision posted twice". Case #CR084838
 KJ 20150414: Bug: Fix for "wrong name on transactions". Case #CR086240
 KJ 20150407: Ext: Include Course main reservation according to new hotelsetup.
 KJ 20150430: Bug: Fix for "Provision not posted on correct folio".
 KJ 20150326: Ext: Added arranagementlinenumber. Handle for multiple precharge.
 KJ 20150318: Bug: Fix for "Charge Discount as Product not posted on correct account"
 KJ 20140804: Bug: Fix for "Package not chargen when no product on hall line". Case #CR075002
 KJ 20140619: Bug: Fix for "Discount not calculated when +product period 4 is used.". Case #CR073483
 KJ 20140305: Bug: Fix for "@Arr24HoursStarts sometimes NULL".
 KJ 20131205: Bug: Fix for "Pieces = 0 when charge hall line only with children 2". Case #CR066929
 KJ 20130531: Bug: Fix for "Res not charged. SchemePattern not NULL anymore" . Case #CR059768
 KJ 20130418: New: Added "More provision wares is possible. Setup per Roomtype". Req #1575
 KJ 20130218: Bug: Fix for "Wrong department on discount when using charge department enabled". Case #CR052983
 KJ 20121022: Bug: Fix for "Don't delete folios that hasn't been created in this run of PostDays". Case #CR047712 + #CR047713
 KJ 20121008: Bug: Fix for "Don't delete folios that hasn't been created in this run of PostDays". Case #CR047712 + #CR047713
 KJ 20120831: Bug: Fix for "To may Folios created when charge" Case #CR046275  
 KJ 20120418: Bug: Fix for "hole period precharged for hall even if only partly selected". Case #CR040630
 KJ 20120411: Bug: Fix for "hole period precharged for hall even if only partly selected". Case #CR040630  
 KJ 20120203: Bug: Fix for "Extras posted on all table folios if multiple tables on reservation". Case # CR039616
 KJ 20120123: Bug: Fix for "halls on different days not posted". Case #CR039065
 KJ 20111207: Bug: Fix for "Res with only table does not post estras" . Case #CR037463
 KJ 20110829: Bug: Optimization not okay. Package is sometime posted multiple times. Case #CR032974
 KJ 20110729: Ext: Optimization: Check for package is posted not needed. If night is posted then post the package as well. Case# CR026217 
 KJ 20110518: Ext: "Post provision on guest". Req# 890+908
 KJ 20110406: Bug: Fix for "Extra charged multiple times" Case# CR023071.
 KJ 20101229: Bug: Fix for "Rooms posted on days before actually room arrival if priceoverwritten and halls arrival before room arrival" case# CR018662
 KJ 20101011: Bug: Fix for "Afbestillingforsikring charged multiple times" CR017336
 KJ 20100602: Bug: Fix for "To many rooms/package posted due to customer/hotel with hotelnumber is deleted"
 KJ 20100406: Bug: Fix for "Extras not charged when same extra on multiple guests"
 KJ 20090930: Bug/Ext: Always use Priceoverwrite from Reservation - do not look at product.
 KJ 20090907: Bug: Fix for "Extras on guest>0 charged multiple times" Case #9826.
 KJ 20090826: Bug: Fix for "Don't charge roomlines on guest = 0, when arriving in the future and not precharge"
 KJ 20090825: Ext: Enable Budget per department Req #348
 KJ 20090812: Bug: Fix for "Extras sometimes not charged i table booking and enable table department"
 KJ 20090806: Bug/Ext: Charge all tables on one table folio if only bowling
 KJ 20090803: Bug: Fix for "Precharge charges tables multiple times if only table reservations"
 KJ 20090709: Bug: Fix for "Charge is done on disabled department when not running Domino"
 KJ 20090520: Bug: Fix for "Change from 20090107 result that not post hall on departureday by Charge d.prod from reservation"
 KJ 20090204: Bug: Added ISNULL to GuestNo
 KJ 20090107: Bug: Fix for "Precharge dayproducts always charges whole period regardless of PostToDate"
 KJ 20081222: Ext: Added OriginalGlobalTransactionNumber
 KJ 20081201: Bug: Fix for "Wrong charge depatment - always select the first department"
 KJ 20081102: Optimized some sql's
 KJ 20081102: Bug: Fix for "Also join on GuestNo for ReservationConferenceLines"
 KJ 20081023: Bug: Fix for "Departure package shoyuld not be charged if priceoverwritten + not AddonIfPriceOverwritten"
 KJ 20081017: Bug: A little improvement of charge halls with same day+product+hallnumber
 KJ 20080925: Bug: Fix for "Extras charged to many times when running Use table departments and extras is charged on table folio."
 KJ 20080829: BUG: Fix for "Halls not always charged". Added tjek for RoomRomber in Note
 KJ 20080827: Bug/OPTIMIZED: Getting number of expostprday takes to long time.
 KJ 20080704: Bug: Try no 1 billion and one for fix "Halls sometimes charged multiple times"
 KJ 20080623: Bug: Try no 1 billion for fix "Halls sometimes charged multiple times"
 KJ 20080618: Bug: Fix for "Arrangementlines (Extras) sometimes posted on both Hall/Room folio and Table folios"
 KJ 20080519: Bug Fix2 for "Halls sometimes charged multiple times"
 KJ 20080519: Bug Fix for "Halls sometimes charged multiple times"
 KJ 20080516: Bug: Fix for "Dayproduct without product but with priceoverwrite not charged"
 KJ 20080417: BUG: Fix for "Multible Halls with same arrival and departure only charged once."
 KJ 20080307: BUG: Fix for "Tables not charged in nightaudit"
 KJ 20080303: BUG/OPTIMIZED: "Checking for existing logi transactions takes to long time"
 KJ 20080215: Bug: Fix for "Unable to delete folio if any (bonus)card is related to the folio"
 KJ 20071222: Bug: Fix for "Turnoverdepartment not set for domino rooms transactions"
 KJ 20071220: Bug: Package charged on wrong folio if only table booking
 KJ 20071220: Bug: Fix for "wrong turnoverdepartment if reservation has been mixed resorce - rooms for more than one hotel on same res"
 KJ 20071220: BUG: Fix for "sometimes Wrong turnover department when autocharge department has been deleted."
 KJ 20071206: Bug Fix for "Halls charged to many times"
 KJ 20071128: Ext: @ChargeTables added as input param. Used to charge tables or not. Default is: Do not charge.
 KJ 20071122: Bug: Fix for "Precharge does not post all products"
 KJ 20071119: Bug: Fix for "Precharge on table does not work."
 KJ 20071010: Fix for "Can not insert the value null into priceoverwrite" - Provision
 KJ 20070830: Extras not charged for more than one guest.
 KJ 20070801: Added @NumOfDecimals for Provision/Discount transactions
 KJ 20070601: Added charge CancellationFee
 KJ 20070423: Department rewrite: Some DepartmentOverwrite missing.
 KJ 20070410: Department Rewrite
 KJ 20070410: Bug: Fix for "Wrong amount if precharge and priceoverwritten and no namelist has been created"
 KJ 20070410: Fix for "wrong TurnoverDepartment when running Domino"
 KJ 20070329: Bug: Fix for Request timeout when early payout.
 KJ 20070328: Bug: Fix for wrong TurnoverDepartment when running Domino.
 KJ 20070308: Changed the delete folio stuff.
 KJ 20070228: BUG Fix for 'IF NULL product and +product then overnight is posted on wrong accountnumber for day2+day3+day4'
 KJ 20070219: Bug Fix for "If +product then the last night was not charged"
 KJ 20070202: Fix for Halls charged on multiple days.
 KJ 20070112: Correct Fix for GuestNumber sometimes NULL
 KJ 20070108: Fix for GuestNumber sometimes NULL
 KJ 20070104: Fix for Halls posted on wrong guest if GuestNumber > 0
 KJ 20070104: Added Support for Halls on subres
 KJ 20070102: Bug: Fix for Error when priceoverwrite for the 4.th product
 KJ 20061208: Added AutodayUserIdNumber to fix problem with precharge future res.
 KJ 20061109: Added RoomTypeNumber to call to ProductPriceDay call when DayProduct
 KJ 20061109: Precharge for hall in the future not working. 
 KJ 20061024: Using CountryNumber instead of CountryCode in provision calculation
 nb20061019 Preventing Lock time outs
 KJ 20061003 DeparturePackage not posted if % and no addon
 nb20060915 Secure  WareText for lodging transactions a litle bit more
 KJ 20060725 Missing a space in logi transactions.
 KJ 20060713 Always use @WareText when GetTextNameLodgingTransactions
 KJ 20060707 Added use of GetTextNameLodgingTransactions function to get WareText for lodging transactions
 KJ 20060707 Fix for PreCharge on tables - post on wrong folio.
 KJ 20060615 Changed the delete of unused folios
 KJ 20060614 Join'ing with ReservationAddressXtab to ensure no guestaddress is deleted
 KJ 20060609 Initialize of some var missing
 KJ 20060609 Changed the delete of unused folios
 KJ 20060510 Postismade moved to the end of this sp. Error on Hotel Svanen.
 KJ 20060505 Changed autocharge department
 KJ 20060424 TRAN T1 replaced with manuel delete of unused folios
 KJ 20060420 Added ', 5, 2' to discount text transactions to prevent 9.5 to be rounded to 10
 KJ 20060419 TRAN T1 removed - does not work properly
 KJ 20060412 Added BEGIN TRAN T1 to Provision post to prevent some folios to be created
 KJ 20060412: Fix for NumberOfDecimalsInDeposit sometimes NULL
 KJ 20060328: Changes made the 20060308 is bad.
 KJ 20060327: Provision not charged. Bug on Copenhagen Business Hotel
 KJ 20060308: Not able to precharge halls if arrival is in the future
 KJ 20060220: SideHousenumber removed from select. fix for PreCharge not working for roomlines without roomnumber
 nb20060207 safety CountryNumber value on transactions is needed
 KJ 20051227: BUG: addon and package if %-split.
 KJ 20051124: BUG/EXT: Fix for "Provision always rounded to nearest hole number"
 KJ 20051117: BUG: Tables re-charged in nightaudit - even if the table product already has been  charged
 KJ 20051101: Added Round to EnvironmentFee
 KJ 20051014: Fix for EnvironmentFee not correct if PriceOwerwrite
 KJ 20050913: Fix for Discount not correctly calculated. error on grandPark ref. 21277
 KJ 20050901: Removed AccountDaily
 nb20050822 fixed the length of @GuestLastName
 KJ 20050623: Changed @NumberOfPostExArrPrDay
 20050526 JP: changed code to use GetNextNumber
 14/04-2005 af KS: imp charge of tablebooking
 13/04-2005 af KS: Bug : if namelistsetting=0 and guestnumber>0
 09/03-2005 af KS: Bug : Added if isnull(@DiscountAsNettoPrice,0) =  0 set @DiscountAsNettoPrice = 0
 04/03-2005 af KS: imp. isnull(mainreservation.hotelnumber,0)
 21/02-2005 af KS: imp. DiscountAsNettoPrice
 08/02-2005 af KS: imp. Children2 and dayproduct.
 07/01-2005 af KS: imp. use EnviromentFee when priceoverwrite
 13/12-2004 af KS: imp. ProvisionOnEnviromentFee
 15/11-2004 af KS: wrong
 02/11-2004 af KS: take namelistsetting from line if @GuestNumber>0
 28/10-2004 af KS: if +-produkt and splitbill1-4 = 0 set splitbill 
 13/10-2004 af KS: When charge package and dayproduct set priceoverwrite=1
 08/10-2004 af KS: Undone 7/9-2004
 05/10-2004 af KS: some optimization
 17/09-2004 af KS: Imp. splitbill when star-product
 15/09-2004 af KS: some optimization
 07/09-2004 af KS: Bug : if plusproduct and change on dep. date now charge both dep. package
 06/09-2004 af KS: new select for MPMS (if not sometime dublicate reservations)
 02/09-2004 af KS: Bug when check  for charged dayproducts
 24/08-2004 af KS: added  isnull(1) on confroom. Bug in reservation
 16/08-2004 af KS: imp. @ChargeAllDayProducts for erlypay of dayproducts
 13/07-2004 af KS: Bug if namelist=0 on product take from hotelsetup
 07/07-2004 af KS: Imp. @ChargeAddonAsProduct
 24/06-2004 af KS: Added hotelnumber>=0 and only saleschannel in join for hotelnumber
 14/05-2004 : Imp. Hotelnumber for multihotels
 16/04-2004 : bug in chargeconfline (if @PacketNumber>0 use @PacketNumber and not packet from line)
 22/03-2004 : Imp "New" NameListReservationPerPerson (read from product or hotelsetup if no product)
 03/03-2004 : Imp @ChargeDiscountAsProduct
 09/02-2004 : bug fix 2/2
 03/02-2004 : Changed department to char(1)
 02/02-2004 : imp. chage if price=0
 16/01-2004 : fixed bug with pricoverwrite when charge dep.package ->> pricoverwrite=1 (price=0 or depaddon)
 15/01-2004 : fixed bug with date when charge package before departure (8/1-2004) wrong day ->> postdate and pricoverwrite=1
 08/01-2004 : fixed bug with date when charge package before departure
 08/01-2004 : fixed bug with environmentfee (invironmentfee)
 07/01-2004 : Imp. PackagesplitAfterDiscount
 04/11-2003 : Added (MarkAsDeleted is null) to wareselect (provision) + WareGroup
 06/10-2003 : Fixed bug with +product and a period at 0 day
 25/09-2003 : now also charge extra when guestnumber>0
 04/09-2003 : remove excl/vat from transtext
 03/09-2003 : Don't charge packet if dayres and no product
 26/08-2003 : Bugfix 4/7-2003 : if both stay/deparatur/arrival package
 11/07-2003 : if exec postering set postonguestnumber=@Guestnumber
 04/07-2003 : Always check fore before-charged-packaged before charge-package
 27/06-2003 : if productnumber = null/0 set priceoverwrite = 1
 11/06-2003 : if isnull(addon+dep.addon) = 0 SET = 0
 02/06-2003 : added if priceoverwrite check product for allow -priceoverwrite
 27/05-2003 : Imp Negative addon/dep-addon
 09/05-2003 : fixed bug if arrivaltime<(arr24starts in hotelsetup)
 07/05-2003 : Round provision to 0 decimals
 07/04-2003 : always postvat=1 (take from account)
 06/03-2003 : if hall and no product price = price*pieces*pax
 17/02-2003 : Bugfix call only PostPackage if packagenumber>0 +product and day4=0 (in day3)
 04/02-2003 : Bugfix call only PostPackage if packagenumber>0 
 30/01-2003 : New "getnextproductwarelinknumber"+"getnextglobaltransactionnumber"
 29/01-2003 : sidehouse number 
 29/01-2003 : call only PostPackage if packagenumber>0
 29/01-2003 : fixed some error if empty/nul-product and package 
 21/01-2003 : imp NoProvisionOnAddon and only discount by productprice
 20/01-2003 : Added (PERSONEL.UserTypeNumber = 4 AND AND(MovedDeleted=0))
 16/01-2003 : Added read_only to cursor declaration
 03/01-2003 : systemtransactions : Hvis autonight (ligeglad med movedstatus) men hvis autoday moveddeleted=0
 27/12-2002 : Bugfix something with @AddonIfPriceOverwritten and @StayEndDate=@StayStartDate
 13/12-2002 : Imp "@AddonIfPriceOverwritten"
 18/11-2002 : imp NoDiscountOnAddon and only discount by productprice
 05/11-2002 : removed "And (MovedDeleted=0)" when count systemtransactions
 30/10-2002 : Provision : Upper(@CountryCode)= 'DK'  -->>  Upper(@CountryCode) = Upper(@HotelContryCode)
 17/10-2002 : Only take accounts from productware if VATProduct
 08/10-2002 : Added "And (Convert(Char(8),OriginalDate,112)=@PostDateStr)" when count systemtransactions
 02/10-2002 : Changed NameOnLodgiTransaction to NameOnLodgingTransaction
 29/09-2002 : Set price if @PriceOverWritten=1 and dayproduct and no product (Schemabooking)
 02/09-2002 : Use convert(float) when VatOfPrice
 30/08-2002 : Alt skal benytte 2 decimaler (det der skal vises ps regningen ellers ss mange som der er mulighed for)
 28/08-2002 : set billtext='' default
 28/08-2002 : Removed @ProductWareLinkNumber from trans if not package or logitran
 27/08-2002 : added @showprint
 26/08-2002 : select only if (RESERVATIONS.PaysAdults+RESERVATIONS.PaysChildren1+RESERVATIONS.PaysChildren2>0) OR (RESERVATIONS.Adults+RESERVATIONS.Children1+RESERVATIONS.Children2>0)
 22/08-2002 : read bookedtypenumber from roomline and not reservations
 22/08-2002 : chargelogi if @Logi<>0 OR @VatOfLogi<>0 OR @CalcPricday>0
 15/08-2002 : Take account from logiware when discount
 14/08-2002 : Fixed problem with a set =
 09/08-2002 : Fixed problem with erlypay if postenddate+1=stayenddate (safe)
 31/07-2002 : Fixed problem med +-product (posteret en pakke formeget)
 10/07-2002 : Fixed problem med afrejsepakke og null/empty-product
 02/07-2002 : Alt skal benytte 2 decimaler
*/

DECLARE @LockTimeOut INT
SET @LockTimeOut = @@LOCK_TIMEOUT
SET LOCK_TIMEOUT 5000

Declare @ShowPrint bit
SET @ShowPrint = 0

if @ShowPrint = 1
  Print 'PostDays'

DECLARE @MaxFolioNumber INT
SELECT @MaxFolioNumber = MAX(FolioNumber) FROM Folios WITH (NOLOCK)

Declare @Pieces int

Declare @VisualRoomNumber int

Declare @DiscountwareText varchar(50)
Declare @DiscountPrice Money
Declare @DiscountWareNumber int

Declare @DummyTransNrShowOnBillOnAdd int

Declare @FirstPost Bit

Declare @DiscountRate float

Declare @BookedTypeNumber Int

Declare @RoomNumber Int
Declare @ArrivalDate Char (8)
Declare @DepartureDate Char (8)

Declare @ArrDate datetime

Declare @FirstPrice1 Money
Declare @FirstPrice2 Money
Declare @FirstPrice3 Money
Declare @FirstPrice4 Money

Declare @Day2 SmallInt
Declare @Day3 SmallInt
Declare @Day4 SmallInt

Declare @ProductNumber  Int
Declare @ProductNumber2 Int
Declare @ProductNumber3 Int
Declare @ProductNumber4 Int

Declare @IsFixedPriceProduct  Bit

Declare @NumberOfRooms SmallInt

Declare @PriceOverwritten  Bit
Declare @PriceOverwritten2 Bit
Declare @PriceOverwritten3 Bit
Declare @PriceOverwritten4 Bit

Declare @Adults Int
Declare @Children1 Int
Declare @Children2 Int
Declare @PaysAdults Int
Declare @PaysChildren1 Int
Declare @PaysChildren2 Int

Declare @NameListReservationPerPerson bit
Declare @Price Money

Declare @StayStartDate DateTime
Declare @StayEndDate DateTime

Declare @CalcPriceDay Money

Declare @PacketNumberReservation Int
Declare @PacketNumber Integer
Declare @PacketNumber2 Integer
Declare @PacketNumber3 Integer
Declare @PacketNumber4 Integer

Declare @PackageTurnOver Money
Declare @VatOfPackageTurnOver Money

Declare @VatValueProduct Float
Declare @VatValueProduct1 Float
Declare @VatValueProduct2 Float
Declare @VatValueProduct3 Float
Declare @VatValueProduct4 Float

Declare @FolioNumber int
Declare @StoreFolioNumber int
DECLARE @ProvisionFolioNumber INT
DECLARE @ProvPostOnGuest INT

Declare @SegmentNumber Int
Declare @PointOfSaleNumber Int
Declare @GetVATFrom SmallInt

Declare @ReservationAddressNumber Integer

Declare @StayResultAccountNumber Integer
Declare @StayResultAccountNumber1 Integer
Declare @StayResultAccountNumber2 Integer
Declare @StayResultAccountNumber3 Integer
Declare @StayResultAccountNumber4 Integer

Declare @StayBalanceAccountNumber Integer
Declare @StayBalanceAccountNumber1 Integer
Declare @StayBalanceAccountNumber2 Integer
Declare @StayBalanceAccountNumber3 Integer
Declare @StayBalanceAccountNumber4 Integer

Declare @StayVATAccountNumber Integer
Declare @StayVATAccountNumber1 Integer
Declare @StayVATAccountNumber2 Integer
Declare @StayVATAccountNumber3 Integer
Declare @StayVATAccountNumber4 Integer

Declare @EnviromentFeeResultAccountNumber Integer
Declare @EnviromentFeeBalanceAccountNumber Integer
Declare @EnviromentFeeVATAccountNumber Integer
Declare @EnviromentFeeWareText Char(50)
Declare @EnviromentFeeWareNumber Integer
Declare @VATValueEnviromentFee Float
Declare @EnviromentFee Money
Declare @EnviromentFeeProduct1 Money
Declare @EnviromentFeeProduct2 Money
Declare @EnviromentFeeProduct3 Money
Declare @EnviromentFeeProduct4 Money
Declare @VatOfEnviromentFee Money
Declare @EnviromentFeeVatValueNumber Integer

Declare @EnviromentFeeType float
Declare @EnviromentFeeType1 float
Declare @EnviromentFeeType2 float
Declare @EnviromentFeeType3 float
Declare @EnviromentFeeType4 float

Declare @PaymentType SmallInt

Declare @ServerDateTime DateTime
Declare @TransactionDatetime DateTime

Declare @WareNumber Integer
Declare @WareNumber1 Integer
Declare @WareNumber2 Integer
Declare @WareNumber3 Integer
Declare @WareNumber4 Integer

Declare @WareText  VARChar(50)
Declare @WareText1 VARChar(50)
Declare @WareText2 VARChar(50)
Declare @WareText3 VARChar(50)
Declare @WareText4 VARChar(50)

Declare @AddressType SmallInt

Declare @StarProduct Bit

Declare @PostDayproducts Bit

Declare @PostStay Bit

Declare @NumberOfPostRoomPrDay Int

Declare @CurrentDate DATETIME
Declare @CurrentDateStr Char(8)

Declare @PostToDate DATETIME
Declare @PostFromDate DATETIME
DECLARE @tmpPostToDate DATETIME

Declare @GetVatValueFromProduct2 Bit
Declare @GetVatValueFromProduct3 Bit
Declare @GetVatValueFromProduct4 Bit

Declare @Logi Money
Declare @VatOfLogi Money

Declare @VatValueRoomProduct1 Float

Declare @VatValueRoomProduct2 Float
Declare @VatValueRoomProduct3 Float
Declare @VatValueRoomProduct4 Float

Declare @PriceProduct1 Money
Declare @PriceProduct2 Money
Declare @PriceProduct3 Money
Declare @PriceProduct4 Money

Declare @PackagePriceProduct1 Money
Declare @PackagePriceProduct2 Money
Declare @PackagePriceProduct3 Money
Declare @PackagePriceProduct4 Money

Declare @VatByPacketValueProduct Money
Declare @VatByPacketValueProduct1 Money
Declare @VatByPacketValueProduct2 Money
Declare @VatByPacketValueProduct3 Money
Declare @VatByPacketValueProduct4 Money

Declare @POSTProduct1 Bit
Declare @POSTProduct2 Bit
Declare @POSTProduct3 Bit
Declare @POSTProduct4 Bit

Declare @TempVatByPacketValueProduct money
Declare @TempPackagePriceProduct Money

Declare @UseEnvironmentFee Bit

Declare @GlobalTransactionNumber Integer
Declare @RealDateTimeForTransaction DateTime

Declare @PostDateStr char(8)
Declare @PostDate DATETIME
DECLARE @LastPostDate DATETIME
SET @LastPostDate = 0

Declare @AddonResultAccountNumber Integer
Declare @AddonBalanceAccountNumber Integer
Declare @AddonVATAccountNumber Integer
Declare @AddonWareText Char(50)
Declare @VATValueAddon Float
Declare @AddonWareNumber int
Declare @AddonVatValueNumber tinyint
Declare @Addon Money
Declare @Addon1 Money
Declare @Addon2 Money
Declare @Addon3 Money
Declare @Addon4 Money
Declare @VATOfAddon Money

Declare @DepartureAddon Money
Declare @DepartureAddon1 Money
Declare @DepartureAddon2 Money
Declare @DepartureAddon3 Money
Declare @DepartureAddon4 Money

Declare @VATOfDepartureAddon Money

Declare @SpecifiedDepartureAddOn bit
Declare @SpecifiedDepartureAddOn1 bit
Declare @SpecifiedDepartureAddOn2 bit
Declare @SpecifiedDepartureAddOn3 bit
Declare @SpecifiedDepartureAddOn4 bit

Declare @BillTextProductDepartureAddon VARCHAR(50)
Declare @BillTextProduct1DepartureAddon VARCHAR(50)
Declare @BillTextProduct2DepartureAddon VARCHAR(50)
Declare @BillTextProduct3DepartureAddon VARCHAR(50)
Declare @BillTextProduct4DepartureAddon VARCHAR(50)
Declare @DepartureAddonWareText Char(50)

Declare @BillTextProduct VARCHAR(50)
Declare @BillTextProduct1 VARCHAR(50)
Declare @BillTextProduct2 VARCHAR(50)
Declare @BillTextProduct3 VARCHAR(50)
Declare @BillTextProduct4 VARCHAR(50)

Declare @BillTextProductAddon VARCHAR(50)
Declare @BillTextProduct1Addon VARCHAR(50)
Declare @BillTextProduct2Addon VARCHAR(50)
Declare @BillTextProduct3Addon VARCHAR(50)
Declare @BillTextProduct4Addon VARCHAR(50)

Declare @SplitBillNumber int
Declare @SplitBillNumber1 int
Declare @SplitBillNumber2 int
Declare @SplitBillNumber3 int
Declare @SplitBillNumber4 int

Declare @VATProduct Bit
Declare @LogiWareIndex tinyint

Declare @DummyAddon money
Declare @DummyDepartureAddon Money
Declare @DummyBillTextProduct varchar(50)
Declare @DummyBillTextProductAddon varchar(50)
Declare @DummyPriceProduct money
Declare @DummyPacketNumber int
Declare @DummyEnviromentFeeProduct money
Declare @DummyIsFixedPriceProduct bit
Declare @DummyVATProduct bit
Declare @DummySpecifiedDepartureAddOn bit
Declare @DummyEnviromentFeeType smallint

Declare @TempStr varchar(50)

Declare @AllDiscountRate Float

--Declare @MemberOfEU Bit

Declare @ProvisionWareNumber int
Declare @CountryNumber Int
Declare @ProvisionRate float
Declare @ProvisionType tinyint
Declare @ProvisionValue float
Declare @ProvisionWareText varchar(50)

Declare @AccountProvisionAddressType tinyint
Declare @AccountProvisionRate float
Declare @AccountProvisionFolioNumber int
Declare @AccountProvisionWareNumber int
Declare @AccountProvisionWareText varchar(50)
Declare @AccountProvisionGuestNumber smallint
Declare @AccountProvisionPostVAT BIT

Declare @PostVAT bit

Declare @UseNameOnLogiTransaction bit

DECLARE @GuestLastName VARCHAR(50)
DECLARE @GuestFirstName VARCHAR(50)

Declare @ShowOnBill bit

Declare @RunOneDayLongerProduct1 Bit
Declare @RunOneDayLongerProduct2 Bit
Declare @RunOneDayLongerProduct3 Bit

Declare @ProductWareLinkNumber int
Declare @ProductWareLinkNumber1 int

Declare @ProductWareLinkNumber2 int

Declare @ProductWareLinkNumber3 int
Declare @ProductWareLinkNumber4 int

Declare @EmptyproductPackageNumber int

Declare @NULproductPackageNumber int

Declare @NoDiscountOnAddon bit
Declare @NoProvisionOnAddon bit

Declare @AddonIfPriceOverwritten bit

Declare @NumberOfPostExArrPrDay int
Declare @NumberOfPostExMainArrPrDay int

Declare @HotelCountryNumber INT

Declare @TotalPostExDepFromArrangement money

Declare @FeeFolioNumber INT
Declare @DummyAddressType smallint

Declare @DepartureTime Char(5)

Declare @SidehouseNumber int

Declare @Arr24HoursStarts char(5)

Declare @AddonPieces SmallInt

--Declare @TempPriceoverwrite Bit

Declare @NumberOfChargedPackaged int
Declare @NumberOfChargedDeparturePackaged int

Declare @PackageDebAccount int

Declare @PackagesplitAfterDiscount Bit
Declare @TotalDiscountValueForPackagesplit Float

Declare @CancellationFeeGuestNumber int

Declare @TotalAmount money

Declare @CancellationFeeAmount money

Declare @ForceLogiChargingOfZeroPrice bit
Declare @ShowForcedLogiChargingOfZeroPrice bit

Declare @NameListReservationPerPersonHotelSetup Bit
Declare @NameListReservationPerPersonProduct Int

Declare @NameListSetting smallint

Declare @ChargeDiscountAsProduct bit

Declare @HotelCustomerNumber int

Declare @ChargeAddonAsProduct Bit

Declare @ChargeAddonAsWare Bit

Declare @NumberOfRepeats Smallint
Declare @RepeatsIndex Smallint

Declare @CentralBookingType smallint

Declare @ProvisionOnEnviromentFee bit

Declare @MainSplitbillNumber int

Declare @DiscountAsNettoPrice bit

Declare @TableReservationLineNumber Int

Declare @EnvironmentfeePerRoom Bit
Declare @ChargeEnviromentFee Bit
Declare @EnviromentTransCount Integer

DECLARE @NumberOfDecimalsInDeposit INTEGER

DECLARE @PostIsMade BIT

DECLARE @NumOfDecimals INT

DECLARE @UseTableDepartmentsInTableBooking BIT

DECLARE @AnyPostHallsOnDay INT

DECLARE @AutoDayUserNumber INT
SELECT @AutoDayUserNumber = UserIdNumber FROM Personel WITH (NOLOCK) WHERE UserTypeNumber = 3

DECLARE @FK_LogiTurnOverDepartment INT
DECLARE @FK_ChargeDepartment SMALLINT
DECLARE @DayProductDepartment SMALLINT
DECLARE @GuestType INT
DECLARE @ReservationConfLineNumber INT

DECLARE @MainCourceResNotInclMIS_OrderBook BIT
SELECT @MainCourceResNotInclMIS_OrderBook = CONVERT(bit, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'MainCourceResNotInclMIS_OrderBook'
SET @MainCourceResNotInclMIS_OrderBook = ISNULL(@MainCourceResNotInclMIS_OrderBook, 0) 

SELECT TOP 1 @FK_LogiTurnoverDepartment = PK_Department 
FROM Departments d WITH (NOLOCK)
WHERE AutoCharge = 1 
AND ISNULL(MarkAsDeleted, 0) = 0
AND PK_Department = @FK_TurnoverDepartment

IF ISNULL(@FK_LogiTurnoverDepartment, 0) = 0
BEGIN
  SELECT TOP 1 @FK_LogiTurnoverDepartment = PK_Department 
  FROM Departments d WITH (NOLOCK)
  WHERE AutoCharge = 1 
  AND ISNULL(MarkAsDeleted, 0) = 0
END

IF ISNULL(@FK_LogiTurnoverDepartment, 0) = 0
BEGIN
  SELECT TOP 1 @FK_LogiTurnoverDepartment = PK_Department 
  FROM Departments d WITH (NOLOCK)
  WHERE ISNULL(MarkAsDeleted, 0) = 0
END

SET @MainSplitbillNumber = -1

Select @CentralBookingType = Convert(Integer,isnull(KeyValue,0)) from HotelSetup WITH (Nolock) where searchkey like '%CentralBookingType%'

Select @ChargeDiscountAsProduct = CONVERT(Bit,KeyValue) From HotelSetUp WITH (NOLOCK)  Where  SearchKey like '%ChargeDiscountAsProduct%'
if isnull(@ChargeDiscountAsProduct,-1)=-1 SET @ChargeDiscountAsProduct = 1

Select @ChargeAddonAsProduct = CONVERT(Bit,KeyValue) From HotelSetUp WITH (NOLOCK)  Where  SearchKey like '%ChargeAddonAsProduct%'
if isnull(@ChargeAddonAsProduct,0)=0 SET @ChargeAddonAsProduct = 0

Select @ChargeAddonAsWare = CONVERT(Bit,KeyValue) From HotelSetUp WITH (NOLOCK)  Where  SearchKey like '%AddonAsWare%'
if isnull(@ChargeAddonAsWare,0)=0 SET @ChargeAddonAsWare = 0

Select @PackagesplitAfterDiscount = CONVERT(Bit,KeyValue) From HotelSetUp WITH (NOLOCK)  Where  SearchKey like '%PackageSplitAfterDiscount%'
if isnull(@PackagesplitAfterDiscount,0)=0 SET @PackagesplitAfterDiscount = 0

Select @NameListReservationPerPersonHotelSetup = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='NameListReservationPerPerson'

Select @PackageDebAccount= AccountNumber From Accounts WITH (nolock) where AccountType=6 AND (MarkAsDeleted='0' or MarkAsDeleted is null)

SELECT @HotelCountryNumber = CONVERT(INT, KeyValue) FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'CountryCode'
IF @@ROWCOUNT = 0
  SELECT TOP 1 @HotelCountryNumber = CountryNumber FROM Countries WITH (NOLOCK)

SELECT @CurrentDateStr = SYSTEMDATE FROM System WITH (NOLOCK)  WHERE NUMBER = 1

Select @GetVATFrom=CONVERT(INT,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='BookkeepingReport'

Select @UseEnvironmentFee = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='UseEnvironmentFee'

Select @NoDiscountOnAddon = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='NoDiscountOnAddon'
if isnull(@NoDiscountOnAddon,0)=0 SET @NoDiscountOnAddon=0

Select @NoProvisionOnAddon = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='NoProvisionOnAddon'
if isnull(@NoProvisionOnAddon,0)=0 SET @NoProvisionOnAddon=0

Select @AddonIfPriceOverwritten = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='AddonIfPriceOverwritten'
if isnull(@AddonIfPriceOverwritten,0)=0 SET @AddonIfPriceOverwritten=0

Select @ForceLogiChargingOfZeroPrice = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='ForceLodgingChargeOfZeroPrice'
if isnull(@ForceLogiChargingOfZeroPrice,0)=0 SET @ForceLogiChargingOfZeroPrice=0

Select @ShowForcedLogiChargingOfZeroPrice = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='ShowForcedLodgingChargeOfZeroPrice'
if isnull(@ShowForcedLogiChargingOfZeroPrice,0)=0 SET @ShowForcedLogiChargingOfZeroPrice=0

Select @ProvisionOnEnviromentFee = CONVERT(Bit,ISNULL(KeyValue,0)) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='ProvisionOnEnviromentFee'

Select @Arr24HoursStarts = KeyValue from HotelSetUp WITH (NOLOCK)  Where  SearchKey='Arr24HoursStarts'
SET @Arr24HoursStarts = ISNULL(@Arr24HoursStarts, '07:00')

Select @DiscountAsNettoPrice =  ISNULL(KeyValue,0) From Hotelsetup WITH (Nolock) where Searchkey ='DiscountAsNettoPrice'
if isnull(@DiscountAsNettoPrice,0) =  0 set @DiscountAsNettoPrice = 0

Select @EnvironmentfeePerRoom =  ISNULL(KeyValue,0) From Hotelsetup WITH (Nolock) where Searchkey ='EnvironmentfeePerRoom'
if isnull(@EnvironmentfeePerRoom,0) =  0 set @EnvironmentfeePerRoom = 0

SELECT @NumberOfDecimalsInDeposit = ISNULL(KeyValue,2) FROM Hotelsetup WITH (NOLOCK) WHERE Searchkey ='NumberOfDecimalsInDeposit'
IF @NumberOfDecimalsInDeposit IS NULL
  SET @NumberOfDecimalsInDeposit = 2

SELECT @UseTableDepartmentsInTableBooking = ISNULL(KeyValue, 0) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'UseTableDepartmentsInTableBooking'

DECLARE @EnableBudgetPerDepartment BIT
SELECT @EnableBudgetPerDepartment = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'EnableBudgetPerDepartment'
SET @EnableBudgetPerDepartment = ISNULL(@EnableBudgetPerDepartment, 0)

if @Dayproduct = 0
  SET @NumberOfRepeats = @ChargeAllDayProducts + 1
else
  SET @NumberOfRepeats = 1

DECLARE @OnlyBowling BIT
EXEC SelectedResourceTypesOnly @ReferenceNumber, '3,9', @OnlyBowling OUTPUT

SET @RepeatsIndex = 1

While @RepeatsIndex<=@NumberOfRepeats
Begin
  if @RepeatsIndex = 2
    SET @Dayproduct=1

  if (@Dayproduct=1)
  begin
    SET @UseNameOnLogiTransaction = 0
    SET @Children2 = 0

    Declare ResCur Cursor Fast_Forward Read_Only For
    SELECT
      RESERVATIONConferenceLINE.DepartureTime,
      RESERVATIONConferenceLINE.BookedConferenceRoomTypeNumber,
      RESERVATIONConferenceLINE.ConferenceRoomNumber,
      RESERVATIONConferenceLINE.ArrivalDate,
      RESERVATIONConferenceLINE.DepartureDate,
      RESERVATIONConferenceLINE.ProductNumber,
      isnull(RESERVATIONConferenceLINE.NumberOfRooms,1),
      ISNULL(ReservationConferenceLine.GuestNo, 0),
      RESERVATIONS.MarketSegment,
      RESERVATIONS.PointOfSale,
      RESERVATIONS.SplitBill,
      RESERVATIONConferenceLINE.PriceOverWritten,
      RESERVATIONConferenceLINE.Adults,
      RESERVATIONConferenceLINE.Children1,
      RESERVATIONConferenceLINE.Children2,
      RESERVATIONConferenceLINE.Price,
      RESERVATIONConferenceLINE.ReferenceNumber,
      RESERVATIONConferenceLINE.PackageNumber,
      isnull(Customer.CustomerNumber,-1),
      Case RESERVATIONConferenceLINE.TableBooking when 1 then RESERVATIONConferenceLINE.ReservationConfLineNumber else 0 end AS TableReservationNumber,
      ReservationConferenceLine.FK_ChargeDepartment, 
      RESERVATIONConferenceLINE.ReservationConfLineNumber
    from RESERVATIONConferenceLINE WITH (NOLOCK) 
      INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber=RESERVATIONConferenceLINE.ReferenceNumber AND ISNULL(ReservationConferenceLine.GuestNo, 0) = Reservations.GuestNumber
      INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.Referencenumber =  RESERVATIONS.ReferenceNumber
      LEFT OUTER JOIN Customer WITH (NOLOCK) ON ISNULL(RESERVATIONMAIN.HotelNumber,0) = Customer.HotelNumber AND Customer.HotelNumber>=0 
        AND Customer.CustomerTypeNumber = 7 AND @CentralBookingType=7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
      LEFT OUTER JOIN ReservationReservationXtab resresx WITH (NOLOCK) ON resresx.FK_ReferenceNumberSub = ReservationMain.ReferenceNumber
    where (RESERVATIONConferenceLINE.ReferenceNumber = @ReferenceNumber) AND (Reservations.GuestNumber = @GuestNumber) AND (RESERVATIONConferenceLINE.DepartureDate >= @CurrentDateStr) AND 
    ((@Arr24HoursStarts<= RESERVATIONConferenceLINE.ArrivalTime AND RESERVATIONConferenceLINE.ArrivalDate <= @CurrentDateStr) OR
    (@Arr24HoursStarts> RESERVATIONConferenceLINE.ArrivalTime AND Convert(Char(8),Convert(Integer,RESERVATIONConferenceLINE.ArrivalDate)-1,112) <= @CurrentDateStr)
    OR ((RESERVATIONConferenceLINE.ArrivalDate > @CurrentDateStr) AND (@UserIDNumber = @AutoDayUserNumber)))
    and ((TableBooking = 1 AND (@ChargeTables = 1 OR TableStatus = 5)) OR (TableBooking = 0 or TableBooking is null))
    AND ISNULL(RESERVATIONConferenceLINE.SchemePattern, 0) = 0
    AND (@MainCourceResNotInclMIS_OrderBook = 0 OR ((resresx.FK_ReferenceNumber <> resresx.FK_ReferenceNumberSub) or resresx.FK_ReferenceNumber IS NULL))
  end
  else
  begin
    Select @UseNameOnLogiTransaction = CONVERT(Bit,KeyValue) from HotelSetUp WITH (NOLOCK)  Where  SearchKey='NameOnLodgingTransaction'
    if @GuestNumber=0
    begin
      Declare ResCur Cursor Fast_Forward Read_Only For
      SELECT
        RESERVATIONROOMLINE.BookedTypeNumber,
        RESERVATIONROOMLINE.RoomNumber,
        RESERVATIONS.MARKETSEGMENT,
        RESERVATIONS.POINTOFSALE,
        RESERVATIONS.SplitBill,
        RESERVATIONROOMLINE.ArrivalDate,
        RESERVATIONROOMLINE.DepartureDate,
        RESERVATIONROOMLINE.Adults,
        RESERVATIONROOMLINE.Children1,
        RESERVATIONROOMLINE.Children2,
        RESERVATIONROOMLINE.Adults,
        RESERVATIONROOMLINE.Children1,
        RESERVATIONROOMLINE.Children2,
        RESERVATIONROOMLINE.ProductNumber,
        RESERVATIONROOMLINE.NumberOfRooms,
        RESERVATIONROOMLINE.PriceOverwritten,
        RESERVATIONROOMLINE.Price,
        RESERVATIONROOMLINE.FirstPrice1,
        RESERVATIONROOMLINE.PriceOverwritten2,
        RESERVATIONROOMLINE.FirstPrice2,
        RESERVATIONROOMLINE.Day2,
        RESERVATIONROOMLINE.ProductNumber2,
        RESERVATIONROOMLINE.PriceOverwritten3,
        RESERVATIONROOMLINE.FirstPrice3,
        RESERVATIONROOMLINE.Day3,
        RESERVATIONROOMLINE.ProductNumber3,
        RESERVATIONROOMLINE.PriceOverwritten4,
        RESERVATIONROOMLINE.FirstPrice4,
        RESERVATIONROOMLINE.Day4,
        RESERVATIONROOMLINE.ProductNumber4,
        0 AS SideHouseNumber,
        RESERVATIONROOMLINE.NameListSetting,
        isnull(Customer.CustomerNumber,-1),
        isnull(RESERVATIONROOMLINE.SplitBillNumber1, 0),
        isnull(RESERVATIONROOMLINE.SplitBillNumber2, 0),
        isnull(RESERVATIONROOMLINE.SplitBillNumber3, 0),
        isnull(RESERVATIONROOMLINE.SplitBillNumber4, 0)
      FROM RESERVATIONROOMLINE WITH (NOLOCK) 
        INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LineNumber 
        INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber
        INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.Referencenumber =  RESERVATIONS.ReferenceNumber
        Left outer join Customer WITH (NOLOCK) ON isnull(RESERVATIONMAIN.HotelNumber,0) = Customer.HotelNumber AND Customer.HotelNumber>=0 
          AND Customer.CustomerTypeNumber = 7 and @CentralBookingType=7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
        LEFT OUTER JOIN ReservationReservationXtab resresx WITH (NOLOCK) ON resresx.FK_ReferenceNumberSub = ReservationMain.ReferenceNumber
      WHERE ((RESERVATIONROOMLINEXTAB.ReferenceNumber=@ReferenceNumber)  AND (RESERVATIONROOMLINEXTAB.GuestNumber=@GuestNumber))
      AND ((RESERVATIONROOMLINE.ArrivalDate <= @CurrentDateStr) OR ((RESERVATIONROOMLINE.ArrivalDate > @CurrentDateStr) AND (@UserIDNumber = @AutoDayUserNumber)))
      AND (@MainCourceResNotInclMIS_OrderBook = 0 OR ((resresx.FK_ReferenceNumber <> resresx.FK_ReferenceNumberSub) OR resresx.FK_ReferenceNumber IS NULL))
    end
    else
    begin
      begin
      Declare ResCur Cursor Fast_Forward Read_Only For
      SELECT
        RESERVATIONROOMLINE.BookedTypeNumber,
        RESERVATIONROOMLINE.RoomNumber,
        RESERVATIONS.MARKETSEGMENT,
        RESERVATIONS.POINTOFSALE,
        RESERVATIONS.SplitBill,
        RESERVATIONS.ArrivalDate,
        RESERVATIONS.DepartureDate,
        RESERVATIONS.PaysAdults,
        RESERVATIONS.PaysChildren1,
        RESERVATIONS.PaysChildren2,
        RESERVATIONS.Adults,
        RESERVATIONS.Children1,
        RESERVATIONS.Children2,
        RESERVATIONS.ProductNumber,
        RESERVATIONROOMLINE.NumberOfRooms,
        RESERVATIONS.PriceOverwritten,
        RESERVATIONS.Price,
        RESERVATIONS.FirstPrice1,
        RESERVATIONS.PriceOverwritten2,
        RESERVATIONS.FirstPrice2,
        RESERVATIONS.Day2,
        RESERVATIONS.ProductNumber2,
        RESERVATIONS.PriceOverwritten3,
        RESERVATIONS.FirstPrice3,
        RESERVATIONS.Day3,
        RESERVATIONS.ProductNumber3,
        RESERVATIONS.PriceOverwritten4,
        RESERVATIONS.FirstPrice4,
        RESERVATIONS.Day4,
        RESERVATIONS.ProductNumber4,
        case reservations.guestnumber when 0 then 0 else case sidehouse when 1 then 1 else 0 end end AS SideHouseNumber,
        RESERVATIONROOMLINE.NameListSetting,
        isnull(Customer.CustomerNumber,-1),
        isnull(RESERVATIONS.SplitBillNumber1, 0),
        isnull(RESERVATIONS.SplitBillNumber2, 0),
        isnull(RESERVATIONS.SplitBillNumber3, 0),
        isnull(RESERVATIONS.SplitBillNumber4, 0)
      FROM RESERVATIONROOMLINE WITH (NOLOCK) 
        INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LineNumber 
        INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber 
        INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.Referencenumber =  RESERVATIONS.ReferenceNumber
        Left outer join Customer WITH (NOLOCK) ON isnull(RESERVATIONMAIN.HotelNumber,0) = Customer.HotelNumber AND Customer.HotelNumber>=0 
          AND Customer.CustomerTypeNumber = 7 and @CentralBookingType=7 AND ISNULL(Customer.MarkAsDeleted, 0) = 0
      LEFT OUTER JOIN ReservationReservationXtab resresx WITH (NOLOCK) ON resresx.FK_ReferenceNumberSub = ReservationMain.ReferenceNumber
      WHERE ((RESERVATIONROOMLINEXTAB.ReferenceNumber=@ReferenceNumber) AND (RESERVATIONROOMLINEXTAB.GuestNumber=@GuestNumber)) AND (RESERVATIONS.Adults+RESERVATIONS.Children1+RESERVATIONS.Children2>0)
      AND (@MainCourceResNotInclMIS_OrderBook = 0 OR ((resresx.FK_ReferenceNumber <> resresx.FK_ReferenceNumberSub) OR resresx.FK_ReferenceNumber IS NULL))
    end
  end

  if IsNull(@UseNameOnLogiTransaction,1)=1 
    SET @UseNameOnLogiTransaction=1
end

Open ResCur

if (@Dayproduct=1)
begin
  Fetch Next From ResCur
  Into @DepartureTime, @BookedTypeNumber, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber,@NumberOfRooms, @GuestNumber, @SegmentNumber, @PointOfSaleNumber, @SplitBillNumber,
       @PriceOverWritten, @Adults, @Children1, @Children2, @Price,@ReferenceNumber, @PacketNumberReservation, @HotelCustomerNumber, @TableReservationLineNumber, @FK_ChargeDepartment, @ReservationConfLineNumber
end
else
begin
  Fetch Next From ResCur
  Into @BookedTypeNumber,@RoomNumber, @SegmentNumber,@PointOfSaleNumber, @SplitBillNumber,
       @ArrivalDate,@DepartureDate, @PaysAdults, @PaysChildren1, @PaysChildren2, @Adults,@Children1,@Children2,@ProductNumber,
       @NumberOfRooms,@PriceOverwritten,@Price,@FirstPrice1,
       @PriceOverwritten2,@FirstPrice2,@Day2,@ProductNumber2,
       @PriceOverwritten3,@FirstPrice3,@Day3,@ProductNumber3,
       @PriceOverwritten4,@FirstPrice4,@Day4,@ProductNumber4,
       @SidehouseNumber,
       @NameListSetting, @HotelCustomerNumber,
       @SplitBillNumber1, @SplitBillNumber2, @SplitBillNumber3, @SplitBillNumber4
end

SET @CurrentDate = Convert(DATETIME, @CurrentDateStr)
SET @PostToDate  = Convert(DATETIME, @PostToDateStr)
SET @PostFromDate = Convert(DATETIME, @PostFromDateStr)
SET @tmpPostToDate = @PostToDate

While (@@Fetch_Status=0)
begin
  IF @CentralBookingType=7
  BEGIN
    IF @Dayproduct=1 
    BEGIN
      SELECT TOP 1 @FK_LogiTurnoverDepartment = PK_Department FROM Departments d WITH (NOLOCK)
      INNER JOIN ReservationMain r WITH (NOLOCK) ON d.HotelNumber = r.HotelNumber AND AutoCharge = 1 AND ISNULL(MarkAsDeleted, 0) = 0 AND ReferenceNumber = @ReferenceNumber
    END
    ELSE
    BEGIN
      SELECT TOP 1 @FK_LogiTurnoverDepartment = PK_Department FROM Departments d WITH (NOLOCK)
      INNER JOIN Rooms r WITH (NOLOCK) ON d.HotelNumber = r.HotelNumber AND AutoCharge = 1 AND ISNULL(MarkAsDeleted, 0) = 0 AND R.RoomNumber = @RoomNumber
    END
   
    IF ISNULL(@FK_LogiTurnoverDepartment, 0) = 0
      SET @FK_LogiTurnoverDepartment = @FK_TurnoverDepartment    
  END

  IF ISNULL(@GuestNumber, 0) = 0 
    SET @GuestNumber = 0

  SET @PostDateStr = @PostFromDateStr
  SET @PostDate = @PostFromDate

  if (@Dayproduct = 1)
  begin
    if (isNull(@BookedTypeNumber,0)=0) OR (@Arr24HoursStarts>@DepartureTime)
      SET @DepartureDate = convert(char(8),Convert(datetime,@DepartureDate) - 1,112)
    if @ChargeAllDayProducts = 1 --AND @Dayproduct = 1 AND NOT (@PostToDate <= @DepartureDate)
    Begin  
      IF @tmpPostToDate < @DepartureDate
      BEGIN
        SET @PostToDateStr = CONVERT(CHAR(8), @tmpPostToDate, 112)
        SET @PostToDate = Convert(DATETIME, @PostToDateStr)
      END
      ELSE
      BEGIN
        SET @PostToDateStr = @DepartureDate
        SET @PostToDate = Convert(DATETIME, @PostToDateStr)
      END  
    end
  end
  ELSE 
  BEGIN
    IF @PostDate < @ArrivalDate
      SET @PostDate = @ArrivalDate
  END
  
  if (@PostDateStr<=@DepartureDate)
  begin
    if IsNull(@SplitBillNumber,0)=0 SET @SplitBillNumber = 0

    if (@ShowPrint=1)
    begin
      print '@SplitBillNumber (postdays)'
      print @SplitBillNumber
    end

    if IsNull(@Adults,0)=0     Set  @Adults = 0
    if IsNull(@Children1,0)=0  Set  @Children1 = 0
    if IsNull(@Children2,0)=0  Set  @Children2 = 0


    if IsNull(@PaysAdults,0)=0  Set @PaysAdults = 0
    if IsNull(@PaysChildren1,0)=0  Set @PaysChildren1 = 0
    if IsNull(@PaysChildren2,0)=0  Set @PaysChildren2 = 0

    if (@Dayproduct = 1)
    begin
      SET @PaymentType = 3 -- Halls

      if @RoomNumber > 0  -- TODO exchange with RoomNumberID when table has been nomalized
        SELECT @VisualRoomNumber = Number FROM ConferenceRooms WITH (NOLOCK) WHERE ConferenceRoomNumber = @RoomNumber  -- TODO use primary key instead! Then select is not needed anymore!
      else
        SET @VisualRoomNumber = NULL

      if ((@PriceOverWritten=0) AND ((@ProductNumber is null) OR (@ProductNumber = 0)))
        SET @PriceOverWritten = 1
/*
      else
      if @PriceOverWritten=1 And @ProductNumber>0
      begin 
        Select @TempPriceoverwrite = PriceOverWrite from Products (nolock) where productnumber=@ProductNumber
        if @TempPriceoverwrite = 0 
          SET @PriceOverWritten=0  
      end
*/
    end
    else
    begin
      SET @TableReservationLineNumber = 0

      if isnull(@NameListSetting, 0) = 0 SET @NameListSetting = 0

      SET @PaymentType = 2 -- Rooms
      if (@ShowPrint=1)
      begin
        PRINT '@PaymentType'
        PRINT @PaymentType
      end

      if @ROOMNUMBER > 0  -- TODO exchange with RoomNumberID when table has been nomalized
      begin
        if @SidehouseNumber = 1
          SELECT @VisualRoomNumber = SidehouseNumber FROM Rooms WITH (NOLOCK) WHERE RoomNumber = @ROOMNUMBER
        else
          SELECT @VisualRoomNumber = Number FROM Rooms WITH (NOLOCK) WHERE RoomNumber = @ROOMNUMBER
      end
      else
      	SET @VisualRoomNumber = NULL

      if IsNull(@Price,0)=0 SET @Price = 0
      if IsNull(@Day2,0)=0  Set @Day2 = 0
      if IsNull(@Day3,0)=0  Set @Day3 = 0
      if IsNull(@Day4,0)=0  Set @Day4 = 0

      if @SplitBillNumber1=0 SET @SplitBillNumber1 = @SplitBillNumber
      if @SplitBillNumber2=0 SET @SplitBillNumber2 = @SplitBillNumber
      if @SplitBillNumber3=0 SET @SplitBillNumber3 = @SplitBillNumber
      if @SplitBillNumber4=0 SET @SplitBillNumber4 = @SplitBillNumber

      if ((Convert(Integer,@ArrivalDate) + @Day2-1) > (Convert(Integer,@DepartureDate)))
        SET @Day2 = Convert(Integer,@DepartureDate) - Convert(Integer,@ArrivalDate) - 1

      if ((@Day2+@Day3+@Day4)>0)
      begin
        if @NameListSetting = 1  -- 1 = per person, 2 = per room
        begin
          SET @Adults = @PaysAdults
          SET @Children1 = @PaysChildren1
          SET @Children2 = @PaysChildren2
        end

        if (@PostFromDate>=Convert(DateTime,@ArrivalDate)) AND (@PostFromDate<=Convert(DateTime,@ArrivalDate)+@Day2-1)
        begin
          if ((@PriceOverWritten=0) AND ((@ProductNumber is null) OR (@ProductNumber = 0)))
            SET @PriceOverWritten = 1
        end
  
        if (((@PostFromDate>=Convert(DateTime,@ArrivalDate)+@Day2-1) AND (@PostFromDate<=Convert(DateTime,@ArrivalDate)+@Day3-1))
           OR ((@PostToDate>=Convert(DateTime,@ArrivalDate)+@Day2-1) AND (@PostToDate<=Convert(DateTime,@ArrivalDate)+@Day3-1)))
        begin
          if ((@PriceOverWritten2=0) AND ((@ProductNumber2 is null) OR (@ProductNumber2 = 0)))
            SET @PriceOverWritten2 = 1
        end
	
        if (((@PostFromDate>=Convert(DateTime,@ArrivalDate)+@Day3-1) AND (@PostFromDate<=Convert(DateTime,@ArrivalDate)+@Day4-1))
           OR ((@PostToDate>=Convert(DateTime,@ArrivalDate)+@Day3-1) AND (@PostToDate<=Convert(DateTime,@ArrivalDate)+@Day4-1)))
        begin
          if ((@PriceOverWritten3=0) AND ((@ProductNumber3 is null) OR (@ProductNumber3 = 0)))
            SET @PriceOverWritten3 = 1
        end
	
        if  (((@PostFromDate>=Convert(DateTime,@ArrivalDate)+@Day4-1) AND (@PostFromDate<=Convert(DateTime,@DepartureDate)))
           OR ((@PostToDate>=Convert(DateTime,@ArrivalDate)+@Day4-1) AND (@PostToDate<=Convert(DateTime,@DepartureDate))))
        begin
          if ((@PriceOverWritten4=0) AND ((@ProductNumber4 is null) OR (@ProductNumber4 = 0)))
            SET @PriceOverWritten4 = 1
        end
      end
      else
      begin
        if ((@PriceOverWritten=0) AND ((@ProductNumber is null) OR (@ProductNumber = 0)))
          SET @PriceOverWritten = 1
	      
        if @ProductNumber>0
        begin
          if @GuestNumber>0
          begin
            SET @NameListReservationPerPersonProduct = @NameListSetting
            if @NameListReservationPerPersonProduct = 0 
              SET @NameListReservationPerPersonProduct = @NameListReservationPerPersonHotelSetup         
          end
          else
          begin
            Select @NameListReservationPerPersonProduct = NameListSetting from Products WITH (nolock) where productnumber=@ProductNumber
            if isnull(@NameListReservationPerPersonProduct,0) = 0 SET @NameListReservationPerPersonProduct = @NameListReservationPerPersonHotelSetup         
          end
        end 
	
        if (@ProductNumber>0 AND @NameListReservationPerPersonProduct=1) OR ((@ProductNumber=0 OR @ProductNumber is null) AND @NameListReservationPerPersonHotelSetup=1)
        begin
          SET @Adults = @PaysAdults
          SET @Children1 = @PaysChildren1
          SET @Children2 = @PaysChildren2
        end               
      end

      if IsNull(@BookedTypeNumber,0)=0  Set @BookedTypeNumber = 0
      if IsNull(@NumberOfRooms,0)=0 SET @NumberOfRooms = 0
    end
  
    if (@ShowPrint=1)
    begin
      Print 'GETVATFROM'
      Print @GetVATFrom
      print '@VisualRoomNumber'
      print @VisualRoomNumber
    end
	
    if ((@GetVATFrom>=0) AND (@GetVATFrom<3) OR (@GetVATFrom=4))
    begin
      if (@GetVATFrom=0) -- Get Vat From Segment
        exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @SegmentNumber, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
      else
      if (@GetVATFrom=1) -- Get Vat From POS
        exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @PointOfSaleNumber, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
      else
      if (@GetVATFrom=2) -- Get Vat From Roomtype -- TODO ConferenceRoom if DayProduct
        exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @BookedTypeNumber, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
      else
      if (@GetVATFrom=4) -- VAT

      begin
        if  @ProductNumber>0
        begin
          Select @VATProduct = ExcludeVAT From Products WITH (nolock) WHERE ProductNumber=@ProductNumber
          if (@VATProduct is null) 
            SET @VATProduct=1
          else
          begin 
            if @VATProduct=0 

              SET @VATProduct=1
            else
              SET @VATProduct = 0
          end
        end
        else
          SET @VATProduct = 1
	
        SET @LogiWareIndex = @VATProduct+1
        exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @LogiWareIndex, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
      end
	
      SET @StayResultAccountNumber2 = @StayResultAccountNumber1
      SET @StayResultAccountNumber3 = @StayResultAccountNumber1
      SET @StayResultAccountNumber4 = @StayResultAccountNumber1
	
      SET @StayBalanceAccountNumber2 = @StayBalanceAccountNumber1
      SET @StayBalanceAccountNumber3 = @StayBalanceAccountNumber1
      SET @StayBalanceAccountNumber4 = @StayBalanceAccountNumber1
	
      SET @StayVATAccountNumber2 = @StayVATAccountNumber1
      SET @StayVATAccountNumber3 = @StayVATAccountNumber1
      SET @StayVATAccountNumber4 = @StayVATAccountNumber1
	
      SET @WareText2 = @WareText1
      SET @WareText3 = @WareText1
      SET @WareText4 = @WareText1
	
      SET @WareNumber2 = @WareNumber1
      SET @WareNumber3 = @WareNumber1
      SET @WareNumber4 = @WareNumber1
	
      SET @VatValueProduct2 = @VatValueProduct1
      SET @VatValueProduct3 = @VatValueProduct1
      SET @VatValueProduct4 = @VatValueProduct1
    end
    else
      exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @ProductNumber,  @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
	  
    if (@ShowPrint=1)
    begin
      print '@WareNumber1'
      Print  @WareNumber1
    end
	
    SET @AddressType = 0

    exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @WareNumber1, @SplitbillNumber, 0, @StoreFolioNumber OUTPUT, @AddressType OUTPUT, @TableReservationNumber = @TableReservationLineNumber
	
    if (@ShowPrint=1)
    begin
      print '@AddressType'
      print @AddressType
    end  

    if (@UseEnvironmentFee = 1)
    begin
      Select
        @EnviromentFeeBalanceAccountNumber = Ware.BalanceAccountNumber,
        @EnviromentFeeResultAccountNumber = Ware.ResultAccountNumber,
        @EnviromentFeeWareText = Ware.WareName,
        @EnviromentFeeWareNumber = Ware.WareNumber
      From WARE WITH (NOLOCK) 
        INNER JOIN WAREGROUPS WITH (NOLOCK) ON WARE.WareGroupNumber =  WAREGROUPS.WareGroupNumber
      WHERE (WAREGROUPS.Payment=4)  AND (Ware.MarkAsDeleted is null) AND Ware.SortNumber=4
	
      if @EnviromentFeeWareNumber>0
      begin
        Select  @EnviromentFeeVATAccountNumber = Accounts.VATAccountNumber, @EnviromentFeeVatValueNumber = VatValueNumber From Accounts WITH (NOLOCK) Where Accounts.AccountNumber = @EnviromentFeeResultAccountNumber
        exec GetVatvalueFromVATValueNumber @EnviromentFeeVatValueNumber, @VATValueEnviromentFee OUTPUT
      end
    end
    else
      SET @EnviromentFeeWareNumber = 0

    Select
      @AddonBalanceAccountNumber = Ware.BalanceAccountNumber,
      @AddonResultAccountNumber = Ware.ResultAccountNumber,
      @AddonWareText = Ware.WareName,
      @AddonWareNumber = Ware.WareNumber
    From WARE WITH (NOLOCK) 
      INNER JOIN WAREGROUPS WITH (NOLOCK) ON WARE.WareGroupNumber =  WAREGROUPS.WareGroupNumber
    WHERE (WAREGROUPS.Payment=4)  AND ((Ware.MarkAsDeleted is null)) AND Ware.SortNumber=5

    if @ChargeAddonAsWare=1
      Set @AddonWareNumber = @WareNumber1

    if (@ShowPrint=1)
    begin
      print '@AddOn warenumber test'
      print '@WareNumber1'
      print @WareNumber1
      print '@AddonWareNumber'
      print @AddonWareNumber
    end  
	
    if (@AddonWareNumber>0)
    begin
      Select  @AddonVATAccountNumber = Accounts.VATAccountNumber, @AddonVatValueNumber = VatValueNumber From Accounts WITH (NOLOCK) Where Accounts.AccountNumber = @AddonResultAccountNumber
      exec GetVatvalueFromVATValueNumber @AddonVatValueNumber, @VATValueAddon OUTPUT
    end
	
    SET @DiscountWareNumber = 0
    SELECT
      @DiscountwareText = Ware.WareName,
      @DiscountWareNumber = Ware.WareNumber
    FROM Ware WITH (NOLOCK) 
    INNER JOIN WareGroups WITH (NOLOCK) ON WARE.WareGroupNumber = WareGroups.WareGroupNumber
      AND WareGroups.Payment = 5  
    WHERE Ware.Type = 19
    AND Ware.MarkAsDeleted IS NULL
	
    if (@ShowPrint=1)
    begin
      print '@PostDate'
      Print Convert(Varchar(8),@PostDate,112)
    end
	
    SET @RunOneDayLongerProduct1 = 0
    SET @RunOneDayLongerProduct2 = 0
    SET @RunOneDayLongerProduct3 = 0
    SET @FeeFolioNumber = 0
	
    exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 0, @AllDiscountRate output
	
    if (@DayProduct=0)
    begin
      exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 1, @DiscountRate output

      if @PackagesplitAfterDiscount = 1
        SET @TotalDiscountValueForPackagesplit = @DiscountRate + @AllDiscountRate
      else
        SET @TotalDiscountValueForPackagesplit = 0
    end

    WHILE (@PostDate<=@PostToDate) AND (@PostDate<=@DepartureDate)
    Begin       
      IF (@Dayproduct=1) AND @LastPostDate <> @PostDate
      BEGIN
        SELECT @AnyPostHallsOnDay = COUNT(TransactionNumber) FROM Transactions WITH (NOLOCK) INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
        WHERE (FolioNumber IN (SELECT FolioNumber FROM Folios WITH (NOLOCK) WHERE ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber)))
        AND ((@GuestNumber>0 AND GuestNumber=@GuestNumber) OR (@GuestNumber = 0)) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0))) AND (PERSONEL.UserTypeNumber = 3)) AND (CONVERT(INT, CONVERT(FLOAT,OriginalDate))=CONVERT(INT,@PostDate))
        AND (((CONVERT(INT,  CONVERT(FLOAT,DateStamp)) = CONVERT(INT,@PostDate)) AND (WareNumber IN (SELECT WareNumber FROM Ware WITH (NOLOCK) WHERE ((Ware.MarkAsDeleted IS NULL) AND WareGroupNumber IN (SELECT WareGroupNumber FROM WareGroups WITH (NOLOCK) WHERE Payment = @PaymentType))))))

        SET @LastPostDate = @PostDate

        IF ISNULL(@AnyPostHallsOnDay, 0) = 0
        BEGIN
          -- any tables transactions
          SELECT @AnyPostHallsOnDay = COUNT(TransactionNumber) FROM Transactions WITH (NOLOCK) INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
          WHERE FolioNumber IN (
            SELECT FolioNumber FROM FolioRestResTableChairsXTab WITH (NOLOCK)
            INNER JOIN ReservationConferenceLine WITH (NOLOCK) ON FolioRestResTableChairsXTab.RestaurantReservationNumber = RESERVATIONCONFERENCELINE.ReservationConfLineNumber
            AND ReservationConferenceLine.ReferenceNumber = @ReferenceNumber
            )
          AND ((@GuestNumber>0 AND GuestNumber=@GuestNumber) OR (@GuestNumber = 0)) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0))) AND (PERSONEL.UserTypeNumber = 3)) AND (CONVERT(INT, CONVERT(FLOAT,OriginalDate))=CONVERT(INT,@PostDate))
          AND (((CONVERT(INT,  CONVERT(FLOAT,DateStamp)) = CONVERT(INT,@PostDate)) AND (WareNumber IN (SELECT WareNumber FROM Ware WITH (NOLOCK) WHERE ((Ware.MarkAsDeleted IS NULL) AND WareGroupNumber IN (SELECT WareGroupNumber FROM WareGroups WITH (NOLOCK) WHERE Payment = @PaymentType))))))
        END
      END

      SET @GetVatValueFromProduct2 = 0
      SET @GetVatValueFromProduct3 = 0
      SET @GetVatValueFromProduct4 = 0
	
      -- Hvis der er forudposteret rum for denne dag, skal der ikke konteres igen!!
      if (@Dayproduct=0)
      begin
        if (@ShowPrint=1)
        begin 
          print '@NumberOfPostRoomPrDay'
          print Convert(Integer,@PostDate)
          print @PaymentType
          print @PostDateStr
          print @DepartureDate
          print @RoomNumber
          print @VisualRoomNumber
          PRINT @AnyPostHallsOnDay
        end

        Select @NumberOfPostRoomPrDay = Count(TransactionNumber) from Transactions WITH (NOLOCK) INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
        where (FolioNumber in (Select FolioNumber FROM Folios WITH (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber)))
        AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))) AND /*OR (MovedDeleted=1 AND MovedFolioNr is null)) AND*/ (Convert(Integer,Convert(Float,OriginalDate))=Convert(Integer,@PostDate))
        AND (((Convert(Integer, Convert(Float,DateStamp)) = Convert(Integer,@PostDate)) AND (WareNumber in (Select WareNumber FROM Ware WITH (NOLOCK) where  ((Ware.MarkAsDeleted is null) AND WareGroupNumber in (Select WareGroupNumber FROM WareGroups WITH (NOLOCK) Where Payment = @PaymentType))))) -- ser om der er nogle roomposteringer
        OR (((Convert(Integer, Convert(Float,DateStamp))= Convert(Integer,@PostDate)) AND (@PostDateStr=@DepartureDate)) 
        AND ((WareNumber in (Select WareNumber FROM Ware WITH (NOLOCK) where  ((Ware.MarkAsDeleted is null) AND WareGroupNumber in (Select WareGroupNumber FROM WareGroups WITH (NOLOCK) Where Payment=4))))
        OR(((Convert(Integer, Convert(Float,DateStamp)) = Convert (Integer,@PostDate-1)) AND (WareNumber in (Select WareNumber FROM Ware WITH (NOLOCK) where  ((Ware.MarkAsDeleted is null) AND WareGroupNumber in (Select WareGroupNumber FROM WareGroups WITH (NOLOCK) Where Payment = @PaymentType)))))))))
      end
      else
      begin
        if ISNULL(@AnyPostHallsOnDay, 0) > 0
        begin
          if (@ShowPrint=1)
          begin 
            print '@PostDate'
            print @PostDate
            print '@TableReservationLineNumber'
            print @TableReservationLineNumber
          end

          if @TableReservationLineNumber > 0
          begin
            IF @OnlyBowling = 1
            BEGIN
              SELECT @NumberOfPostRoomPrDay = Count(TransactionNumber) FROM Transactions WITH (NOLOCK) INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
              WHERE (((Convert(varchar(8), DateStamp, 112) = @PostDate) AND (WareNumber in (SELECT WareNumber FROM Ware WITH (NOLOCK) where  ((Ware.MarkAsDeleted is null) AND WareGroupNumber in (Select WareGroupNumber FROM WareGroups WITH (NOLOCK) Where Payment = @PaymentType))))))
              AND (FolioNumber IN (
                SELECT FolioNumber FROM FolioRestResTableChairsXTab WITH (NOLOCK)
                INNER JOIN ReservationConferenceLine WITH (NOLOCK) ON FolioRestResTableChairsXTab.RestaurantReservationNumber = RESERVATIONCONFERENCELINE.ReservationConfLineNumber
                AND ReservationConferenceLine.ReferenceNumber = @ReferenceNumber))
              AND ((@GuestNumber>0 AND GuestNumber=@GuestNumber) or (@GuestNumber = 0)) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0))) AND (PERSONEL.UserTypeNumber = 3)) AND (Convert(varchar(8), OriginalDate, 112) = @PostDate)
            END
            ELSE
            BEGIN
              Select @NumberOfPostRoomPrDay = Count(TransactionNumber) from Transactions WITH (NOLOCK) INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
              where (((Convert(varchar(8), DateStamp, 112) = @PostDate) AND (WareNumber in (Select WareNumber FROM Ware WITH (NOLOCK) where  ((Ware.MarkAsDeleted is null) AND WareGroupNumber in (Select WareGroupNumber FROM WareGroups WITH (NOLOCK) Where Payment = @PaymentType))))))
              AND (FolioNumber in (Select FolioNumber FROM FolioRestResTableChairsXTab WITH (NOLOCK) where RestaurantReservationNumber=@TableReservationLineNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber)))
              AND ((@GuestNumber>0 AND GuestNumber=@GuestNumber) or (@GuestNumber = 0)) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0))) AND (PERSONEL.UserTypeNumber = 3)) AND (Convert(varchar(8), OriginalDate, 112) = @PostDate)
            END
          end
          else
          begin
            Select @NumberOfPostRoomPrDay = Count(TransactionNumber) from Transactions WITH (NOLOCK) INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
            where (((Convert(Integer,  Convert(Float,DateStamp)) = Convert(Integer,@PostDate)) AND (WareNumber in (Select WareNumber FROM Ware WITH (NOLOCK) where  ((Ware.MarkAsDeleted is null) AND WareGroupNumber in (Select WareGroupNumber FROM WareGroups WITH (NOLOCK) Where Payment = @PaymentType))))))
            AND (FolioNumber in (Select FolioNumber FROM Folios WITH (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber)))
            AND ((@GuestNumber>0 AND GuestNumber=@GuestNumber) or (@GuestNumber = 0)) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0))) AND (PERSONEL.UserTypeNumber = 3)) AND /*OR (MovedDeleted=1 AND MovedFolioNr is null)) AND*/ (Convert(Integer, Convert(Float,OriginalDate))=Convert(Integer,@PostDate))
            AND (ISNULL(@ProductNumber, 0) = 0 OR ProductNumber = @ProductNumber)
            AND (ISNULL(@VisualRoomNumber, 0) = 0 OR Note = CAST(@VisualRoomNumber AS VARCHAR(50)))
          end
        end
        else
          SET @NumberOfPostRoomPrDay = 0

        IF @PostDate < @ArrivalDate OR @PostDate > @DepartureDate
        BEGIN
          SET @NumberOfPostRoomPrDay = 1
        END
      end
	
      if (@ShowPrint=1)
      begin
        print '@NumberOfPostRoomPrDay'
        print @NumberOfPostRoomPrDay
        print '@DayProduct'
        print @DayProduct
      end  
	 
      if (@ShowPrint=1)
      begin
        print '@NumberOfPostRoomPrDay'
        print @NumberOfPostRoomPrDay
      end
	
/*
      if (@NumberOfPostRoomPrDay=0)  --der er ikke posteret ophold for denne dag!!!! --ks 9/5-2001
      begin
        IF @TableReservationLineNumber > 0
        BEGIN
          IF (@ShowPrint = 1)
          BEGIN
            PRINT '@TableReservationLineNumber'
            PRINT @TableReservationLineNumber
          END

          IF @OnlyBowling = 1
          BEGIN
            IF @ShowPrint = 1
              PRINT 'Only Bowling..'
            SELECT @NumberOfPostExMainArrPrDay = COUNT(TransactionNumber) 
            FROM Transactions WITH (NOLOCK) 
              INNER JOIN Personel WITH (NOLOCK) ON Transactions.UserIDNumber = Personel.UserIDNumber
              INNER JOIN ArrangementLines WITH (NOLOCK) ON ArrangementLines.WareNumber = TRANSACTIONS.WareNumber
                AND ArrangementLines.Date = @PostDateStr
              INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
                AND ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber
                AND ArrangementReservationsXtab.GuestNumber=0
              INNER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = ArrangementLines.FK_ExDepartment AND Departments.AutoCharge = 1
              INNER JOIN ReservationConferenceLine WITH (NOLOCK) ON ReservationConferenceLine.ReferenceNumber = ArrangementReservationsXtab.ReferenceNumber
              INNER JOIN FolioRestResTableChairsXTab WITH (NOLOCK) ON FolioRestResTableChairsXTab.FolioNumber = Transactions.FolioNumber 
                AND FolioRestResTableChairsXTab.RestaurantReservationNumber = ReservationConferenceLine.ReservationConfLineNumber
            WHERE ((CONVERT(Integer, CONVERT(FLOAT,OriginalDate)) = CONVERT(Integer,@PostDate)) AND ((Personel.UserTypeNumber = 4) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))))
            AND ISNULL(Transactions.ProductNumber, 0) = 0
            AND ISNULL(Transactions.PackageNumber, 0) = 0
          END
          ELSE
          BEGIN
            SELECT @NumberOfPostExMainArrPrDay = COUNT(TransactionNumber) 
            FROM Transactions WITH (NOLOCK) 
              INNER JOIN Personel WITH (NOLOCK) ON Transactions.UserIDNumber = Personel.UserIDNumber
              INNER JOIN ArrangementLines WITH (NOLOCK) ON ArrangementLines.WareNumber = TRANSACTIONS.WareNumber
                AND ArrangementLines.Date = @PostDateStr
              INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
                AND ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber
                AND ArrangementReservationsXtab.GuestNumber=0 
              INNER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = ArrangementLines.FK_ExDepartment 
                AND Departments.AutoCharge = 1
              INNER JOIN ReservationConferenceLine WITH (NOLOCK) ON ReservationConferenceLine.ReferenceNumber = ArrangementReservationsXtab.ReferenceNumber
              INNER JOIN FolioRestResTableChairsXTab WITH (NOLOCK) ON FolioRestResTableChairsXTab.RestaurantReservationNumber = ReservationConferenceLine.ReservationConfLineNumber
                AND FolioRestResTableChairsXTab.FolioNumber = Transactions.FolioNumber
		AND ISNULL(FolioRestResTableChairsXTab.ChairNumber, 0) = 0
            WHERE ((CONVERT(Integer, CONVERT(FLOAT,OriginalDate)) = CONVERT(Integer,@PostDate)) AND ((Personel.UserTypeNumber = 4) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))))
            AND ISNULL(Transactions.ProductNumber, 0) = 0
            AND ISNULL(Transactions.PackageNumber, 0) = 0
          END
  
          IF @NumberOfPostExMainArrPrDay = 0
          BEGIN
            SELECT @NumberOfPostExMainArrPrDay = COUNT(TransactionNumber) 
            FROM Transactions WITH (NOLOCK) 
              INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = Transactions.FolioNumber 
                AND Folios.ReferenceNumber = @ReferenceNumber AND Folios.GuestNumber=0
              INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
              INNER JOIN ArrangementLines WITH (NOLOCK) ON ArrangementLines.WareNumber = TRANSACTIONS.WareNumber
                AND ArrangementLines.Date = @PostDateStr
              INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
                AND ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber
                AND ArrangementReservationsXtab.GuestNumber = 0
              INNER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = ArrangementLines.FK_ExDepartment AND Departments.AutoCharge = 1
            WHERE ((OriginalDate = CONVERT(DATETIME, @PostDateStr, 112)) AND ((PERSONEL.UserTypeNumber = 4) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))))
            AND ISNULL(Transactions.ProductNumber, 0) = 0
            AND ISNULL(Transactions.PackageNumber, 0) = 0
          END 
        END
        ELSE
        BEGIN
          Select @NumberOfPostExMainArrPrDay = Count(TransactionNumber) 
          from Transactions WITH (NOLOCK) 
            INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = Transactions.FolioNumber 
              AND Folios.ReferenceNumber = @ReferenceNumber AND Folios.GuestNumber=0
            INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
            INNER JOIN ArrangementLines WITH (NOLOCK) ON ArrangementLines.WareNumber = TRANSACTIONS.WareNumber
              AND ArrangementLines.Date = @PostDateStr
            INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
              AND ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber
              AND ArrangementReservationsXtab.GuestNumber = 0
            INNER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = ArrangementLines.FK_ExDepartment AND Departments.AutoCharge = 1
          WHERE ((OriginalDate = CONVERT(DATETIME, @PostDateStr, 112)) AND ((PERSONEL.UserTypeNumber = 4) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))))
          AND ISNULL(Transactions.ProductNumber, 0) = 0
          AND ISNULL(Transactions.PackageNumber, 0) = 0

          IF ISNULL(@NumberOfPostExMainArrPrDay, 0) = 0
            SELECT @NumberOfPostExMainArrPrDay = COUNT(TransactionNumber) 
            FROM Transactions WITH (NOLOCK) 
              INNER JOIN Personel WITH (NOLOCK) ON Transactions.UserIDNumber = Personel.UserIDNumber
              INNER JOIN ArrangementLines WITH (NOLOCK) ON ArrangementLines.WareNumber = TRANSACTIONS.WareNumber
                AND ArrangementLines.Date = @PostDateStr
              INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
                AND ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber
                AND ArrangementReservationsXtab.GuestNumber=0
              INNER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = ArrangementLines.FK_ExDepartment AND Departments.AutoCharge = 1
              INNER JOIN FolioRestResTableChairsXTab WITH (NOLOCK) ON FolioRestResTableChairsXTab.FolioNumber = Transactions.FolioNumber
              INNER JOIN ReservationConferenceLine WITH (NOLOCK) ON ReservationConferenceLine.ReservationConfLineNumber = FolioRestResTableChairsXTab.RestaurantReservationNumber
                AND ReservationConferenceLine.ReferenceNumber = @ReferenceNumber
            WHERE  ((CONVERT(Integer, CONVERT(FLOAT,OriginalDate)) = CONVERT(Integer,@PostDate)) AND ((Personel.UserTypeNumber = 4) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))))
            AND ISNULL(Transactions.ProductNumber, 0) = 0
            AND ISNULL(Transactions.PackageNumber, 0) = 0
        END

        if @NumberOfPostExMainArrPrDay = 0
        begin
          if @GuestNumber=0
            SET @MainSplitbillNumber = @SplitBillNumber
          else
          if @MainSplitbillNumber<0
            Select @MainSplitbillNumber = isnull(SplitBill, 0) from Reservations WITH (Nolock) Where ReferenceNumber=@ReferenceNumber and GuestNumber=0

          IF @TableReservationLineNumber > 0
            EXEC PostExDepFromArrangement @ReferenceNumber, 0, @MainSplitBillNumber, @UserIDNumber, @PostDate, @PostDate, @HotelCountryNumber, @TotalPostExDepFromArrangement OUTPUT, @HotelCustomerNumber, -1, @TableReservationLineNumber
          ELSE
            EXEC PostExDepFromArrangement @ReferenceNumber, 0, @MainSplitBillNumber, @UserIDNumber, @PostDate, @PostDate, @HotelCountryNumber, @TotalPostExDepFromArrangement OUTPUT, @HotelCustomerNumber
        end
	      
        if @GuestNumber>0
        begin
          Set @NumberOfPostExArrPrDay = 0
	
          Select @NumberOfPostExArrPrDay = Count(TransactionNumber) 
          From Transactions WITH (NOLOCK)
            INNER JOIN PERSONEL WITH (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
            INNER JOIN ArrangementLines WITH (NOLOCK) ON ArrangementLines.WareNumber = TRANSACTIONS.WareNumber
            INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
            INNER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = ArrangementLines.FK_ExDepartment AND Departments.AutoCharge = 1
          WHERE ((ArrangementReservationsXtab.ReferenceNumber=@ReferenceNumber)  AND (ArrangementReservationsXtab.GuestNumber=@GuestNumber) AND (ArrangementLines.Date= @PostDateStr))
          AND ((OriginalDate = CONVERT(DATETIME, @PostDateStr, 112)) AND ((PERSONEL.UserTypeNumber = 4) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))))
          AND (((Transactions.ProductNumber is null) OR (Transactions.ProductNumber = 0)) AND ((Transactions.PackageNumber is null) OR (Transactions.PackageNumber = 0)))
--          AND (FolioNumber in (Select FolioNumber FROM Folios WITH (NOLOCK) where ReferenceNumber=@ReferenceNumber AND GuestNumber=@GuestNumber))
          AND (FolioNumber in (Select FolioNumber FROM Folios WITH (NOLOCK) where ReferenceNumber=@ReferenceNumber AND ((GuestNumber=@GuestNumber) OR (GuestNumber = 0))))
          AND Transactions.GuestNumber = @GuestNumber

          if @NumberOfPostExArrPrDay = 0
          Begin
            if ((@Day2+@Day3+@Day4)=0)
              SET @MainSplitbillNumber = @SplitBillNumber
            else   
            begin
              if (@PostDate<=(Convert (DATETIME, @ArrivalDate)+@Day2-1)) and  ((@PostDate) <> Convert (DATETIME, @DepartureDate))  
              Begin
                if @MainSplitbillNumber <> @SplitbillNumber1
                  SET @MainSplitbillNumber = @SplitbillNumber1
              end
              else 
              if (@Day3=0)
              begin
                if  @MainSplitbillNumber <> @SplitbillNumber2
                  SET @MainSplitbillNumber = @SplitbillNumber2
              end 
              else
              Begin
                if ((@PostDate>=(Convert (DATETIME, @ArrivalDate)+@Day2-1)) AND (@PostDate<=(Convert (DATETIME, @ArrivalDate)+@Day3-1))) AND ((Convert (DATETIME, @ArrivalDate)+@Day2-1)<>(Convert (DATETIME, @ArrivalDate)+@Day3-1))
                begin
                  if @MainSplitbillNumber <> @SplitbillNumber2
                    SET @MainSplitbillNumber = @SplitbillNumber2
                end
                else  
                if (@Day4=0)
                begin
                  if @MainSplitbillNumber <> @SplitbillNumber3
                    SET @MainSplitbillNumber = @SplitbillNumber3
                end
                else
                begin   
                  if @PostDate>=Convert (DATETIME,@ArrivalDate)+ @Day3-1 AND @PostDate<=Convert (DATETIME,@ArrivalDate)+ @Day4-1 AND ((Convert (DATETIME,@ArrivalDate)+ @Day3-1) <> (Convert (DATETIME,@ArrivalDate) + @Day4-1))
                  begin
                    if @MainSplitbillNumber <> @SplitbillNumber3
                      SET @MainSplitbillNumber = @SplitbillNumber3
                  end
                  else 
                  if ((@PostDate>=(Convert (DATETIME,@ArrivalDate)+ @Day4-1)) AND (@PostDate<=(Convert (DATETIME,@DepartureDate)))) AND ((Convert (DATETIME,@ArrivalDate)+ @Day4-1) <>Convert (DATETIME,@DepartureDate))
                  begin
                    if  @MainSplitbillNumber <> @SplitbillNumber4
                      SET @MainSplitbillNumber = @SplitbillNumber4
                  end
                end
              end
            end
		
            Exec PostExDepFromArrangement @ReferenceNumber, @GuestNumber, @MainSplitbillNumber, @UserIDNumber, @PostDate, @PostDate, @HotelCountryNumber, @TotalPostExDepFromArrangement OUTPUT, @HotelCustomerNumber
          end
        end            
*/	
      -- Precharge guest 0
      IF @GuestNumber = 0
        SET @MainSplitbillNumber = @SplitBillNumber
      ELSE IF @MainSplitbillNumber < 0
        SELECT @MainSplitbillNumber = ISNULL(SplitBill, 0) FROM Reservations WITH (NOLOCK) WHERE ReferenceNumber = @ReferenceNumber AND GuestNumber = 0
      IF @TableReservationLineNumber > 0
        EXEC PostExDepFromArrangement @ReferenceNumber, 0, @MainSplitBillNumber, @UserIDNumber, @PostDate, @PostDate, @HotelCountryNumber, @TotalPostExDepFromArrangement OUTPUT, @HotelCustomerNumber, -1, @TableReservationLineNumber
      ELSE
        EXEC PostExDepFromArrangement @ReferenceNumber, 0, @MainSplitBillNumber, @UserIDNumber, @PostDate, @PostDate, @HotelCountryNumber, @TotalPostExDepFromArrangement OUTPUT, @HotelCustomerNumber
      
      IF @GuestNumber > 0
      BEGIN
        IF (@Day2+@Day3+@Day4) = 0
          SET @MainSplitbillNumber = @SplitBillNumber
        ELSE
        BEGIN
          IF (@PostDate<=(CONVERT(DATETIME, @ArrivalDate)+@Day2-1)) AND ((@PostDate) <> CONVERT(DATETIME, @DepartureDate))  
          BEGIN
            IF @MainSplitbillNumber <> @SplitbillNumber1
              SET @MainSplitbillNumber = @SplitbillNumber1
          END
          ELSE IF (@Day3=0)
          BEGIN
            IF  @MainSplitbillNumber <> @SplitbillNumber2
              SET @MainSplitbillNumber = @SplitbillNumber2
          END 
          ELSE
          BEGIN
            IF ((@PostDate>=(CONVERT(DATETIME, @ArrivalDate)+@Day2-1)) AND (@PostDate<=(CONVERT(DATETIME, @ArrivalDate)+@Day3-1))) AND ((CONVERT(DATETIME, @ArrivalDate)+@Day2-1)<>(CONVERT(DATETIME, @ArrivalDate)+@Day3-1))
            BEGIN
              IF @MainSplitbillNumber <> @SplitbillNumber2
                SET @MainSplitbillNumber = @SplitbillNumber2
            END
            ELSE IF (@Day4=0)
            BEGIN
              IF @MainSplitbillNumber <> @SplitbillNumber3
                SET @MainSplitbillNumber = @SplitbillNumber3
            END
            ELSE
            BEGIN   
              IF @PostDate>=CONVERT(DATETIME,@ArrivalDate)+ @Day3-1 AND @PostDate<=CONVERT(DATETIME,@ArrivalDate)+ @Day4-1 AND ((CONVERT(DATETIME,@ArrivalDate)+ @Day3-1) <> (CONVERT(DATETIME,@ArrivalDate) + @Day4-1))
              BEGIN
                IF @MainSplitbillNumber <> @SplitbillNumber3
                  SET @MainSplitbillNumber = @SplitbillNumber3
              END
              ELSE IF ((@PostDate>=(CONVERT(DATETIME,@ArrivalDate)+ @Day4-1)) AND (@PostDate<=(CONVERT(DATETIME,@DepartureDate)))) AND ((CONVERT(DATETIME,@ArrivalDate)+ @Day4-1) <> CONVERT(DATETIME,@DepartureDate))
              BEGIN
                IF  @MainSplitbillNumber <> @SplitbillNumber4
                  SET @MainSplitbillNumber = @SplitbillNumber4
              END
            END
          END
        END

        EXEC PostExDepFromArrangement @ReferenceNumber, @GuestNumber, @MainSplitbillNumber, @UserIDNumber, @PostDate, @PostDate, @HotelCountryNumber, @TotalPostExDepFromArrangement OUTPUT, @HotelCustomerNumber
	  END

      if (@NumberOfPostRoomPrDay=0)  --der er ikke posteret ophold for denne dag!!!! --ks 9/5-2001
      begin
        SET @PackageTurnOver = 0
        SET @VatOfPackageTurnOver = 0
        SET @POSTProduct1 = 0
        SET @POSTProduct2 = 0
        SET @POSTProduct3 = 0
        SET @POSTProduct4 = 0
	
        if (@ShowPrint=1)
        begin
          print '@Dayproduct'
          print @Dayproduct
        end
	
        if (@Dayproduct=1)
        begin
          if (@NumberOfRooms < 1)
            SET @NumberOfRooms = 1
	
          EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber1 OUTPUT
	
          SET @POSTProduct1 = 1
          Set @StayStartDate = Convert (DATETIME, @ArrivalDate)
          Set @StayEndDate =  Convert (DATETIME,@DepartureDate)

          if (@ProductNumber>0)
          begin
            SET @DepartureAddon = 0
	
            exec ProductPricesDay @ProductNumber, @StayStartDate, @StayEndDate, @PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct1 OUTPUT, @BillTextProduct1Addon OUTPUT, @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFeeProduct1 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn1 OUTPUT, -1, 0, @EnviromentFeeType1 OUTPUT

            if @IsFixedPriceProduct=1
            begin
              exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 2, @DiscountRate output
              if (@PriceOverWritten=1)
              begin
                if isnull(@Price,0)=0 
                  SET @Price = 0
                SET @PriceProduct1 = @Price*@NumberOfRooms
              end
            end
            else
            begin
              exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 3, @DiscountRate output
              if (@PriceOverWritten=1)
              begin
                if isnull(@Price,0)=0 
                  SET @Price = 0
                SET  @PriceProduct1 = (Convert(Money, (@Price * (@Adults + @Children1+@Children2)))) * @NumberOfRooms
              end
            end

            if @PackagesplitAfterDiscount = 1
              SET @TotalDiscountValueForPackagesplit = @DiscountRate + @AllDiscountRate
            else
              SET @TotalDiscountValueForPackagesplit = 0

            if (@PacketNumber > 0)
              exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber, @StayResultAccountNumber1, 1,1, @PriceOverWritten, @BookedTypeNumber, @UserIDNumber, @PacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct1, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber, NULL, NULL, @TableReservationLineNumber, -1, @ReservationConfLineNumber
            else
            begin
              SET @PackagePriceProduct1 = 0
              SET @VatByPacketValueProduct1 = 0
            end
          end
          else -- no product
          begin
            exec GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 3, @DiscountRate output
            if (@PriceOverWritten=1)
            begin
              if isnull(@Price,0)=0 SET @Price = 0
              SET @PriceProduct1 = @Price*@NumberOfRooms*(@Adults+@Children1+@Children2)
            end
            else
              SET @PriceProduct1 = 0
	
            SET @Addon1 = 0
            SET @EnviromentFeeProduct1 = 0
	
            SET @DiscountRate = 0
            SET @BillTextProduct1 = ''
            SET @BillTextProduct1Addon = ''

            SET @PackagePriceProduct1 = 0
            SET @VatByPacketValueProduct1 = 0
	
            if (@PacketNumber > 0)
              exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber, @StayResultAccountNumber1, 1,1, @PriceOverWritten, @BookedTypeNumber, @UserIDNumber, @PacketNumberReservation, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct1, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber, NULL, NULL, @TableReservationLineNumber
            else
            begin
              SET @PackagePriceProduct1 = 0
              SET @VatByPacketValueProduct1 = 0
            end

            if (@ShowPrint=1)
            begin
              Print '@CalcPriceDay without product'
              Print Convert(VarChar(10),@CalcPriceDay)
            end
          end
        end
        else
        begin
          SET @TempVatByPacketValueProduct = 0
          SET @TempPackagePriceProduct = 0
	
          if ((@Day2+@Day3+@Day4)>0)
            SET @StarProduct=1
          else

            SET @StarProduct=0
	
          if (@StarProduct=0)
          Begin
            if @StayEndDate = @PostToDate+1

              SET @PostToDate = @StayEndDate
	
            SET @BillTextProduct1DepartureAddon = ''
            SET @DepartureAddon1 = 0
	
            SET @StayStartDate = Convert (DATETIME, @ArrivalDate)
            SET @StayEndDate =  Convert (DATETIME, @DepartureDate)
	
            if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
              EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber1 OUTPUT	

            SET @POSTProduct1 = 1

            exec ProductPricesDay @ProductNumber,@StayStartDate, @StayEndDate, @PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct1 OUTPUT, @BillTextProduct1Addon OUTPUT,  @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFeeProduct1 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn1 OUTPUT, -1, 0, @EnviromentFeeType1 OUTPUT
	
            if ((@SpecifiedDepartureAddOn1=0) AND (@StayEndDate=@PostDate+1)) /*OR ((@SpecifiedDepartureAddOn1=1) AND (@StayEndDate=@StayStartDate))*/
              exec ProductPricesDay @ProductNumber, @StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DepartureAddon1 OUTPUT, @DummyBillTextProduct OUTPUT, @BillTextProduct1DepartureAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
            else
            if ((@SpecifiedDepartureAddOn1=0) AND (@StayEndDate=@PostDate)AND(@StayEndDate<>@StayStartDate))
            begin
              SET @BillTextProduct1Addon = ''
              SET @Addon1 = 0
            end
	
            if (@GetVATFrom=4)
            begin
              SET @LogiWareIndex = @VATProduct+1
              exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @LogiWareIndex, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
            end
	
            if (@StayEndDate=@PostDate+1) -- pakke debitering afrejse dagen f°r
            begin
              exec ProductPricesDay @ProductNumber,@StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DummyDepartureAddon OUTPUT, @DummyBillTextProduct OUTPUT, @BillTextProduct1DepartureAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
	
              Select @NumberOfChargedDeparturePackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
              where ProductNumber = @ProductNumber and PackageNumber = @DummyPacketNumber
              AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
              AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
              AND AccountNumber = @PackageDebAccount and Debit=1
              AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @StayEndDate, 112)
	
              if @DummyPacketNumber>0 AND @NumberOfChargedDeparturePackaged = 0
              begin
                IF @PriceOverWritten=1 AND @AddonIfPriceOverwritten = 0
                  SET @DummyPriceProduct = 0
                if @DummySpecifiedDepartureAddOn = 1
                  SET @DummyPriceProduct = @DummyDepartureAddon
                else
                  SET @DummyPriceProduct = 0
                exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber, @StayResultAccountNumber1, 1,0, 1, @BookedTypeNumber, @UserIDNumber, @DummyPacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber
              end
              else
              begin
                SET @PackagePriceProduct1 = 0
                SET @VatByPacketValueProduct1 = 0
              end
            end
	
            if (@PriceOverWritten=1) OR (@ProductNumber=0)
            begin
              if (@StayEndDate<>@PostDate) OR (@StayEndDate=@StayStartDate)
              begin
                if isnull(@Price,0)=0 
                  SET @Price = 0
                IF @GuestNumber = 0 and @NumberOfRooms > 0
                  SET @PriceProduct1 = @Price * @NumberOfRooms
                ELSE 
                  SET @PriceProduct1 = @Price
              end
              if @PriceOverWritten=1
              begin
                if @AddonIfPriceOverwritten = 0
                begin
                  SET @Addon1 = 0
                  SET @DepartureAddon1 = 0
                  SET @BillTextProduct1DepartureAddon = ''
                end
              end
            end
	
            if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
            begin
              if (@StayEndDate=@PostDate+1)
              begin
                SET @TempVatByPacketValueProduct = @VatByPacketValueProduct1
                SET @TempPackagePriceProduct = @PackagePriceProduct1
              end
	
              Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
              where ProductNumber = @ProductNumber and PackageNumber = @PacketNumber
              AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
              AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))) 
              AND AccountNumber = @PackageDebAccount and Debit=1
              AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @PostDate, 112)

              if @PacketNumber>0 AND @NumberOfChargedPackaged = 0
                exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber, @StayResultAccountNumber1, 1, 1, @PriceOverWritten, @BookedTypeNumber, @UserIDNumber, @PacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct1, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber
              else
              begin
                SET @PackagePriceProduct1 = 0
                SET @VatByPacketValueProduct1 = 0
              end
              if (@StayEndDate=@PostDate+1)
              begin
                SET @VatByPacketValueProduct1 = @VatByPacketValueProduct1 + @TempVatByPacketValueProduct
                SET @PackagePriceProduct1 =  @PackagePriceProduct1 + @TempPackagePriceProduct
              end
            end
            else
            begin

              if @PacketNumber>0 AND @NumberOfChargedDeparturePackaged = 0
              begin
                if @SpecifiedDepartureAddOn1 = 1
                  SET @DummyPriceProduct = @Addon1
                else
                  SET @DummyPriceProduct = 0
                IF @DummyPriceProduct = 0 

                  SET @DummyPriceProduct = @PriceProduct1
                exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber, @StayResultAccountNumber1, 0, 1, 1, @BookedTypeNumber, @UserIDNumber, @PacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber
              end
              else
              begin
                SET @PackagePriceProduct1 = 0
                SET @VatByPacketValueProduct1 = 0
              end
            end
          end
          else -- StarProduct = 1
          begin
            SET @BillTextProduct1DepartureAddon = ''
            SET @BillTextProduct2DepartureAddon = ''
            SET @BillTextProduct3DepartureAddon = ''
            SET @BillTextProduct4DepartureAddon = ''
	
            SET @DepartureAddon1 = 0
            SET @DepartureAddon2 = 0
            SET @DepartureAddon3 = 0
            SET @DepartureAddon4 = 0
	
            if (@PostDate<=(Convert (DATETIME, @ArrivalDate)+@Day2-1)) and  ((@PostDate) <> Convert (DATETIME, @DepartureDate))  -- ProductNumber incl afrejse pakke
            Begin
              Set @StayStartDate = Convert (DATETIME, @ArrivalDate)
              Set @StayEndDate =  Convert (DATETIME, @ArrivalDate)+@Day2-1
	
              if not(@PostDate=@StayEndDate AND ((@PostToDate = @PostFromDate + 1) OR (@PostFromDateStr = @PostToDateStr)) AND @RunOneDayLongerProduct1=0)
              begin
                if NOT((@PostFromDateStr <> @PostToDateStr) AND (@PostDate=@StayEndDate))
                  SET @POSTProduct1 = 1

                IF @DayProduct = 1
                BEGIN
                  IF @PostProduct1 = 1 AND @PostDate >= @ArrivalDate AND @PostDate <= @DepartureDate
                    SET @POSTProduct1 = 1
                  ELSE
                    SET @POSTProduct1 = 0
                END

                if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                  EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber1 OUTPUT
	
                if (@PostToDate = @PostFromDate) AND (@PostDate+1 = @StayEndDate)
                begin
                  SET @PostToDate = @PostToDate + 1
                  SET @RunOneDayLongerProduct1 = 1
                end
	
                exec ProductPricesDay @ProductNumber,@StayStartDate, @StayEndDate, @PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct1 OUTPUT, @BillTextProduct1Addon OUTPUT,  @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFeeProduct1 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn1 OUTPUT, -1, 0, @EnviromentFeeType1 OUTPUT
	
                if ((@SpecifiedDepartureAddOn1=0) AND (@StayEndDate=@PostDate+1)) OR ((@SpecifiedDepartureAddOn1=1) AND (@StayEndDate=@StayStartDate))
                  exec ProductPricesDay @ProductNumber, @StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DepartureAddon1 OUTPUT, @DummyBillTextProduct OUTPUT, @BillTextProduct1DepartureAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
                else
                if ((@SpecifiedDepartureAddOn1=0) AND (@StayEndDate=@PostDate))
                begin
                  SET @BillTextProduct1Addon = ''
                  SET @Addon1 = 0
                end
	
                if (@GetVATFrom=4)
                begin
                  SET @LogiWareIndex = @VATProduct+1
                  exec GetVatValueAndAccountnumbers @DayProduct, @GetVatFrom, @LogiWareIndex, @WareNumber1 OUTPUT, @StayBalanceAccountNumber1 OUTPUT, @StayResultAccountNumber1 OUTPUT, @StayVATAccountNumber1 OUTPUT , @VatValueProduct1 OUTPUT, @WareText1 OUTPUT
                end
	
                if (@StayEndDate=@PostDate+1) -- pakke debitering afrejse dagen f°r
                begin
                  exec ProductPricesDay @ProductNumber,@StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DummyDepartureAddon OUTPUT, @DummyBillTextProduct OUTPUT, @DummyBillTextProductAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT , @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
	
                  Select @NumberOfChargedDeparturePackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                  where ProductNumber = @ProductNumber and PackageNumber = @DummyPacketNumber
                  AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                  AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                  AND AccountNumber = @PackageDebAccount and Debit=1
                  AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @StayEndDate, 112)
	
                  if @DummyPacketNumber>0 And @NumberOfChargedDeparturePackaged=0
                  begin
                    if @DummySpecifiedDepartureAddOn = 1
                      SET @DummyPriceProduct = @DummyDepartureAddon
                    else
                      SET @DummyPriceProduct = 0
                    exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber1, @StayResultAccountNumber1, 1, 0, 1, @BookedTypeNumber, @UserIDNumber, @DummyPacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber
                  end
                  else
                  begin
                    SET @PackagePriceProduct1 = 0
                    SET @VatByPacketValueProduct1 = 0
                  end
                end
	

                if (@PriceOverWritten=1) OR (@ProductNumber=0)
                begin
                  if (@StayEndDate<>@PostDate)
                  begin
                    if isnull(@Price,0)=0 SET @Price = 0
                    SET @PriceProduct1 = @Price
                  end
                  if @PriceOverWritten=1
                  begin
                    if @AddonIfPriceOverwritten = 0
                    begin
                      SET @Addon1 = 0
                      SET @DepartureAddon1 = 0

                      SET @BillTextProduct1DepartureAddon = ''
                    end
                  end
                end
	
                if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                begin
                  if (@StayEndDate=@PostDate+1)
                  begin
                    SET @TempVatByPacketValueProduct = @VatByPacketValueProduct1
                    SET @TempPackagePriceProduct = @PackagePriceProduct1
                  end
	   
                  Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                  where ProductNumber = @ProductNumber and PackageNumber = @PacketNumber
                  AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                  AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                  AND AccountNumber = @PackageDebAccount and Debit=1
                  AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @PostDate, 112)
	
                  if @PacketNumber>0 And @NumberOfChargedPackaged=0
                    exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber1, @StayResultAccountNumber1, 1, 1, @PriceOverWritten, @BookedTypeNumber, @UserIDNumber, @PacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct1, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber
                  else
                  begin
                    SET @PackagePriceProduct1 = 0
                    SET @VatByPacketValueProduct1 = 0
                  end
                  if (@StayEndDate=@PostDate+1)
                  begin
                    SET @VatByPacketValueProduct1 = @VatByPacketValueProduct1 + @TempVatByPacketValueProduct
                    SET @PackagePriceProduct1 =  @PackagePriceProduct1 + @TempPackagePriceProduct
                  end
                end
                else
                begin
                  if @PacketNumber>0 AND @NumberOfChargedDeparturePackaged = 0
                  begin
                    if @SpecifiedDepartureAddOn1 = 1
                      SET @DummyPriceProduct = @Addon1
                    else
                      SET @DummyPriceProduct = 0
	
                    exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber1, @StayResultAccountNumber1, 0, 1, 1, @BookedTypeNumber, @UserIDNumber, @PacketNumber, @ProductNumber, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @ProductWareLinkNumber1, @HotelCountryNumber, @HotelCustomerNumber
                  end
                  SET @PackagePriceProduct1 = 0
                  SET @VatByPacketValueProduct1 = 0
                end
              end
            end
            if (@RunOneDayLongerProduct1=0)
            begin
              if (@Day3=0)
              begin
                if (@PostDate>=(Convert (DATETIME, @ArrivalDate)+@Day2-1)) and ((Convert (DATETIME, @ArrivalDate)+@Day2-1)<>Convert (DATETIME, @DepartureDate))
                begin
                  SET @POSTProduct2 = 1
                  Set @StayStartDate = (Convert (DATETIME, @ArrivalDate)+@Day2-1)
                  Set @StayEndDate =  Convert (DATETIME, @DepartureDate)
	
                  if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                    EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber2 OUTPUT
	
                  exec ProductPricesDay @ProductNumber2,@StayStartDate, @StayEndDate,@PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon2 OUTPUT, @BillTextProduct2 OUTPUT, @BillTextProduct2Addon OUTPUT,  @PriceProduct2 OUTPUT, @PacketNumber2 OUTPUT, @EnviromentFeeProduct2 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn2 OUTPUT, -1, 0, @EnviromentFeeType2 OUTPUT

                  if ((@SpecifiedDepartureAddOn2=0) AND (@StayEndDate=@PostDate+1)) OR ((@SpecifiedDepartureAddOn2=1) AND (@StayEndDate=@StayStartDate))
                    exec ProductPricesDay @ProductNumber2, @StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DepartureAddon2 OUTPUT, @DummyBillTextProduct OUTPUT, @BillTextProduct2DepartureAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
                  else
                  if ((@SpecifiedDepartureAddOn2=0) AND (@StayEndDate=@PostDate))
                  begin
                    SET @BillTextProduct2Addon = ''
                    SET @Addon2 = 0
                  end
	
                  if ((@GetVatValueFromProduct2 = 0) and ((@GetVATFrom=3) OR (@GetVATFrom=4)))
                  begin
                    if (@GetVATFrom=3)
                      exec GetVatValueAndAccountnumbers 0, 3, @ProductNumber2,  @WareNumber2 OUTPUT, @StayBalanceAccountNumber2 OUTPUT, @StayResultAccountNumber2 OUTPUT, @StayVATAccountNumber2 OUTPUT , @VatValueProduct2 OUTPUT, @WareText2 OUTPUT
                    else
                    begin

                      SET @LogiWareIndex = @VATProduct+1
                      exec GetVatValueAndAccountnumbers 0, 4, @LogiWareIndex,  @WareNumber2 OUTPUT, @StayBalanceAccountNumber2 OUTPUT, @StayResultAccountNumber2 OUTPUT, @StayVATAccountNumber2 OUTPUT , @VatValueProduct2 OUTPUT, @WareText2 OUTPUT
                    end
                    SET @GetVatValueFromProduct2 = 1
                  end
	
                  if (@StayEndDate=@PostDate+1)
                  begin
                    exec ProductPricesDay @ProductNumber2,@StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DummyDepartureAddon OUTPUT, @DummyBillTextProduct OUTPUT, @DummyBillTextProductAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
	
                    Select @NumberOfChargedDeparturePackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                    where ProductNumber = @ProductNumber2 and PackageNumber = @DummyPacketNumber
                    AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                    AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))) 
                    AND AccountNumber = @PackageDebAccount and Debit=1
                    AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @StayEndDate, 112)
	
                    if @DummyPacketNumber>0 And @NumberOfChargedDeparturePackaged=0
                    begin
                      if @DummySpecifiedDepartureAddOn = 1
                        SET @DummyPriceProduct = @DummyDepartureAddon
                      else
                        SET @DummyPriceProduct = 0
	
                      exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber2, @StayResultAccountNumber2, 1, 0, 1, @BookedTypeNumber, @UserIDNumber, @DummyPacketNumber, @ProductNumber2, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @ProductWareLinkNumber2, @HotelCountryNumber, @HotelCustomerNumber
                    end
                    else
                    begin
                      SET @PackagePriceProduct2 = 0
                      SET @VatByPacketValueProduct2 = 0
                    end
                  end
	
                  if (@PriceOverWritten2=1) OR (@ProductNumber2=0)
                  begin
                    if (@StayEndDate<>@PostDate)
                    begin
                      if isnull(@FirstPrice2,0)=0 
                        SET @FirstPrice2 = 0
	
                      SET @PriceProduct2 = @FirstPrice2
                    end
                    if @PriceOverWritten2=1
                    begin
                      if @AddonIfPriceOverwritten = 0
                      begin
                        SET @Addon2 = 0
                        SET @DepartureAddon2 = 0
                        SET @BillTextProduct2DepartureAddon =''
                      end
                    end
                  end
	

                  if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                  begin
                    if (@StayEndDate=@PostDate+1)
                    begin
                      SET @TempVatByPacketValueProduct = @VatByPacketValueProduct2
                      SET @TempPackagePriceProduct = @PackagePriceProduct2
                    end
	
                    Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                    where ProductNumber = @ProductNumber2 and PackageNumber = @PacketNumber2
                    AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                    AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                    AND AccountNumber = @PackageDebAccount and Debit=1
                    AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @PostDate, 112)
	
                    if @PacketNumber2>0 And @NumberOfChargedPackaged=0
                    begin
                      if @DummySpecifiedDepartureAddOn = 1
                        SET @DummyPriceProduct = @DummyDepartureAddon
	
                      exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber2, @StayResultAccountNumber2, 1, 1, @PriceOverWritten2, @BookedTypeNumber, @UserIDNumber, @PacketNumber2, @ProductNumber2, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct2, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @ProductWareLinkNumber2, @HotelCountryNumber, @HotelCustomerNumber
                    end
                    else
                    begin
                      SET @PackagePriceProduct2 = 0
                      SET @VatByPacketValueProduct2 = 0
                    end
	
                    if (@StayEndDate=@PostDate+1)
                    begin
                      SET @VatByPacketValueProduct2 = @VatByPacketValueProduct2 + @TempVatByPacketValueProduct
                      SET @PackagePriceProduct2 =  @PackagePriceProduct2 + @TempPackagePriceProduct
                    end
                  end
                  else
                  begin
                    if @PacketNumber2>0 AND @NumberOfChargedDeparturePackaged = 0
                    begin
                      if @SpecifiedDepartureAddOn2 = 1
                        SET @DummyPriceProduct = @Addon2
                      else
                        SET @DummyPriceProduct = 0
	
                      exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber2, @StayResultAccountNumber2, 0, 1, 1, @BookedTypeNumber, @UserIDNumber, @PacketNumber2, @ProductNumber2, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @ProductWareLinkNumber2, @HotelCountryNumber, @HotelCustomerNumber
                    end
                    else
                    begin
                      SET @PackagePriceProduct2 = 0
                      SET @VatByPacketValueProduct2 = 0
                    end
                  end
                end
              end
              else
              Begin
                if ((@PostDate>=(Convert (DATETIME, @ArrivalDate)+@Day2-1)) AND (@PostDate<=(Convert (DATETIME, @ArrivalDate)+@Day3-1))) AND ((Convert (DATETIME, @ArrivalDate)+@Day2-1)<>(Convert (DATETIME, @ArrivalDate)+@Day3-1))
                Begin
                  Set @StayStartDate = Convert (DATETIME, @ArrivalDate) +@Day2-1
                  Set @StayEndDate = Convert (DATETIME, @ArrivalDate)+@Day3-1
	
                  if (@ShowPrint=1)
                  begin
                    Print '@ProductNumber2'
                    Print  @ProductNumber2
                  end
  
                  if not(@PostDate=@StayEndDate AND ((@PostToDate = @PostFromDate + 1) OR (@PostFromDateStr = @PostToDateStr)) AND @RunOneDayLongerProduct2=0)
                  begin
                    if NOT((@PostFromDateStr <> @PostToDateStr) AND (@PostDate=@StayEndDate))
                      SET @POSTProduct2 = 1
	
                    if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                      EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber2 OUTPUT
	
                    if  (@PostToDate  = @PostFromDate) AND (@PostDate+1= @StayEndDate)
                    begin
                      SET @PostToDate = @PostToDate + 1
                      SET @RunOneDayLongerProduct2 = 1
                    end
	
                    exec ProductPricesDay @ProductNumber2,@StayStartDate, @StayEndDate,@PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon2 OUTPUT, @BillTextProduct2 OUTPUT, @BillTextProduct2Addon OUTPUT,  @PriceProduct2 OUTPUT, @PacketNumber2 OUTPUT, @EnviromentFeeProduct2 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn2 OUTPUT, -1, 0, @EnviromentFeeType2 OUTPUT 
	
                    if ((@SpecifiedDepartureAddOn2=0) AND (@StayEndDate=@PostDate+1)) OR ((@SpecifiedDepartureAddOn2=1) AND (@StayEndDate=@StayStartDate))
                      exec ProductPricesDay @ProductNumber2, @StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DepartureAddon2 OUTPUT, @DummyBillTextProduct OUTPUT, @BillTextProduct2DepartureAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
                    else
                    if ((@SpecifiedDepartureAddOn2=0) AND (@StayEndDate=@PostDate))
                    begin
                      SET @BillTextProduct2Addon = ''
                      SET @Addon2 = 0
                    end
	
                    if ((@GetVatValueFromProduct2 = 0) and ((@GetVATFrom=3) OR (@GetVATFrom=4)))
                    begin
                      if (@GetVATFrom=3)
                        exec GetVatValueAndAccountnumbers 0, 3, @ProductNumber2,  @WareNumber2 OUTPUT, @StayBalanceAccountNumber2 OUTPUT, @StayResultAccountNumber2 OUTPUT, @StayVATAccountNumber2 OUTPUT , @VatValueProduct2 OUTPUT, @WareText2 OUTPUT
                      else
                      begin
                        SET @LogiWareIndex = @VATProduct+1
                        exec GetVatValueAndAccountnumbers 0, 4, @LogiWareIndex,  @WareNumber2 OUTPUT, @StayBalanceAccountNumber2 OUTPUT, @StayResultAccountNumber2 OUTPUT, @StayVATAccountNumber2 OUTPUT , @VatValueProduct2 OUTPUT, @WareText2 OUTPUT
                      end
	
                      SET @GetVatValueFromProduct2 = 1

                    end
	
                    if (@StayEndDate=@PostDate+1)
                    begin
                      exec ProductPricesDay @ProductNumber2,@StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DummyDepartureAddon OUTPUT, @DummyBillTextProduct OUTPUT, @DummyBillTextProductAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
	
                      Select @NumberOfChargedDeparturePackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                      where ProductNumber = @ProductNumber2 and PackageNumber = @DummyPacketNumber
                      AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                      AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3))) AND /*OR (MovedDeleted=1 AND MovedFolioNr is null)) AND*/ (Convert(Integer,Convert(Float,OriginalDate))=Convert(Integer, @StayEndDate))
                      AND AccountNumber = @PackageDebAccount and Debit=1
                      AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @StayEndDate, 112)
	
                      if @DummyPacketNumber>0 And @NumberOfChargedDeparturePackaged=0
                      begin
                        if @DummySpecifiedDepartureAddOn = 1
                          SET @DummyPriceProduct = @DummyDepartureAddon
                        else
                          SET @DummyPriceProduct = 0
	
                        exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber2, @StayResultAccountNumber2, 1, 0, 1, @BookedTypeNumber, @UserIDNumber, @DummyPacketNumber, @ProductNumber2, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @ProductWareLinkNumber2, @HotelCountryNumber, @HotelCustomerNumber
                      end

                      else
                      begin
                        SET @PackagePriceProduct2 = 0
                        SET @VatByPacketValueProduct2 = 0
                      end
                    end
	
                    if (@PriceOverWritten2=1) OR (@ProductNumber2=0)
                    begin
                      if (@StayEndDate<>@PostDate)
                      begin
                        if isnull(@FirstPrice2,0)=0 SET @FirstPrice2 = 0
                        SET @PriceProduct2 = @FirstPrice2
                      end
                      if @PriceOverWritten2=1
                      begin
                        if @AddonIfPriceOverwritten = 0
                        begin
                          SET @Addon2 = 0
                          SET @DepartureAddon2 = 0
                          SET @BillTextProduct2DepartureAddon = ''
                        end
                      end
                    end
	
                    if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                    begin
                      if (@StayEndDate=@PostDate+1)
                      begin
                        SET @TempVatByPacketValueProduct = @VatByPacketValueProduct2
                        SET @TempPackagePriceProduct = @PackagePriceProduct2
                      end
	
                      Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                      where ProductNumber = @ProductNumber2 and PackageNumber = @PacketNumber2
                      AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                      AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                      AND AccountNumber = @PackageDebAccount and Debit=1
                      AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @PostDate, 112)
	
                      if @PacketNumber2>0 And @NumberOfChargedPackaged=0
                        exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber2, @StayResultAccountNumber2, 1, 1, @PriceOverWritten2, @BookedTypeNumber, @UserIDNumber, @PacketNumber2, @ProductNumber2, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct2, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @ProductWareLinkNumber2, @HotelCountryNumber, @HotelCustomerNumber
                      else
                      begin
                        SET @PackagePriceProduct2 = 0
                        SET @VatByPacketValueProduct2 = 0
                      end
	
                      if (@StayEndDate=@PostDate+1)
                      begin
                        SET @VatByPacketValueProduct2 = @VatByPacketValueProduct2 + @TempVatByPacketValueProduct
                        SET @PackagePriceProduct2 =  @PackagePriceProduct2 + @TempPackagePriceProduct
                      end
                    end

                    else
                    begin
                      if @PacketNumber2>0 AND @NumberOfChargedDeparturePackaged = 0
                      begin
                        if @SpecifiedDepartureAddOn2 = 1
                          SET @DummyPriceProduct = @Addon2
                        else
                          SET @DummyPriceProduct = 0
	
                        exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber2, @StayResultAccountNumber2, 0, 1, 1, @BookedTypeNumber, @UserIDNumber, @PacketNumber2, @ProductNumber2, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @ProductWareLinkNumber2, @HotelCountryNumber, @HotelCustomerNumber
                      end
                      SET @PackagePriceProduct2 = 0
                      SET @VatByPacketValueProduct2 = 0
                    end
                  end
                end
	
                if (@RunOneDayLongerProduct2=0)
                begin
                  if (@Day4=0)
                  begin
                    if (@PostDate>=(Convert (DATETIME,@ArrivalDate)+ @Day3-1)) AND ((Convert (DATETIME, @ArrivalDate) +@Day3-1)<>(Convert (DATETIME, @DepartureDate)))
                    begin
                      SET @POSTProduct3 = 1
                      Set @StayStartDate = Convert (DATETIME, @ArrivalDate) +@Day3-1
                      Set @StayEndDate =  Convert (DATETIME, @DepartureDate)
	
                      if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                        EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber3 OUTPUT
	
                      exec ProductPricesDay @ProductNumber3, @StayStartDate, @StayEndDate, @PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2,  @Addon3 OUTPUT, @BillTextProduct3 OUTPUT, @BillTextProduct3Addon OUTPUT,  @PriceProduct3 OUTPUT, @PacketNumber3 OUTPUT, @EnviromentFeeProduct3 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn3 OUTPUT, -1, 0, @EnviromentFeeType3 OUTPUT

                      if ((@SpecifiedDepartureAddOn3=0) AND (@StayEndDate=@PostDate+1)) OR ((@SpecifiedDepartureAddOn3=1) AND (@StayEndDate=@StayStartDate))
                        exec ProductPricesDay @ProductNumber3, @StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DepartureAddon3 OUTPUT, @DummyBillTextProduct OUTPUT, @BillTextProduct3DepartureAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
                      else
                      if ((@SpecifiedDepartureAddOn3=0) AND (@StayEndDate=@PostDate))
                      begin
                        SET @BillTextProduct3Addon = ''
                        SET @Addon3 = 0
                      end
	
                      if ((@GetVatValueFromProduct3 = 0) and ((@GetVATFrom=3) OR (@GetVATFrom=4)))
                      begin
                        if (@GetVATFrom=3)
                          exec GetVatValueAndAccountnumbers 0, 3, @ProductNumber3,  @WareNumber3 OUTPUT, @StayBalanceAccountNumber3 OUTPUT, @StayResultAccountNumber3 OUTPUT, @StayVATAccountNumber3 OUTPUT , @VatValueProduct3 OUTPUT, @WareText3 OUTPUT
                        else
                        begin

                          SET @LogiWareIndex = @VATProduct+1
                          exec GetVatValueAndAccountnumbers 0, 4, @LogiWareIndex,  @WareNumber3 OUTPUT, @StayBalanceAccountNumber3 OUTPUT, @StayResultAccountNumber3 OUTPUT, @StayVATAccountNumber3 OUTPUT , @VatValueProduct3 OUTPUT, @WareText3 OUTPUT
                        end
                        SET @GetVatValueFromProduct3 = 1
                      end
	
                      if (@StayEndDate=@PostDate+1)
                      begin
                        exec ProductPricesDay @ProductNumber3,@StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DummyDepartureAddon OUTPUT, @DummyBillTextProduct OUTPUT, @DummyBillTextProductAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
	
                        Select @NumberOfChargedDeparturePackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                        where ProductNumber = @ProductNumber3 and PackageNumber = @DummyPacketNumber
                        AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                        AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                        AND AccountNumber = @PackageDebAccount and Debit=1
                        AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @StayEndDate, 112)
	
                        if @DummyPacketNumber>0 And @NumberOfChargedDeparturePackaged=0
                        begin
                          if @DummySpecifiedDepartureAddOn = 1
                            SET @DummyPriceProduct = @DummyDepartureAddon
                          else
                            SET @DummyPriceProduct = 0
	
                          exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber3, @StayResultAccountNumber3, 1, 0, 1, @BookedTypeNumber, @UserIDNumber, @DummyPacketNumber, @ProductNumber3, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @ProductWareLinkNumber3, @HotelCountryNumber, @HotelCustomerNumber
                        end
                        else
                        begin
                          SET @PackagePriceProduct3 = 0
                          SET @VatByPacketValueProduct3 = 0
                        end
                      end
	
                      if (@PriceOverWritten3=1) OR (@ProductNumber3=0)
                      begin
                        if (@StayEndDate<>@PostDate)
                        begin
                          if isnull(@FirstPrice3,0)=0 SET @FirstPrice3 = 0
                          SET @PriceProduct3 = @FirstPrice3
                        end
                        if @PriceOverWritten3=1
                        begin
                          if @AddonIfPriceOverwritten = 0
                          begin
                            SET @Addon3 = 0
                            SET @DepartureAddon3 = 0
                            SET @BillTextProduct3DepartureAddon = ''
                          end
                        end
                      end	

                      if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                      begin
                        if (@StayEndDate=@PostDate+1)
                        begin
                          SET @TempVatByPacketValueProduct = @VatByPacketValueProduct3
                          SET @TempPackagePriceProduct = @PackagePriceProduct3
                        end
	
                        Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                        where ProductNumber = @ProductNumber3 and PackageNumber = @PacketNumber3
                        AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                        AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                        AND AccountNumber = @PackageDebAccount and Debit=1
                        AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @PostDate, 112)
	
                        if @PacketNumber3>0 And @NumberOfChargedPackaged=0
                          exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber3, @StayResultAccountNumber3, 1, 1, @PriceOverWritten3, @BookedTypeNumber, @UserIDNumber, @PacketNumber3, @ProductNumber3, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct3, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @ProductWareLinkNumber3, @HotelCountryNumber, @HotelCustomerNumber
                        else
                        begin
                          SET @PackagePriceProduct3 = 0
                          SET @VatByPacketValueProduct3 = 0
                        end
	
                        if (@StayEndDate=@PostDate+1)
                        begin
                          SET @VatByPacketValueProduct3 = @VatByPacketValueProduct3 + @TempVatByPacketValueProduct
                          SET @PackagePriceProduct3 =  @PackagePriceProduct3 + @TempPackagePriceProduct
                        end
                      end
                      else
                      begin
                        if @PacketNumber3>0 AND @NumberOfChargedDeparturePackaged = 0
                        begin
                          if @SpecifiedDepartureAddOn3 = 1
                            SET @DummyPriceProduct = @Addon3
                          else
                            SET @DummyPriceProduct = 0
	
                          exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber3, @StayResultAccountNumber3, 0, 1, 1, @BookedTypeNumber, @UserIDNumber, @PacketNumber3, @ProductNumber3, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @ProductWareLinkNumber3, @HotelCountryNumber, @HotelCustomerNumber
                        end
                        else
                        begin
                          SET @PackagePriceProduct3 = 0
                          SET @VatByPacketValueProduct3 = 0
                        end
                      end
                    end
                  end
                  else
                  begin
                    set @Arrdate = Convert (DATETIME,@ArrivalDate)
                    if @PostDate>=@ArrDate+ @Day3-1 AND @PostDate<=@Arrdate+ @Day4-1 /*AV 290702*/ AND ((@ArrDate+ @Day3-1) <> (@Arrdate + @Day4-1))
                    begin
                      Set @StayStartDate = Convert (DATETIME, @ArrivalDate) +@Day3-1
                      Set @StayEndDate =  Convert (DATETIME, @ArrivalDate)+@Day4-1
	
                      if not(@PostDate=@StayEndDate AND ((@PostToDate = @PostFromDate + 1) OR (@PostFromDateStr = @PostToDateStr)) AND @RunOneDayLongerProduct3=0)
                      begin
                        if NOT((@PostFromDateStr <> @PostToDateStr) AND (@PostDate=@StayEndDate))
                          SET @POSTProduct3 = 1


                        if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                          EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber3 OUTPUT
	 
                        if (@PostToDate = @PostFromDate) AND (@PostDate+1 = @StayEndDate)
                        begin
                          SET @PostToDate = @PostToDate + 1
                          SET @RunOneDayLongerProduct3 = 1
                        end
                        exec ProductPricesDay @ProductNumber3,@StayStartDate, @StayEndDate,@PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon3 OUTPUT, @BillTextProduct3 OUTPUT, @BillTextProduct3Addon OUTPUT,  @PriceProduct3 OUTPUT, @PacketNumber3 OUTPUT, @EnviromentFeeProduct3 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn3 OUTPUT, -1, 0, @EnviromentFeeType3 OUTPUT
	
                        if ((@SpecifiedDepartureAddOn3=0) AND (@StayEndDate=@PostDate+1)) OR ((@SpecifiedDepartureAddOn3=1) AND (@StayEndDate=@StayStartDate))
                          exec ProductPricesDay @ProductNumber3, @StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DepartureAddon3 OUTPUT, @DummyBillTextProduct OUTPUT, @BillTextProduct3DepartureAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
                        else
                        if ((@SpecifiedDepartureAddOn3=0) AND (@StayEndDate=@PostDate))
                        begin
                          SET @BillTextProduct3Addon = ''
                          SET @Addon3 = 0
                        end
	
                        if ((@GetVatValueFromProduct3 = 0) and ((@GetVATFrom=3) OR (@GetVATFrom=4)))
                        begin
                          if (@GetVATFrom=3)
                            exec GetVatValueAndAccountnumbers 0, 3, @ProductNumber3,  @WareNumber3 OUTPUT, @StayBalanceAccountNumber3 OUTPUT, @StayResultAccountNumber3 OUTPUT, @StayVATAccountNumber3 OUTPUT , @VatValueProduct3 OUTPUT, @WareText3 OUTPUT
                          else
                          begin
                            SET @LogiWareIndex = @VATProduct+1
                            exec GetVatValueAndAccountnumbers 0, 4, @LogiWareIndex,  @WareNumber3 OUTPUT, @StayBalanceAccountNumber3 OUTPUT, @StayResultAccountNumber3 OUTPUT, @StayVATAccountNumber3 OUTPUT , @VatValueProduct3 OUTPUT, @WareText3 OUTPUT
                          end
                          SET @GetVatValueFromProduct3 = 1
                        end
	
                        if (@StayEndDate=@PostDate+1)
                        begin
                          exec ProductPricesDay @ProductNumber3,@StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DummyDepartureAddon OUTPUT, @DummyBillTextProduct OUTPUT, @DummyBillTextProductAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
	
                          Select @NumberOfChargedDeparturePackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                          where ProductNumber = @ProductNumber3 and PackageNumber = @DummyPacketNumber
                          AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                          AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                          AND AccountNumber = @PackageDebAccount and Debit=1
                          AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @StayEndDate, 112)
	
                          if @DummyPacketNumber>0 And @NumberOfChargedDeparturePackaged=0
                          begin
                            if @DummySpecifiedDepartureAddOn = 1
                              SET @DummyPriceProduct = @DummyDepartureAddon
                            else
                              SET @DummyPriceProduct = 0
	
                            exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber3, @StayResultAccountNumber3, 1, 0, 1, @BookedTypeNumber, @UserIDNumber, @DummyPacketNumber, @ProductNumber3, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @ProductWareLinkNumber3, @HotelCountryNumber, @HotelCustomerNumber
                          end
                          else
                          begin
                            SET @PackagePriceProduct3 = 0
                            SET @VatByPacketValueProduct3 = 0
                          end
                        end
                        if (@PriceOverWritten3=1) OR (@ProductNumber3=0)
                        begin
                          if (@StayEndDate<>@PostDate)
                          begin
                            if isnull(@FirstPrice3,0)=0 SET @FirstPrice3 = 0
                            SET @PriceProduct3 = @FirstPrice3
                          end
                          if @PriceOverWritten3=1
                          begin
                            if @AddonIfPriceOverwritten = 0
                            begin
                              SET @Addon3 = 0
                              SET @DepartureAddon3 = 0
                              SET @BillTextProduct3DepartureAddon = ''
                            end
                          end
                        end

                        if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                        begin
                          if (@StayEndDate=@PostDate+1)
                          begin
                            SET @TempVatByPacketValueProduct = @VatByPacketValueProduct3
                            SET @TempPackagePriceProduct = @PackagePriceProduct3
                          end
	
                          Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                          where ProductNumber = @ProductNumber3 and PackageNumber = @PacketNumber3
                          AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                          AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                          AND AccountNumber = @PackageDebAccount and Debit=1
                          AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @PostDate, 112)
	
                          if @PacketNumber3>0 And @NumberOfChargedPackaged=0
                            exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber3, @StayResultAccountNumber3, 1, 1, @PriceOverWritten3, @BookedTypeNumber, @UserIDNumber, @PacketNumber3, @ProductNumber3, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct3, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @ProductWareLinkNumber3, @HotelCountryNumber, @HotelCustomerNumber
                          else
                          begin
                            SET @PackagePriceProduct3 = 0
                            SET @VatByPacketValueProduct3 = 0
                          end
	
                          if (@StayEndDate=@PostDate+1)
                          begin
                            SET @VatByPacketValueProduct3 = @VatByPacketValueProduct3 + @TempVatByPacketValueProduct
                            SET @PackagePriceProduct3 =  @PackagePriceProduct3 + @TempPackagePriceProduct
                          end
                        end
                        else
                        begin
                          if @PacketNumber3>0 AND @NumberOfChargedDeparturePackaged = 0
                          begin
                            if @SpecifiedDepartureAddOn3 = 1
                              SET @DummyPriceProduct = @Addon3
                            else
                              SET @DummyPriceProduct = 0
	
                            exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber3, @StayResultAccountNumber3, 0, 1, 1, @BookedTypeNumber, @UserIDNumber, @PacketNumber3, @ProductNumber3, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @ProductWareLinkNumber3, @HotelCountryNumber, @HotelCustomerNumber
                          end
                          SET @PackagePriceProduct3 = 0
                          SET @VatByPacketValueProduct3 = 0
                        end
                      end
                    End
	
                    if (@RunOneDayLongerProduct3=0)
                    Begin
                      SET @PackagePriceProduct4 = 0
                      SET @VatByPacketValueProduct4 = 0
                      SET @PriceProduct4 = 0
                      SET @Addon4 = 0
                      SET @EnviromentFeeProduct4 = 0
--                      SET @DiscountRate = 0
                      SET @BillTextProduct4 = ''
                      SET @BillTextProduct4Addon = ''
	
                      if ((@PostDate>=(Convert (DATETIME,@ArrivalDate)+ @Day4-1)) AND (@PostDate<=(Convert (DATETIME,@DepartureDate)))) AND ((Convert (DATETIME,@ArrivalDate)+ @Day4-1) <>Convert (DATETIME,@DepartureDate))
                      begin
                        SET @POSTProduct4 = 1
                        Set @StayStartDate =  Convert (DATETIME, @ArrivalDate)+@Day4-1
                        Set @StayEndDate =  Convert (DATETIME, @DepartureDate)
	
                        if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                          EXEC GetNextNumber 'PRODUCTWARELINKIDENTITY', 1, @ProductWareLinkNumber4 OUTPUT

                        exec ProductPricesDay @ProductNumber4,@StayStartDate, @StayEndDate,@PostDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon4 OUTPUT, @BillTextProduct4 OUTPUT, @BillTextProduct4Addon OUTPUT,  @PriceProduct4 OUTPUT, @PacketNumber4 OUTPUT, @EnviromentFeeProduct4 OUTPUT, @IsFixedPriceProduct OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn4 OUTPUT, -1, 0, @EnviromentFeeType4 OUTPUT

                        if ((@SpecifiedDepartureAddOn4=0) AND (@StayEndDate=@PostDate+1)) OR ((@SpecifiedDepartureAddOn4=1) AND (@StayEndDate=@StayStartDate))
                          exec ProductPricesDay @ProductNumber4, @StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DepartureAddon4 OUTPUT, @DummyBillTextProduct OUTPUT, @BillTextProduct4DepartureAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
                        else
                        if ((@SpecifiedDepartureAddOn4=0) AND (@StayEndDate=@PostDate))
                        begin
                          SET @BillTextProduct4Addon = ''
                          SET @Addon4 = 0
                        end
	
                        if ((@GetVatValueFromProduct4 = 0) and ((@GetVATFrom=3) OR (@GetVATFrom=4)))
                        begin

                          if (@GetVATFrom=3)
                            exec GetVatValueAndAccountnumbers 0, 3, @ProductNumber4,  @WareNumber4 OUTPUT, @StayBalanceAccountNumber4 OUTPUT, @StayResultAccountNumber4 OUTPUT, @StayVATAccountNumber4 OUTPUT , @VatValueProduct4 OUTPUT, @WareText4 OUTPUT
                          else
                          begin
                            SET @LogiWareIndex = @VATProduct+1
                            exec GetVatValueAndAccountnumbers 0, 4, @LogiWareIndex,  @WareNumber4 OUTPUT, @StayBalanceAccountNumber4 OUTPUT, @StayResultAccountNumber4 OUTPUT, @StayVATAccountNumber4 OUTPUT , @VatValueProduct4 OUTPUT, @WareText4 OUTPUT
                          end
                          SET @GetVatValueFromProduct4 = 1
                        end
	  
                        if (@StayEndDate=@PostDate+1)
                        begin
                          exec ProductPricesDay @ProductNumber4,@StayStartDate, @StayEndDate, @StayEndDate, @BookedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @DummyDepartureAddon OUTPUT, @DummyBillTextProduct OUTPUT, @DummyBillTextProductAddon OUTPUT,  @DummyPriceProduct OUTPUT, @DummyPacketNumber OUTPUT, @DummyEnviromentFeeProduct OUTPUT, @DummyIsFixedPriceProduct OUTPUT, @DummyVATProduct OUTPUT, @DummySpecifiedDepartureAddOn OUTPUT, -1, 0, @DummyEnviromentFeeType OUTPUT
	
                          Select @NumberOfChargedDeparturePackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                          where ProductNumber = @ProductNumber4 and PackageNumber = @DummyPacketNumber
                          AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                          AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                          AND AccountNumber = @PackageDebAccount and Debit=1
                          AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @StayEndDate, 112)
	
                          if @DummyPacketNumber>0 And @NumberOfChargedDeparturePackaged=0
                          begin
                            if @DummySpecifiedDepartureAddOn = 1
                              SET @DummyPriceProduct = @DummyDepartureAddon
                            else
                              SET @DummyPriceProduct = 0

                            exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber4, @StayResultAccountNumber4, 1, 0, 1, @BookedTypeNumber, @UserIDNumber, @DummyPacketNumber, @ProductNumber4, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct4 OUTPUT, @VatByPacketValueProduct4 OUTPUT, @ProductWareLinkNumber4, @HotelCountryNumber, @HotelCustomerNumber
                          end
                          else
                          begin

                            SET @PackagePriceProduct4 = 0
                            SET @VatByPacketValueProduct4 = 0
                          end
                        end
    
                        if (@PriceOverWritten4=1) OR (@ProductNumber4=0)
                        begin
                          if (@StayEndDate<>@PostDate)
                          begin
                            if isnull(@FirstPrice4,0)=0 SET @FirstPrice4 = 0
                            SET @PriceProduct4 = @FirstPrice4
                          end
                          if @PriceOverWritten4=1
                          begin
                            if @AddonIfPriceOverwritten = 0
                            begin
                              SET @Addon4 = 0
                              SET @DepartureAddon4 = 0
                              SET @BillTextProduct4DepartureAddon = ''
                            end
                          end
                        end

                        if (@StayEndDate<>@PostDate) OR (@StayEndDate = @StayStartDate)
                        begin
                          if (@StayEndDate=@PostDate+1)
                          begin
                            SET @TempVatByPacketValueProduct = @VatByPacketValueProduct4
                            SET @TempPackagePriceProduct = @PackagePriceProduct4
                          end
	 
                          Select @NumberOfChargedPackaged = Count(TransactionNumber) from Transactions (NOLOCK) INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
                          where ProductNumber = @ProductNumber4 and PackageNumber = @PacketNumber4
                          AND FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber))
                          AND (GuestNumber=@GuestNumber) AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
                          AND AccountNumber = @PackageDebAccount and Debit=1
                          AND Convert(VARCHAR(8), OriginalDate, 112) = Convert(VARCHAR(8), @PostDate, 112)

                          if @PacketNumber4>0 And @NumberOfChargedPackaged=0
                            exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber4, @StayResultAccountNumber4, 1,1, @PriceOverWritten4, @BookedTypeNumber, @UserIDNumber, @PacketNumber4, @ProductNumber4, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @PriceProduct4, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct4 OUTPUT, @VatByPacketValueProduct4 OUTPUT, @ProductWareLinkNumber4, @HotelCountryNumber, @HotelCustomerNumber
                          else
                          begin
                            SET @PackagePriceProduct4 = 0
                            SET @VatByPacketValueProduct4 = 0
                          end
 
                          if (@StayEndDate=@PostDate+1)
                          begin
                            SET @VatByPacketValueProduct4 = @VatByPacketValueProduct4 + @TempVatByPacketValueProduct
                            SET @PackagePriceProduct4 =  @PackagePriceProduct4 + @TempPackagePriceProduct
                          end
                        end
                        else
                        begin
                          if @PacketNumber4>0 AND @NumberOfChargedDeparturePackaged = 0
                          begin
                            if @SpecifiedDepartureAddOn4 = 1
                              SET @DummyPriceProduct = @Addon4
                            else
                              SET @DummyPriceProduct = 0
 
                            exec PostPackage -1, @ReferenceNumber, @GuestNumber, @SplitBillNumber4, @StayResultAccountNumber4, 0, 1, 1, @BookedTypeNumber, @UserIDNumber, @PacketNumber4, @ProductNumber4, @NumberOfRooms, @PostDate, @Adults, @Children1, @Children2, @DummyPriceProduct, @FK_TurnoverDepartment, @TotalDiscountValueForPackagesplit, @PackagePriceProduct4 OUTPUT, @VatByPacketValueProduct4 OUTPUT, @ProductWareLinkNumber4, @HotelCountryNumber, @HotelCustomerNumber
                          end
                          else
                          begin
                            SET @PackagePriceProduct4 = 0
                            SET @VatByPacketValueProduct4 = 0
                          end
                        end
                      end
                    end
                  end
                end
              end
            end
          end
        end
	
        SET @ServerDateTime = CURRENT_TIMESTAMP

        SET @TransactionDatetime = Convert(DateTime,@PostDateStr+' '+Convert(Char(8),@ServerDateTime,108))
        SET @RealDateTimeForTransaction =  Convert(DateTime,@CurrentDateStr+' '+Convert(Char(8),@ServerDateTime,108))
	
        if (@POSTProduct1=1)
        Begin
          SET @SpecifiedDepartureAddOn = @SpecifiedDepartureAddOn1
          SET @WareNumber = @WareNumber1
          SET @ProductWareLinkNumber = @ProductWareLinkNumber1
          SET @StayBalanceAccountNumber = @StayBalanceAccountNumber1
          SET @StayResultAccountNumber = @StayResultAccountNumber1
          SET @StayVATAccountNumber = @StayVATAccountNumber1
          SET @VatValueProduct = @VatValueProduct1
          SET @VatByPacketValueProduct = @VatByPacketValueProduct1
          SET @CalcPriceDay = @PriceProduct1
          SET @BillTextProductAddon = @BillTextProduct1Addon

          if isnull(@Addon1,0)=0 SET @Addon1=0

          if @BillTextProductAddon = ''
          begin
            SET @CalcPriceDay = @CalcPriceDay + @Addon1
            SET @Addon = 0
          end
          else
          begin
            if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
              SET @Addon = @Addon1 - Round(@Addon1 * ((@AllDiscountRate)/100),2)
            else
              SET @Addon =  @Addon1

            SET @AddonWareText = @BillTextProductAddon
          end

          SET @BillTextProductDepartureAddon = @BillTextProduct1DepartureAddon

          if isnull(@DepartureAddon1,0)=0 SET @DepartureAddon1=0

          if @BillTextProductDepartureAddon = ''
          begin
            SET @CalcPriceDay = @CalcPriceDay  + @DepartureAddon1
            SET @DepartureAddon = 0
          end
          else
          begin
            if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
              SET @DepartureAddon = @DepartureAddon1 - Round(@DepartureAddon1 * ((@AllDiscountRate)/100),2)

            else
              SET @DepartureAddon = @DepartureAddon1
	
            SET @DepartureAddonWareText = @BillTextProductDepartureAddon
          end
	
          SET @PackageTurnOver = @PackagePriceProduct1
	
          if @DiscountAsNettoPrice=1
            SET @CalcPriceDay = @CalcPriceDay - Round(@CalcPriceDay * ((@AllDiscountRate+@DiscountRate)/100),2)
	 
          SET @Logi = @CalcPriceDay - @PackageTurnOver
          SET @EnviromentFee = @EnviromentFeeProduct1

          SET @EnviromentFeeType = @EnviromentFeeType1
	
          if @BillTextProduct1 = ''
            SET @WareText = @WareText1
          else
            SET @WareText = @BillTextProduct1
	
          if (@DayProduct=0) AND ((@Day2+@Day3+@Day4)>0)
            SET @SplitBillNumber = @SplitBillNumber1
        end
        else
        if (@POSTProduct2=1)
        Begin
          SET @SpecifiedDepartureAddOn = @SpecifiedDepartureAddOn2
          SET @WareNumber = @WareNumber2
          SET @ProductWareLinkNumber = @ProductWareLinkNumber2
          SET @StayBalanceAccountNumber = @StayBalanceAccountNumber2
          SET @StayResultAccountNumber = @StayResultAccountNumber2

          SET @StayVATAccountNumber = @StayVATAccountNumber2
          SET @VatValueProduct = @VatValueProduct2
          SET @VatByPacketValueProduct = @VatByPacketValueProduct2
          SET @CalcPriceDay = @PriceProduct2
          SET @BillTextProductAddon = @BillTextProduct2Addon
	
          if isnull(@Addon2,0)=0 SET @Addon2=0
	
          if @BillTextProductAddon = ''
          begin
            SET @CalcPriceDay = @CalcPriceDay + @Addon2
            SET @Addon = 0
          end
          else
          begin
            if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
              SET @Addon = @Addon2 - Round(@Addon2 * ((@AllDiscountRate)/100),2)
            else
              SET @Addon =  @Addon2
  
            SET @AddonWareText = @BillTextProductAddon
          end

          SET @BillTextProductDepartureAddon = @BillTextProduct2DepartureAddon

          if isnull(@DepartureAddon2,0)=0 SET @DepartureAddon2=0


          if @BillTextProductDepartureAddon = ''
          begin
            SET @CalcPriceDay = @CalcPriceDay  + @DepartureAddon2
            SET @DepartureAddon = 0
          end
          else
          begin
            if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
              SET @DepartureAddon = @DepartureAddon2 - Round(@DepartureAddon2 * ((@AllDiscountRate)/100),2)
            else
              SET @DepartureAddon = @DepartureAddon2


            SET @DepartureAddonWareText = @BillTextProductDepartureAddon
          end

          SET @PackageTurnOver = @PackagePriceProduct2
          SET @EnviromentFee = @EnviromentFeeProduct2
          SET @EnviromentFeeType = @EnviromentFeeType2

          if @DiscountAsNettoPrice=1
            SET @CalcPriceDay = @CalcPriceDay - Round(@CalcPriceDay * ((@AllDiscountRate+@DiscountRate)/100),2)


          SET @Logi = @CalcPriceDay  - @PackageTurnOver

          if @BillTextProduct2 = ''
            SET @WareText = @WareText2
          else

            SET @WareText = @BillTextProduct2

          SET @ProductNumber = @ProductNumber2
          SET @PacketNumber = @PacketNumber2

          if (@DayProduct=0) AND ((@Day2+@Day3+@Day4)>0)
            SET @SplitBillNumber = @SplitBillNumber2
        end
        else
        if (@POSTProduct3=1)
        Begin
          SET @SpecifiedDepartureAddOn = @SpecifiedDepartureAddOn3
          SET @WareNumber = @WareNumber3
          SET @ProductWareLinkNumber = @ProductWareLinkNumber3
          SET @StayBalanceAccountNumber = @StayBalanceAccountNumber3
          SET @StayResultAccountNumber = @StayResultAccountNumber3
          SET @StayVATAccountNumber = @StayVATAccountNumber3
          SET @VatValueProduct = @VatValueProduct3
          SET @VatByPacketValueProduct = @VatByPacketValueProduct3
          SET @CalcPriceDay = @PriceProduct3
          SET @BillTextProductAddon = @BillTextProduct3Addon
	
          if isnull(@Addon3,0)=0 SET @Addon3=0
	
          if @BillTextProductAddon = ''
          begin
            SET @CalcPriceDay = @CalcPriceDay + @Addon3
            SET @Addon = 0
          end
          else
          begin
            if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
              SET @Addon = @Addon3 - Round(@Addon3 * ((@AllDiscountRate)/100),2)
            else
              SET @Addon =  @Addon3

            SET @AddonWareText = @BillTextProductAddon
          end

          SET @BillTextProductDepartureAddon = @BillTextProduct3DepartureAddon

          if isnull(@DepartureAddon3,0)=0 SET @DepartureAddon3=0
	
          if @BillTextProductDepartureAddon = ''
          begin
            SET @CalcPriceDay = @CalcPriceDay  + @DepartureAddon3
            SET @DepartureAddon = 0
          end
          else
          begin
            if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
              SET @DepartureAddon = @DepartureAddon3 - Round(@DepartureAddon3 * ((@AllDiscountRate)/100),2)
            else
              SET @DepartureAddon = @DepartureAddon3

            SET @DepartureAddonWareText = @BillTextProductDepartureAddon
          end

          SET @PackageTurnOver = @PackagePriceProduct3

          if @DiscountAsNettoPrice=1
            SET @CalcPriceDay = @CalcPriceDay - Round(@CalcPriceDay * ((@AllDiscountRate+@DiscountRate)/100),2)

          SET @Logi = @CalcPriceDay - @PackageTurnOver
          SET @EnviromentFee = @EnviromentFeeProduct3
          SET @EnviromentFeeType = @EnviromentFeeType3
          if @BillTextProduct3 = ''
            SET @WareText = @WareText3
          else
            SET @WareText = @BillTextProduct3
	
          SET @ProductNumber = @ProductNumber3
          SET @PacketNumber = @PacketNumber3
	
          if (@DayProduct=0) AND ((@Day2+@Day3+@Day4)>0)
             SET @SplitBillNumber = @SplitBillNumber3
          end
          else
          if (@POSTProduct4=1)
          Begin
            SET @SpecifiedDepartureAddOn = @SpecifiedDepartureAddOn4
            SET @WareNumber = @WareNumber4
            SET @ProductWareLinkNumber = @ProductWareLinkNumber4
            SET @StayBalanceAccountNumber = @StayBalanceAccountNumber4
            SET @StayResultAccountNumber = @StayResultAccountNumber4

            SET @StayVATAccountNumber = @StayVATAccountNumber4
            SET @VatValueProduct = @VatValueProduct4

            SET @VatByPacketValueProduct = @VatByPacketValueProduct4
            SET @CalcPriceDay = @PriceProduct4
            SET @BillTextProductAddon = @BillTextProduct4Addon
	
            if isnull(@Addon4,0)=0 SET @Addon4=0

            if @BillTextProductAddon = ''
            begin
              SET @CalcPriceDay = @CalcPriceDay + @Addon4
              SET @Addon = 0
            end
            else
            begin
              if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
                SET @Addon = @Addon4 - Round(@Addon4 * ((@AllDiscountRate)/100),2)
              else
                SET @Addon =  @Addon4
  
              SET @AddonWareText = @BillTextProductAddon
            end
	  
            SET @BillTextProductDepartureAddon = @BillTextProduct4DepartureAddon
   
            if isnull(@DepartureAddon4,0)=0 SET @DepartureAddon4=0
  
            if @BillTextProductDepartureAddon = ''
            begin
              SET @CalcPriceDay = @CalcPriceDay  + @DepartureAddon4
              SET @DepartureAddon = 0
            end
            else
            begin
              if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
                SET @DepartureAddon = @DepartureAddon4 - Round(@DepartureAddon4 * ((@AllDiscountRate)/100),2)
              else
                SET @DepartureAddon = @DepartureAddon4

              SET @DepartureAddonWareText = @BillTextProductDepartureAddon
            end
 
            SET @PackageTurnOver = @PackagePriceProduct4
 
            if @DiscountAsNettoPrice=1
              SET @CalcPriceDay = @CalcPriceDay - Round(@CalcPriceDay * ((@AllDiscountRate+@DiscountRate)/100),2)
	 
            SET @Logi = @CalcPriceDay - @PackageTurnOver
            SET @EnviromentFee = @EnviromentFeeProduct4
            SET @EnviromentFeeType = @EnviromentFeeType4
	 
            if @BillTextProduct4 = ''

              SET @WareText = @WareText4
            else
              SET @WareText = @BillTextProduct4
	 
            SET @ProductNumber = @ProductNumber4
            SET @PacketNumber = @PacketNumber4
 
            if (@DayProduct=0) AND ((@Day2+@Day3+@Day4)>0)
              SET @SplitBillNumber = @SplitBillNumber4
          end
          else
          begin 
            SET @SpecifiedDepartureAddOn = @SpecifiedDepartureAddOn4
            SET @WareNumber = 0
            SET @ProductWareLinkNumber = 0
            SET @StayBalanceAccountNumber = 0
            SET @StayResultAccountNumber = 0
            SET @StayVATAccountNumber = 0
            SET @VatValueProduct = 0
            SET @VatByPacketValueProduct = 0
            SET @CalcPriceDay = 0
            SET @Addon=0
            SET @CalcPriceDay = 0
            SET @DepartureAddon=0
            SET @CalcPriceDay = 0
            SET @PackageTurnOver = 0
            SET @Logi = 0
            SET @EnviromentFee  = 0
          end
 
          if (@DayProduct=1)
          begin
            if (@IsFixedPriceProduct=1)
              SET @Pieces = @NumberOfRooms
            else
              SET @Pieces = (@Adults+@Children1+@Children2)*@NumberOfRooms
          end
          else
            SET @Pieces = @NumberOfRooms
	
          If IsNull(@VATOfLogi,0)=0 SET @VATOfLogi = 0
	
          SET @PostStay = 1
          SET @FirstPost = 1
	
          if (@ShowPrint=1)
          begin
            print '@DiscountRate'
            print @DiscountRate
            print '@AllDiscountRate'
            print @AllDiscountRate
            print '@AddressType'
            print @AddressType
          end
          -- Discount Rate Slut

          SET @EnviromentFee = Round(@EnviromentFee,0)
          if @CalcPriceDay<0 
          begin  
            SET @Pieces = - @Pieces 
            SET @CalcPriceDay = ABS(Round(@CalcPriceDay,2))
          end
          else 
            SET @CalcPriceDay = Round(@CalcPriceDay,2)

          SET @Logi = Round(@Logi,2)
          SET @DepartureAddon = Round(@DepartureAddon,2)
          SET @Addon = Round(@Addon,2)
	
          While (@PostStay=1)
          begin
            if ((@UseEnvironmentFee = 1) AND (@EnviromentFee>Convert(Money,0))) OR (((@DiscountRate>0) OR (@AllDiscountRate>0)) AND (@DiscountWareNumber>0) AND(@CalcPriceDay<>0)) OR((@StayEndDate<>@PostDate) OR (@StayEndDate=@StayStartDate)) OR ((@Dayproduct=1) AND (@StayEndDate=@PostDate))
            begin
              SET @AddressType = 0
	  
              if (@ShowPrint=1)
              begin
                print 'Findfolionumber when charge'
                print @SplitbillNumber
                print @TableReservationLineNumber
              end
  
              exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @WareNumber, @SplitbillNumber, 1, @FolioNumber OUTPUT, @AddressType OUTPUT, @TableReservationNumber = @TableReservationLineNumber
  
              if (@ShowPrint=1)
              begin
                print '@FolioNumber efter findfolionumber'
                print @FolioNumber
              end
            end
 
            if (@ShowPrint=1)
            begin
              print '@CalcPriceDay'
              print convert(char,@CalcPriceDay)
            end
      
            if (@UseEnvironmentFee=1)
            begin
              if @EnviromentFee>Convert(Money,0) AND @EnviromentFeeWareNumber>0
              Begin
                if @EnvironmentfeePerRoom = 1 AND ((@ProductNumber>0 AND @NameListReservationPerPersonProduct=1) OR ((@ProductNumber=0 OR @ProductNumber is null) AND @NameListReservationPerPersonHotelSetup=1))
                begin
                  if (@ShowPrint=1)
                    print @NameListReservationPerPersonProduct
                  
                  Select @EnviromentTransCount = count(*)  from Transactions WITH (nolock) where WareNumber=@EnviromentFeeWareNumber AND note=Convert(varchar,@VisualRoomNumber) AND UserIDNumber=@UserIDNumber AND (Convert(Integer,  Convert(Float,DateStamp)) = Convert(Integer,@PostDate))
                     
                  if @EnviromentTransCount = 0  
                    SET @ChargeEnviromentFee = 1
                  else
                    SET @ChargeEnviromentFee  = 0
                end 
                else
                  SET @ChargeEnviromentFee = 1
	                 
                if @ChargeEnviromentFee = 1
                begin
                  if (@EnviromentFeeType > 0) and (@PriceOverwritten = 1)  -- %-sats 
                    Set @EnviromentFee = Round((@CalcPriceDay)*(@EnviromentFeeType/100), 2)
                  ELSE
                    SET @EnviromentFee = Round(@EnviromentFee, 2)

                  SET @VatOfEnviromentFee = @EnviromentFee*(1-(1/Convert(Float,((@VATValueEnviromentFee/100)+1))))

                  EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT
	    
                  -- POSTERING AF ENVIROMENTFEE
                  SET @DummyAddressType = 0
                  exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @EnviromentFeeWareNumber, @SplitbillNumber, 1, @FeeFolioNumber OUTPUT, @DummyAddressType OUTPUT, @TableReservationNumber = @TableReservationLineNumber

                  -- Krediter EnviromentFee pris på omsætning (ophold) på resultat excl moms
                  INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                  VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2, @TransactionDatetime, @UserIDNumber, @FeeFolioNumber, @Pieces, (@EnviromentFee - @VatOfEnviromentFee), @HotelCountryNumber, 0, 0, 0, @EnviromentFeeWareNumber, @EnviromentFeeWareText, 0, @EnviromentFeeResultAccountNumber, @VATValueEnviromentFee, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime, NULL/*@ProductWareLinkNumber*/, @GuestNumber, 1, @HotelCustomerNumber)
                  INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2,DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                  VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FeeFolioNumber,@Pieces,  @EnviromentFee,@HotelCountryNumber, 1, 1, 0,@EnviromentFeeWareNumber, @EnviromentFeeWareText, 0, @EnviromentFeeBalanceAccountNumber,@VATValueEnviromentFee,@FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber, 1, @HotelCustomerNumber)
                  INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber, GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                  VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,@Pieces, @VatOfEnviromentFee,@HotelCountryNumber, 0, 0, 0,@EnviromentFeeWareNumber, @EnviromentFeeWareText, 0, @EnviromentFeeVATAccountNumber, @VATValueEnviromentFee,@FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/, @GuestNumber, 1, @HotelCustomerNumber)
                end
              end
            end

            SET @PostIsMade = 0
	
            if @FirstPost = 1
            begin
              Select @ProvisionWareNumber = Ware.WareNumber 
              From Ware WITH (NOLOCK) 
              INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
                AND WareGroups.Payment = 5
                AND ISNULL(WareGroups.MarkAsDeleted, '0') = '0'
              Where Ware.MarkAsDeleted IS NULL 
              AND Ware.Type = 10 -- provision bill on guest. Type ligegyldig da det alene handler om at finde en folio (FindFolioNumber). Det korrekte warenumber findes senere.

			  -- Get Provision AddressType
              Select @GuestType = GuestType 
			  from SplitBillWareGroupXTab WITH (NOLOCK) 
			  where SplitBillNumber = @SplitbillNumber 
			  AND WareGroupNumber in (Select WareGroupNumber From Ware WITH (NOLOCK) where WareNumber=@ProvisionWareNumber)
              IF ISNULL(@GuestType,1) = 1 
                SET @GuestType = 1 -- Safe if not marked - guest pay

              if (@GuestType in (2,4,6,8))
              begin
--                SET @GuestNumber=0
                SET @AddressType = (@GuestType/2)
              end
              else
              begin
                if @GuestType=1
                  SET @AddressType = 1
                else if @GuestType=3
                  SET @AddressType = 2
                else if @GuestType=5
                  SET @AddressType = 3
                else if @GuestType=7
                  SET @AddressType = 4
              end

              SELECT @ProvisionType = Reservationaddress.ProvisionType, @ProvPostOnGuest = RESERVATIONADDRESS.ProvisionPostOnGuest
              FROM ReservationAddress WITH (NOLOCK)
              INNER JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.AddressNumber = ReservationAddress.AddressNumber
                AND ReservationAddressXTab.ReferenceNumber = @ReferenceNumber 
                AND ReservationAddressXTab.GuestNumber IN (@GuestNumber, 0)
              WHERE ReservationAddress.ProvisionType IN (2,3) AND ReservationAddress.AddressType = @AddressType
              
              SET @ProvPostOnGuest = ISNULL(@ProvPostOnGuest, 0)

              exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @ProvisionWareNumber, @SplitbillNumber, 1, @ProvisionFolioNumber OUTPUT, @AddressType OUTPUT, @TableReservationNumber = @TableReservationLineNumber

              if (@ShowPrint=1)
              begin
                print '@ProvisionFolioNumber i Provision postering'
                print @ProvisionFolioNumber
              end

              EXEC GetProvisionWareNumber @ProvisionFolioNumber, @DayProduct, @HotelCountryNumber, @ProvisionType, @BookedTypeNumber, @ProvisionWareNumber OUTPUT, @ProvisionWareText OUTPUT, @ProvisionRate OUTPUT, @PostVAT OUTPUT
              
              if (@ShowPrint=1)
              begin
                PRINT '@ProvisionWareNumber'
                PRINT @ProvisionWareNumber
                PRINT '@ProvisionWareText'
                PRINT @ProvisionWareText
                PRINT '@ProvisionRate'
                PRINT @ProvisionRate
                PRINT '@PostVAT'
                PRINT @PostVAT
              end

              exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @ProvisionWareNumber, @SplitbillNumber, 1, @ProvisionFolioNumber OUTPUT, @AddressType OUTPUT, @TableReservationNumber = @TableReservationLineNumber, @ProvisionPostOnGuest = @ProvPostOnGuest

              SET @TempStr = RTRIM(LTRIM(Str(@ProvisionRate, 5, 2) + ' % ' + @ProvisionWareText))

              Declare AccountProvisionCur Cursor SCROLL Read_Only For
              SELECT
                ReservationAddress.AddressType,
                ReservationAddress.PROVISIONRATE,
                ReservationAddress.CountryNumber,
                ReservationAddressXTab.GuestNumber,
                ReservationAddress.ProvisionPostOnGuest,
                ReservationAddress.ProvisionType
                from ReservationAddress WITH (NOLOCK)  INNER JOIN
                ReservationAddressXTab WITH (NOLOCK) ON
                ReservationAddressXTab.AddressNumber = ReservationAddress.AddressNumber
                WHERE ReservationAddressXTab.ReferenceNumber=@ReferenceNumber and (ReservationAddressXTab.GuestNumber=@GuestNumber OR ReservationAddressXTab.GuestNumber = 0)  AND ReservationAddress.ProvisionType IN (2,3) AND ReservationAddress.AddressType>0
              OPEN AccountProvisionCur
              Fetch Next From AccountProvisionCur
              Into @AccountProvisionAddressType,@AccountProvisionRate, @CountryNumber, @AccountProvisionGuestNumber, @ProvPostOnGuest, @ProvisionType
            end	

            if @ProvisionWareNumber>0 AND @ProvPostOnGuest = 1
            begin
              SELECT @NumOfDecimals = ISNULL(NumberOfDecimals, @NumberOfDecimalsInDeposit) FROM Ware WITH (NOLOCK) WHERE WareNumber = @ProvisionWareNumber 
              IF @NoProvisionOnAddon = 0
              begin
                if @ProvisionOnEnviromentFee = 1
                  SET @ProvisionValue = Round((@EnviromentFee + @CalcPriceDay + @Addon + @DepartureAddon)*(@ProvisionRate/100), @NumOfDecimals)
                else
                  SET @ProvisionValue = Round((@CalcPriceDay + @Addon + @DepartureAddon)*(@ProvisionRate/100), @NumOfDecimals)
              end 
              ELSE
              begin
                if @ProvisionOnEnviromentFee = 1
                  SET @ProvisionValue = Round((@EnviromentFee + @CalcPriceDay)*(@ProvisionRate/100), @NumOfDecimals)
                else
                  SET @ProvisionValue = Round((@CalcPriceDay)*(@ProvisionRate/100), @NumOfDecimals)
              end

              if (@ShowPrint=1)
              begin
                print ' @ProvisionValue/@ProvisionRate'
                print  @ProvisionValue
                print  @ProvisionRate
              end

              IF ISNULL(@ProvisionValue,0) = 0
                SET @ProvisionValue = 0
              if (@ProvisionValue<>0) AND @PostIsMade = 0
              begin
                exec Postering @TransactionDatetime, 1, @PostVAT, 0, @GuestNumber, 0, @UserIDNumber, @ProvisionFolioNumber, 0, 0, 0, 0, @TempStr, 1, @ProvisionValue, @HotelCountryNumber, 0, 0 , 0, 0, @FK_LogiTurnOverDepartment, @ProvisionWareNumber, 0, 0, 0, 0, @VisualRoomNumber, @DummyTransNrShowOnBillOnAdd OUTPUT, @HotelCustomerNumber
                SET @PostIsMade = 1
              end
            end

            if @FirstPost=0
              Fetch FIRST From AccountProvisionCur Into @AccountProvisionAddressType,@AccountProvisionRate,@CountryNumber, @AccountProvisionGuestNumber, @ProvPostOnGuest, @ProvisionType

            While (@@Fetch_Status=0)
            begin
              EXEC FindFolioNumber @ReferenceNumber, @AccountProvisionGuestNumber, @UserIDNumber, -1, -1, 1, @AccountProvisionFolioNumber OUTPUT, @AccountProvisionAddressType OUTPUT, @ProvisionPostOnGuest = @ProvPostOnGuest
              EXEC GetProvisionWareNumber @AccountProvisionFolioNumber, @DayProduct, @HotelCountryNumber, @ProvisionType, @BookedTypeNumber, @AccountProvisionWareNumber OUTPUT, @AccountProvisionWareText OUTPUT, @ProvisionRate OUTPUT, @AccountProvisionPostVAT OUTPUT, @CountryNumber

              if @AccountProvisionWareNumber > 0
              begin
                SELECT @NumOfDecimals = ISNULL(NumberOfDecimals, @NumberOfDecimalsInDeposit) FROM Ware WITH (NOLOCK) WHERE WareNumber = @AccountProvisionWareNumber 
                IF @NoProvisionOnAddon = 0
                begin
                  if @ProvisionOnEnviromentFee = 1
                    SET @ProvisionValue = Round((@EnviromentFee + @CalcPriceDay + @Addon + @DepartureAddon)*(@AccountProvisionRate/100), @NumOfDecimals)
                  else
                    SET @ProvisionValue = Round((@CalcPriceDay + @Addon + @DepartureAddon)*(@AccountProvisionRate/100), @NumOfDecimals)
                end
                ELSE
                begin
                  if @ProvisionOnEnviromentFee = 1
                    SET @ProvisionValue = Round((@EnviromentFee + @CalcPriceDay)*(@AccountProvisionRate/100), @NumOfDecimals)
                  else
                    SET @ProvisionValue = Round((@CalcPriceDay)*(@AccountProvisionRate/100), @NumOfDecimals)
                end

                if (@ShowPrint=1)
                begin
                  print ' @ProvisionValue/@AccountProvisionRate'
                  print  @ProvisionValue
                  print  @AccountProvisionRate
                end
  
                SET @AccountProvisionWareText = RTRIM(LTRIM(Str(@AccountProvisionRate, 5, 2) + ' % ' + @AccountProvisionWareText))
  
                IF ISNULL(@ProvisionValue,0) = 0
                  SET @ProvisionValue = 0
                if (@ProvisionValue<>0) AND @PostIsMade = 0
                begin
                  if (@ShowPrint=1)
                  begin
                    PRINT '@AccountProvisionFolioNumber'
                    PRINT @AccountProvisionFolioNumber
                    PRINT '@ProvPostOnGuest'
                    PRINT @ProvPostOnGuest
                  END  
                  exec Postering @TransactionDatetime,1, @AccountProvisionPostVAT, 0, @GuestNumber, 0, @UserIDNumber, @AccountProvisionFolioNumber, 0, 0, 0, 0, @AccountProvisionWareText, 1, @ProvisionValue, @HotelCountryNumber, 0, 0 , 0, 0, @FK_LogiTurnOverDepartment, @AccountProvisionWareNumber, 0, 0 , 0, 0, @VisualRoomNumber, @DummyTransNrShowOnBillOnAdd OUTPUT, @HotelCustomerNumber--,@ProductWareLinkNumber
                  SET @PostIsMade = 1
                end
              end

              Fetch NEXT From AccountProvisionCur Into @AccountProvisionAddressType,@AccountProvisionRate, @CountryNumber, @AccountProvisionGuestNumber, @ProvPostOnGuest, @ProvisionType
            end

            IF @DayProduct = 1 AND @EnableBudgetPerDepartment = 1
            BEGIN
              IF ISNULL(@FK_ChargeDepartment, 0) > 0
                SET @DayProductDepartment = @FK_ChargeDepartment
              ELSE
                SET @DayProductDepartment = @FK_LogiTurnOverDepartment
            END
            ELSE
              SET @DayProductDepartment = @FK_LogiTurnOverDepartment

            if (@DiscountRate>0) AND (@DiscountWareNumber>0) AND (@DiscountAsNettoPrice=0)  -- postering af rabat
            begin
              if (@ShowPrint=1)
                print 'postering af rabat'

              SELECT @NumOfDecimals = ISNULL(NumberOfDecimals, 2) FROM Ware WITH (NOLOCK) WHERE WareNumber = @DiscountWareNumber 

              if (@NoDiscountOnAddon=1)
                SET @DiscountPrice = Round(@CalcPriceDay * (@DiscountRate/100), @NumOfDecimals)
              else
                SET @DiscountPrice = Round((@CalcPriceDay + @Addon + @DepartureAddon) * (@DiscountRate/100), @NumOfDecimals)
  
              if (@DiscountPrice<>0)
              begin
                SET @TempStr =RTRIM(LTRIM(Str(@DiscountRate, 5, 2) + ' % ' + @DiscountwareText))
                if @GetVATFrom=4 -- VATProduct
                  exec Postering @TransactionDatetime, 1, 1, 0, @GuestNumber, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountPrice, @HotelCountryNumber, 0, 0 , 0, 0, @DayProductDepartment, @DiscountWareNumber, 0, 0 , 0, 0, @VisualRoomNumber, @DummyTransNrShowOnBillOnAdd OUTPUT, @HotelCustomerNumber,-1/*@ProductWareLinkNumber*/, @WareNumber
                else if @ChargeDiscountAsProduct = 0  
                  exec Postering @TransactionDatetime, 1, 1, 0, @GuestNumber, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountPrice, @HotelCountryNumber, 0, 0 , 0, 0, @DayProductDepartment, @DiscountWareNumber, 0, 0 , 0, 0, @VisualRoomNumber, @DummyTransNrShowOnBillOnAdd OUTPUT, @HotelCustomerNumber,-1/*@ProductWareLinkNumber*/, 0--@WareNumber
                else
                  exec Postering @TransactionDatetime, 1, 1, 0, @GuestNumber, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountPrice, @HotelCountryNumber, 0, 0 , 0, 0, @DayProductDepartment, @DiscountWareNumber, 0, 0 , 0, 0, @VisualRoomNumber, @DummyTransNrShowOnBillOnAdd OUTPUT, @HotelCustomerNumber,-1/*@ProductWareLinkNumber*/, @WareNumber
              end
            end

            if (@AllDiscountRate > 0) AND (@DiscountWareNumber>0) AND (@DiscountAsNettoPrice=0)
            begin
              SELECT @NumOfDecimals = ISNULL(NumberOfDecimals, 2) FROM Ware WITH (NOLOCK) WHERE WareNumber = @DiscountWareNumber 
              if (@NoDiscountOnAddon=1) 
                SET @DiscountPrice = Round(@CalcPriceDay * (@AllDiscountRate/100), @NumOfDecimals)
              else
                SET @DiscountPrice = Round((@CalcPriceDay + @Addon + @DepartureAddon)*(@AllDiscountRate/100), @NumOfDecimals)

              if (@DiscountPrice<>0)
              begin
                SET @TempStr = RTRIM( LTRIM(Str(@AllDiscountRate) +' % ' + @DiscountwareText))
                if @GetVATFrom=4 -- VATProduct
                  exec Postering @TransactionDatetime, 1, 1, 0, @GuestNumber, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountPrice, @HotelCountryNumber, 0, 0 , 0, 0, @DayProductDepartment, @DiscountWareNumber, 0, 0 , 0, 0, @VisualRoomNumber, @DummyTransNrShowOnBillOnAdd OUTPUT, @HotelCustomerNumber,/*@ProductWareLinkNumber*/-1, @WareNumber
                else if @ChargeDiscountAsProduct = 0  
                  exec Postering @TransactionDatetime, 1, 1, 0, @GuestNumber, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountPrice, @HotelCountryNumber, 0, 0 , 0, 0, @DayProductDepartment, @DiscountWareNumber, 0, 0 , 0, 0, @VisualRoomNumber, @DummyTransNrShowOnBillOnAdd OUTPUT, @HotelCustomerNumber,/*@ProductWareLinkNumber*/-1, 0--@WareNumber
                else
                  exec Postering @TransactionDatetime, 1, 1, 0, @GuestNumber, 0, @UserIDNumber, @FolioNumber, 0, 0, 0, 0, @TempStr, 1, @DiscountPrice, @HotelCountryNumber, 0, 0 , 0, 0, @DayProductDepartment, @DiscountWareNumber, 0, 0 , 0, 0, @VisualRoomNumber, @DummyTransNrShowOnBillOnAdd OUTPUT, @HotelCustomerNumber,/*@ProductWareLinkNumber*/-1, @WareNumber
              end
            end

            -- POSTERING AF OPHOLD hvis bel°b st°rre end 0
            SET @VATOfLogi = @Logi*(1-(1/Convert(Float,((@VatValueProduct/100)+1))))

            if((((@StayEndDate<>@PostDate)  OR (@StayEndDate=@StayStartDate)) OR ((@Dayproduct=1) AND (@StayEndDate=@PostDate))) AND (((@ForceLogiChargingOfZeroPrice = 0 AND  (@CalcPriceDay<>0 OR @Logi<>0 OR @VatOfLogi<>0)) OR (@ForceLogiChargingOfZeroPrice=1))))
            begin
              if (@ShowPrint=1)
              begin
                print '@UseNameOnLogiTransaction'
                print @UseNameOnLogiTransaction
                print convert(char,@Logi)
              end
                  
              if ((@Dayproduct = 0) AND (@UseNameOnLogiTransaction=1))
              begin
                SET @WareText = LTRIM(RTRIM(@WareText)) + ' ' + LTRIM(DBO.GetTextNameLodgingTransactions(@ReferenceNumber, @GuestNumber))
              end

              SET @WareText = LTRIM(RTRIM(@WareText))
--              SET @VATOfLogi = @Logi*(1-(1/Convert(Float,((@VatValueProduct/100)+1))))

              EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT

              if (@Logi - @VatOfLogi)>=0
              begin
                -- Krediter opholdets pris (Produktpris - Pakkepris) ps oms¦tning (ophold) ps resultat excl moms
                if (@ShowPrint=1)
                begin
                  Print '@WareNumber'
                  Print  @WareNumber
                end
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite , Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FolioNumber,@Pieces, (@Logi - @VatOfLogi),@HotelCountryNumber, 0, 0, 0,@WareNumber,@WareText, 0, @StayResultAccountNumber, @VatValueProduct, @DayProductDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
              end

              else
              begin
                if (@ShowPrint=1)
                begin
                  Print '@WareNumber'
                  Print  @WareNumber
                end
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite , Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FolioNumber,-@Pieces, ABS(@Logi - @VatOfLogi),@HotelCountryNumber, 0, 1, 0,@WareNumber,@WareText, 0, @StayResultAccountNumber, @VatValueProduct, @DayProductDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
              end

              if @Pieces>=0
              begin 
                -- Debiter vare incl moms (opholdets pris) ps balancekonto KUNDENS REGNING!!!
                if (@CalcPriceDay=0 AND @ShowForcedLogiChargingOfZeroPrice = 0) 
                  SET @ShowOnBill = 0
                ELSE
                  SET @ShowOnBill = 1
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FolioNumber,@Pieces,  @CalcPriceDay,@HotelCountryNumber, @ShowOnBill, 1, 0,@WareNumber, @WareText, 0, @StayBalanceAccountNumber, @VatValueProduct, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
              end
              else
              begin
                -- Debiter vare incl moms (opholdets pris) ps balancekonto KUNDENS REGNING!!!
                if @CalcPriceDay=0 
                  SET @ShowOnBill = 0
                ELSE
                  SET @ShowOnBill = 1
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FolioNumber,@Pieces,  @CalcPriceDay,@HotelCountryNumber, @ShowOnBill, 0, 0,@WareNumber, @WareText, 0, @StayBalanceAccountNumber, @VatValueProduct, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
              end

              if @VatOfLogi>=0
              begin
                -- Krediter momsen for opholdet ps balancen (moms)
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FolioNumber,@Pieces, @VatOfLogi,@HotelCountryNumber, 0, 0, 0,@WareNumber,@WareText,0, @StayVATAccountNumber, @VatValueProduct, @DayProductDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
              end
              else
              begin
                -- Krediter momsen for opholdet ps balancen (moms)
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, GuestNumber, OriginalDate,ProductWareLinkNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FolioNumber,-@Pieces, ABS(@VatOfLogi),@HotelCountryNumber, 0, 1, 0,@WareNumber,@WareText,0, @StayVATAccountNumber, @VatValueProduct, @DayProductDepartment, Convert(varchar,@VisualRoomNumber), @GuestNumber, @TransactionDatetime,@ProductWareLinkNumber, 1, @HotelCustomerNumber)
              end
            end

            -- Udspecificering af till¦g, hvis der k¦res med udspecificering
            if @ChargeAddonAsProduct=1 AND @AddonWareNumber>0
            begin
              if @AddonResultAccountNumber<>@StayResultAccountNumber
                SET @AddonResultAccountNumber = @StayResultAccountNumber               
              if @AddonBalanceAccountNumber <> @StayBalanceAccountNumber
                SET @AddonBalanceAccountNumber = @StayBalanceAccountNumber
              if @VatValueAddon <> @VatValueProduct 
                SET @VatValueAddon = @VatValueProduct 
              if @AddonVATAccountNumber <> @StayVATAccountNumber
                SET @AddonVATAccountNumber = @StayVATAccountNumber
            end

            if @Addon<>Convert(Money,0) AND @AddonWareNumber>0
            begin
              EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT

              if @FeeFolioNumber = 0
              begin
                SET @DummyAddressType = 0
                exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @AddonWareNumber, @SplitbillNumber, 1, @FeeFolioNumber OUTPUT, @DummyAddressType OUTPUT, @TableReservationNumber = @TableReservationLineNumber
              end

              if @Addon>0
                SET @AddonPieces = 1
              else
              begin
                SET @AddonPieces = -1
                SET @Addon = - @Addon
              end

              SET @AddonWareText = LTRIM(RTRIM(@AddonWareText))
              SET @VATOfAddon = @Addon*(1-(1/Convert(Float,((@VatValueAddon/100)+1))))

              if @AddonPieces=1
              begin
                -- Krediter tillægets pris på omsætning (ophold) på resultat excl moms
                if (@ShowPrint=1)
                begin
                  Print '@WareNumber'
                  Print  @WareNumber
                  print '@VatValueAddon'
                  print  @VatValueAddon
                end

                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite , Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,@Pieces, (@Addon - @VatOfAddon),@HotelCountryNumber, 0, 0, 0,@AddonWareNumber, Convert(varchar, @AddonWareText) , 0, @AddonResultAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/, @GuestNumber, 1, @HotelCustomerNumber)
                -- Debiter tillæg incl moms på balancekonto KUNDENS REGNING!!!
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber, GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FeeFolioNumber,@Pieces,  @Addon,@HotelCountryNumber, 1, 1, 0,@AddonWareNumber, @AddonWareText, 0, @AddonBalanceAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/, @GuestNumber, 1, @HotelCustomerNumber)
                -- Krediter momsen for tillæg på balancen (moms)
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,@Pieces, @VatOfAddon,@HotelCountryNumber, 0, 0, 0,@AddonWareNumber,@AddonWareText,0, @AddonVATAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber, 1, @HotelCustomerNumber)
              end
              else
              begin
                -- Krediter tillægets pris på omsætning (ophold) på resultat excl moms
                if (@ShowPrint=1)
                begin
                  Print '@WareNumber'
                  Print  @WareNumber
                  print '@VatValueAddon'
                  print  @VatValueAddon
                end

                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite , Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,-@Pieces, (@Addon - @VatOfAddon),@HotelCountryNumber, 0, 1, 0,@AddonWareNumber, Convert(varchar, @AddonWareText) , 0, @AddonResultAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/, @GuestNumber, 1, @HotelCustomerNumber)
                -- Debiter tillæg incl moms på balancekonto KUNDENS REGNING!!!
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber, GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FeeFolioNumber,-@Pieces,  @Addon,@HotelCountryNumber, 1, 0, 0,@AddonWareNumber, @AddonWareText, 0, @AddonBalanceAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/, @GuestNumber, 1, @HotelCustomerNumber)
                -- Krediter momsen for tillæg på balancen (moms)
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,-@Pieces, @VatOfAddon,@HotelCountryNumber, 0, 1, 0,@AddonWareNumber,@AddonWareText,0, @AddonVATAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber, 1, @HotelCustomerNumber)
              end
            end

            if @DepartureAddon<>Convert(Money,0) AND @AddonWareNumber>0 -- afrejsetillµg
            begin
              EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT
  
              if @FeeFolioNumber = 0
              begin
                SET @DummyAddressType = 0
                exec FindFolioNumber @ReferenceNumber, @GuestNumber, @UserIDNumber, @AddonWareNumber, @SplitbillNumber, 1, @FeeFolioNumber OUTPUT, @DummyAddressType OUTPUT, @TableReservationNumber = @TableReservationLineNumber
              end

              if @DepartureAddon>0
                SET @AddonPieces = 1
              else
              begin
                SET @AddonPieces = -1
                SET @DepartureAddon = - @DepartureAddon
              end

              SET @DepartureAddonWareText = LTRIM(RTRIM(@DepartureAddonWareText))
              SET @VATOfAddon = @DepartureAddon*(1-(1/Convert(Float,((@VatValueAddon/100)+1))))

              if @AddonPieces=1
              begin
                -- Krediter tillægets pris på omsætning (ophold) på resultat excl moms
                if (@ShowPrint=1)
                begin
                  Print '@WareNumber'
                  Print  @WareNumber
                  print '@VatValueAddon'
                  print @VatValueAddon
                end

                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite , Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber,ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,@Pieces, (@DepartureAddon - @VatOfAddon),@HotelCountryNumber, 0, 0, 0,@AddonWareNumber, Convert(varchar, @DepartureAddonWareText) , 0, @AddonResultAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber, 1, @HotelCustomerNumber)
                -- Debiter tillæg incl moms på balancekonto KUNDENS REGNING!!!
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber,ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FeeFolioNumber,@Pieces,  @DepartureAddon,@HotelCountryNumber, 1, 1, 0,@AddonWareNumber, @DepartureAddonWareText, 0, @AddonBalanceAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber,1, @HotelCustomerNumber)
                -- Krediter momsen for tillæg på balancen (moms)
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,@Pieces, @VatOfAddon,@HotelCountryNumber, 0, 0, 0,@AddonWareNumber,@DepartureAddonWareText,0, @AddonVATAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber,1, @HotelCustomerNumber)
              end

              else
              begin
                -- Krediter tillægets pris på omsætning (ophold) på resultat excl moms
                if (@ShowPrint=1)
                begin
                  Print '@WareNumber'
                  Print  @WareNumber
                  print '@VatValueAddon'
                  print @VatValueAddon
                end

                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite , Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber,ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,-@Pieces, (@DepartureAddon - @VatOfAddon),@HotelCountryNumber, 0, 1, 0,@AddonWareNumber, Convert(varchar, @DepartureAddonWareText) , 0, @AddonResultAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber, 1, @HotelCustomerNumber)
                -- Debiter till¦g incl moms ps balancekonto KUNDENS REGNING!!!
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber,ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber, @FeeFolioNumber,-@Pieces,  @DepartureAddon,@HotelCountryNumber, 1, 0, 0,@AddonWareNumber, @DepartureAddonWareText, 0, @AddonBalanceAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber,1, @HotelCustomerNumber)
                -- Krediter momsen for till¦g ps balancen (moms)
                INSERT INTO Transactions (GlobalTransactionNumber, OriginalGlobalTransactionNumber, RealDateTimeForTransaction, ProductNumber, PackageNumber, PAXadult, PAXChild1, PAXChild2, DateStamp, UserIDNumber, FolioNumber, Pieces, PriceOverwrite, CurrencyNumber, ShowOnBillFlag, Debit, MovedDeleted, WareNumber, TextOverwrite, Payment, AccountNumber, VATValue, FK_DepartmentNumber, Note, OriginalDate,ProductWareLinkNumber,GuestNumber, ExchangeRateOverwrite, HotelCustomerNumber)
                VALUES(@GlobalTransactionNumber, @GlobalTransactionNumber, @RealDateTimeForTransaction, @ProductNumber, @PacketNumber, @Adults, @Children1, @Children2,@TransactionDatetime,@UserIDNumber,@FeeFolioNumber,-@Pieces, @VatOfAddon,@HotelCountryNumber, 0, 1, 0,@AddonWareNumber,@DepartureAddonWareText,0, @AddonVATAccountNumber, @VatValueAddon, @FK_LogiTurnOverDepartment, Convert(varchar,@VisualRoomNumber), @TransactionDatetime,NULL/*@ProductWareLinkNumber*/,@GuestNumber,1, @HotelCustomerNumber)
              end
            end

            if (@FirstPost = 1)
            begin
              if ((@POSTProduct1=1)and (@POSTProduct2=1))
              Begin
                SET @SpecifiedDepartureAddOn = @SpecifiedDepartureAddOn2
                SET @WareNumber = @WareNumber2
                SET @ProductWareLinkNumber = @ProductWareLinkNumber2
                SET @StayBalanceAccountNumber = @StayBalanceAccountNumber2
                SET @StayResultAccountNumber = @StayResultAccountNumber2
                SET @StayVATAccountNumber = @StayVATAccountNumber2
                SET @VatValueProduct = @VatValueProduct2
                SET @VatByPacketValueProduct = @VatByPacketValueProduct2
                SET @CalcPriceDay = @PriceProduct2
                SET @BillTextProductAddon = @BillTextProduct2Addon

                if isnull(@Addon2,0)=0 

                  SET @Addon2=0
                if @BillTextProductAddon = ''
                begin
                  SET @CalcPriceDay = @CalcPriceDay + @Addon2
                  SET @Addon = 0
                end
                else
                begin
                  if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
                    SET @Addon = @Addon2 - Round(@Addon2 * ((@AllDiscountRate)/100),2)
                  else
                    SET @Addon =  @Addon2

                  SET @AddonWareText = @BillTextProductAddon
                end

                SET @BillTextProductDepartureAddon = @BillTextProduct2DepartureAddon
 
                if isnull(@DepartureAddon2,0)=0 SET @DepartureAddon2=0

                if @BillTextProductDepartureAddon = ''
                begin
                  SET @CalcPriceDay = @CalcPriceDay  + @DepartureAddon2
                  SET @DepartureAddon = 0
                end
                else
                begin
                  if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
                    SET @DepartureAddon = @DepartureAddon2 - Round(@DepartureAddon2 * ((@AllDiscountRate)/100),2)
                  else
                    SET @DepartureAddon = @DepartureAddon2

                  SET @DepartureAddonWareText = @BillTextProductDepartureAddon
                end

                SET @PackageTurnOver = @PackagePriceProduct2
  
                if @DiscountAsNettoPrice=1
                  SET @CalcPriceDay = @CalcPriceDay - Round(@CalcPriceDay * ((@AllDiscountRate+@DiscountRate)/100),2)
  
                SET @Logi = @CalcPriceDay  - @PackageTurnOver
                SET @EnviromentFee  = @EnviromentFeeProduct2

                if @BillTextProduct2 = ''
                  SET @WareText = @WareText2
                else
                  SET @WareText = @BillTextProduct2

                SET @ProductNumber = @ProductNumber2
                SET @PacketNumber = @PacketNumber2

                if (@DayProduct=0) AND ((@Day2+@Day3+@Day4)>0)
                  SET @SplitBillNumber = @SplitBillNumber2
              end
              else if ((@POSTProduct2=1) and (@POSTProduct3=1))
              Begin
                SET @SpecifiedDepartureAddOn = @SpecifiedDepartureAddOn3
                SET @WareNumber = @WareNumber3
                SET @ProductWareLinkNumber = @ProductWareLinkNumber3
                SET @StayBalanceAccountNumber = @StayBalanceAccountNumber3
                SET @StayResultAccountNumber = @StayResultAccountNumber3
                SET @StayVATAccountNumber = @StayVATAccountNumber3
                SET @VatValueProduct = @VatValueProduct3
                SET @VatByPacketValueProduct = @VatByPacketValueProduct3
                SET @CalcPriceDay = @PriceProduct3
                SET @BillTextProductAddon = @BillTextProduct3Addon
  
                if isnull(@Addon3,0)=0 SET @Addon3=0

                if @BillTextProductAddon = ''
                begin
                  SET @CalcPriceDay = @CalcPriceDay + @Addon3
                  SET @Addon = 0
                end
                else
                begin
                  if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
                    SET @Addon = @Addon3 - Round(@Addon3 * ((@AllDiscountRate)/100),2)
                  else
                    SET @Addon =  @Addon3

                  SET @AddonWareText = @BillTextProductAddon
                end

                SET @BillTextProductDepartureAddon = @BillTextProduct3DepartureAddon
  
                if isnull(@DepartureAddon3,0)=0 SET @DepartureAddon3=0
    
                if @BillTextProductDepartureAddon = ''
                begin
                  SET @CalcPriceDay = @CalcPriceDay  + @DepartureAddon3
                  SET @DepartureAddon = 0
                end
                else
                begin
                  if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
                    SET @DepartureAddon = @DepartureAddon3 - Round(@DepartureAddon3 * ((@AllDiscountRate)/100),2)
                  else
                    SET @DepartureAddon = @DepartureAddon3

                  SET @DepartureAddonWareText = @BillTextProductDepartureAddon
                end
	
                SET @PackageTurnOver = @PackagePriceProduct3
   
                if @DiscountAsNettoPrice=1
                  SET @CalcPriceDay = @CalcPriceDay - Round(@CalcPriceDay * ((@AllDiscountRate+@DiscountRate)/100),2)
  
                SET @Logi = @CalcPriceDay  - @PackageTurnOver
                SET @EnviromentFee  = @EnviromentFeeProduct3
  
                if @BillTextProduct3 = ''
                  SET @WareText = @WareText3
                else
                  SET @WareText = @BillTextProduct3


                SET @ProductNumber = @ProductNumber3
                SET @PacketNumber = @PacketNumber3

                if (@DayProduct=0) AND ((@Day2+@Day3+@Day4)>0)
                  SET @SplitBillNumber = @SplitBillNumber3
              end
              else if ((@POSTProduct3=1) and (@POSTProduct4=1))
              Begin
                SET @SpecifiedDepartureAddOn = @SpecifiedDepartureAddOn4
                SET @WareNumber = @WareNumber4

                SET @ProductWareLinkNumber = @ProductWareLinkNumber4
                SET @StayBalanceAccountNumber = @StayBalanceAccountNumber4
                SET @StayResultAccountNumber = @StayResultAccountNumber4
                SET @StayVATAccountNumber = @StayVATAccountNumber4
                SET @VatValueProduct = @VatValueProduct4
                SET @VatByPacketValueProduct = @VatByPacketValueProduct4
                SET @CalcPriceDay = @PriceProduct4
                SET @BillTextProductAddon = @BillTextProduct4Addon

                if isnull(@Addon4,0)=0 SET @Addon4=0

                if @BillTextProductAddon = ''
                begin
                  SET @CalcPriceDay = @CalcPriceDay + @Addon4
                  SET @Addon = 0
                end
                else
                begin
                  if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
                    SET @Addon = @Addon4 - Round(@Addon4 * ((@AllDiscountRate)/100),2)
                  else
                    SET @Addon =  @Addon4

                  SET @AddonWareText = @BillTextProductAddon
                end

                SET @BillTextProductDepartureAddon = @BillTextProduct4DepartureAddon

                if isnull(@DepartureAddon4,0)=0 SET @DepartureAddon4=0
 
                if @BillTextProductDepartureAddon = ''
                begin
                  SET @CalcPriceDay = @CalcPriceDay  + @DepartureAddon4
                  SET @DepartureAddon = 0
                end
                else
                begin
                  if (@NoDiscountOnAddon=0) AND (@DiscountAsNettoPrice=1)
                    SET @DepartureAddon = @DepartureAddon4 - Round(@DepartureAddon4 * ((@AllDiscountRate)/100),2)
                  else
                    SET @DepartureAddon = @DepartureAddon4

                  SET @DepartureAddonWareText = @BillTextProductDepartureAddon
                end

                SET @PackageTurnOver = @PackagePriceProduct4

                if @DiscountAsNettoPrice=1
                  SET @CalcPriceDay = @CalcPriceDay - Round(@CalcPriceDay * ((@AllDiscountRate+@DiscountRate)/100),2)
 
                 SET @Logi = @CalcPriceDay  - @PackageTurnOver
                 SET @EnviromentFee  = @EnviromentFeeProduct4

                 if @BillTextProduct4 = ''
                   SET @WareText = @WareText4
                 else
                   SET @WareText = @BillTextProduct4

                 SET @ProductNumber = @ProductNumber4
                 SET @PacketNumber = @PacketNumber4

                 if (@DayProduct=0) AND ((@Day2+@Day3+@Day4)>0)
                   SET @SplitBillNumber = @SplitBillNumber4
                end
                else
                  SET @PostStay = 0
              end
	
              if (@FirstPost=0)
                SET @PostStay = 0
              else
                SET @FirstPost=0
	
              if (@PostStay=0)
              begin
                Close AccountProvisionCur
                Deallocate AccountProvisionCur
              end
            end
          end         

          SET @PostDate = @PostDate + 1
          SET @PostDateStr = Convert (Char (8), @PostDate, 112)
        end
      end
	
      if (@Dayproduct=1)
      begin
        Fetch Next From ResCur
        Into @DepartureTime, @BookedTypeNumber,@RoomNumber,@ArrivalDate,@DepartureDate,@ProductNumber,  
             @NumberOfRooms,@GuestNumber,@SegmentNumber,@PointOfSaleNumber, @SplitBillNumber,
             @PriceOverWritten,@Adults,@Children1, @Children2, @Price,@ReferenceNumber,@PacketNumberReservation, @HotelCustomerNumber, @TableReservationLineNumber, @FK_ChargeDepartment, @ReservationConfLineNumber
      end
      else
      begin
        Fetch Next From ResCur
        Into @BookedTypeNumber,@RoomNumber, @SegmentNumber,@PointOfSaleNumber, @SplitBillNumber,
           @ArrivalDate,@DepartureDate, @PaysAdults, @PaysChildren1, @PaysChildren2, @Adults,@Children1,@Children2,@ProductNumber,
           @NumberOfRooms,@PriceOverwritten,@Price,@FirstPrice1,
           @PriceOverwritten2,@FirstPrice2,@Day2,@ProductNumber2,
           @PriceOverwritten3,@FirstPrice3,@Day3,@ProductNumber3,
           @PriceOverwritten4,@FirstPrice4,@Day4,@ProductNumber4,
           @SidehouseNumber,
           @NameListSetting, @HotelCustomerNumber,
           @SplitBillNumber1, @SplitBillNumber2, @SplitBillNumber3, @SplitBillNumber4
      end
    end

  IF @PostIsMade = 0 AND @ProvisionFolioNumber > 0
  BEGIN
    DECLARE @cnt INT

    SET @AccountProvisionFolioNumber = ISNULL(@AccountProvisionFolioNumber, -1)
    SET @ProvisionFolioNumber = ISNULL(@ProvisionFolioNumber, -1)

    IF @ProvisionFolioNumber > @MaxFolioNumber
    BEGIN
      SELECT @cnt = COUNT(*) FROM Transactions WITH (NOLOCK) WHERE FolioNumber = @ProvisionFolioNumber
      IF ISNULL(@cnt, 0) = 0
      BEGIN
        DELETE FolioCardXTab WHERE FolioNumber = @ProvisionFolioNumber
        DELETE FolioRestResTableChairsXTab WHERE FolioNumber = @ProvisionFolioNumber
        DELETE Folios WHERE FolioNumber = @ProvisionFolioNumber
      END
    END

    IF @AccountProvisionFolioNumber > @MaxFolioNumber
    BEGIN
      SELECT @cnt = COUNT(*) FROM Transactions WITH (NOLOCK) WHERE FolioNumber = @AccountProvisionFolioNumber
      IF ISNULL(@cnt, 0) = 0
      BEGIN
        DELETE FolioCardXTab WHERE FolioNumber = @AccountProvisionFolioNumber
        DELETE FolioRestResTableChairsXTab WHERE FolioNumber = @AccountProvisionFolioNumber
        DELETE Folios WHERE FolioNumber = @AccountProvisionFolioNumber
      END
    END
  END    

  Close ResCur

  Deallocate ResCur

  SET @RepeatsIndex = @RepeatsIndex + 1
end

IF @ChargeCancellationFee = 1
BEGIN
  DECLARE @CancelFeeTotalAmount MONEY
  DECLARE @CancelFeeAmount MONEY

  Select @NumberOfPostRoomPrDay = Count(TransactionNumber) 
  from Transactions (NOLOCK) 
  INNER JOIN PERSONEL (NOLOCK) ON TRANSACTIONS.UserIDNumber = PERSONEL.UserIDNumber
  where (FolioNumber in (Select FolioNumber FROM Folios (NOLOCK) where ReferenceNumber=@ReferenceNumber AND (GuestNumber=0 OR GuestNumber=@GuestNumber)))
  AND ((PERSONEL.UserTypeNumber = 4 AND (MovedDeleted=0)) OR ((MovedDeleted=0 OR (MovedDeleted=1 AND MovedFolioNr>0)) AND (PERSONEL.UserTypeNumber = 3)))
  AND WareNumber in (Select WareNumber FROM Ware (NOLOCK) where ((Ware.MarkAsDeleted is null) AND Ware.SortNumber = 1 AND WareGroupNumber in (Select WareGroupNumber FROM WareGroups (NOLOCK) Where Payment = 4)))
  
  IF @NumberOfPostRoomPrDay = 0
    EXEC DBO.ChargeAndCalcCancellationFee @ReferenceNumber, @GuestNumber, @CancelFeeTotalAmount output, @CancelFeeAmount output, @FK_TurnoverDepartment, @UserIDNumber, @HotelCountryNumber, 0, 0, 0, 1, 0
END

DECLARE @SqlStr VARCHAR(25)
SET @SqlStr = 'SET LOCK_TIMEOUT '+ CONVERT(VARCHAR, @LockTimeOut)
EXEC (@SqlStr)