//Created by Genisys / Guile 5/26/08

/*
This script will give every member every member 50% of each items' value
up-to 600,000 Gold (10 Gold for Plot or Cheap Items), divided by the number
of members!  So if you put in a 200,000 gold piece item the total value will be
100,000 gold DIVIDED BY Each Member, so if there are 4 members, each will get
25,000 Gold for that item.

*/

#include "X0_I0_PARTYWIDE"
#include "nw_i0_plot"
//Put this script OnClose

object oTarget;
object oItem;

int GetIdentifiedGoldPieceValue(object oItem)
{
    // Initial flag
    int bIdentified = GetIdentified(oItem);

    // If not already, set to identfied
    if (!bIdentified) SetIdentified(oItem, TRUE);

    // Get the GP value
    int nGP=GetGoldPieceValue(oItem);

    //Cap the max gold for an item at 200,000 gold.(1/2 the value)
    if(nGP >400000)
    {
    nGP = 400000;
    return nGP;
    }
    else if(nGP<10)
    {
    nGP = 10;
    return nGP;
    }
    else
    { return nGP; }
}

void main()
{

//declare major variables
object oPC = GetLastClosedBy();
oTarget = OBJECT_SELF;
object oItem = GetFirstItemInInventory(oTarget);

     //Not sure if they fixed the error or not (usually it shoudl be -1)
     //This function may return 3 if two players are in the party or
     //it may return 2 if just one player is in the party, needs to be tested
     int nMembers = GetNumberPartyMembers(oPC);

//if not a pc stop
if (!GetIsPC(oPC)) return;

//If the closer is not the person who has the key stop the script!!
if (GetItemPossessedBy(oPC, "barrel")== OBJECT_INVALID) return;

//Note all items which are plot or unidentified might cause an error, lets check.

    while(oItem != OBJECT_INVALID)
    {
    //Lets loop through to get the total cost of all items in the container

    // Get the Identified GP value
    int nGP = GetIdentifiedGoldPieceValue(oItem);
    //Note 15 Gold minimum divide by #of Member (15 Party members max!
    int aValue = nGP+20; //This is done to prevent the divide by 0 error.
    int bValue = aValue/2; //50% of the item's value
    int nValue = bValue;

    //GiveGoldToAll(oPC, nValue);
    GiveGoldToAll(oPC, nValue);

    oItem = GetNextItemInInventory(oTarget);
    }


//Lets destroy all the stuff now.

    oItem = GetFirstItemInInventory(oTarget);
    while(oItem != OBJECT_INVALID)
    {
    if(GetIsObjectValid(oItem))
      {
       DestroyObject(oItem, 0.0f);
      }
     //Loop to make sure we got all items.
     oItem = GetNextItemInInventory(oTarget);

    }

//Let's prevent reopening for 3 seconds, to ensure all contents are gone!
DelayCommand(0.4, SetLocked(OBJECT_SELF, TRUE));
DelayCommand(3.0, SetLocked(OBJECT_SELF, FALSE));
}