///////////////////////////////////////////////////////////////////////////
//  Copyright (C) Wizardry and Steamworks 2011 - License: GNU GPLv3      //
//  Please see: http://www.gnu.org/licenses/gpl.html for legal details,  //
//  rights of fair usage, the disclaimer and warranty conditions.        //
///////////////////////////////////////////////////////////////////////////
 
integer found = FALSE;
 
default
{
    state_entry() {
        if(llGetObjectDesc() == llGetRegionName()) found = TRUE; 
        if(found == TRUE) return;
        integer flags = llGetParcelFlags(llGetPos());
        if(flags & PARCEL_FLAG_ALLOW_CREATE_OBJECTS && flags & PARCEL_FLAG_ALLOW_SCRIPTS)
            state search; 
    }
    touch_start(integer num) {
        state off;
    }
    changed(integer change) {
        if (change & CHANGED_REGION) {
            found = FALSE;
            llSetObjectDesc(llGetRegionName());
            integer flags = llGetParcelFlags(llGetPos());
            if(flags & PARCEL_FLAG_ALLOW_CREATE_OBJECTS && flags & PARCEL_FLAG_ALLOW_SCRIPTS)
                state search;  
        }
    }
    on_rez(integer num) {
        llResetScript();
    }
}
 
state search
{
    state_entry() {
        integer comChannel = ((integer)("0x"+llGetSubString((string)llGetOwner(),-8,-1)) & 0x3FFFFFFF) ^ 0xBFFFFFFF;
        llListen(comChannel, "Glow", "", "Glow!"+(string)llGetOwner());
        llSensorRepeat("Glow", "", ACTIVE|SCRIPTED, 64, TWO_PI, 1);
        llSetTimerEvent(30);
    }
    touch_start(integer num) {
        state off;
    }
    listen(integer channel, string name, key id, string message) {
        found = TRUE;
    }
    sensor(integer num) {
        do {
            if(llGetOwnerKey(llDetectedKey(num)) == llGetOwner()) found = TRUE;
        } while(~--num);
    }
    no_sensor() {
        integer comChannel = ((integer)("0x"+llGetSubString((string)llGetOwner(),-8,-1)) & 0x3FFFFFFF) ^ 0xBFFFFFFF;
        llRegionSay(comChannel, "Glow?"+(string)llGetOwner());
    }
    timer() {
        llSensorRemove();
        llSetTimerEvent(0);
        if(!found) state rez;
        state default;
    }
    on_rez(integer num) {
        llResetScript();
    }
}
 
state rez {
    state_entry() {
        llOwnerSay("Spawning glow...");
        float x = llFrand(1);
        float y = llFrand(1);
        float z = llFrand(1);
        llRezObject("Glow", llGetPos()+<x,y,z>, ZERO_VECTOR, llEuler2Rot(<0, 90, 0> * DEG_TO_RAD), 0);
        state default;
    }
    touch_start(integer num) {
        state off;
    }
    on_rez(integer num) {
        llResetScript();
    }
}
 
state off {
    state_entry() {
        llOwnerSay("Glow will not rez...");
    }
    touch_start(integer num) {
        llOwnerSay("Glow will now rez...");
        llResetScript();
    }
}