--
-- timespan__copy/1
--
create or replace function timespan__copy(
  integer
) returns int4 as $$
	-- timespans.timespan_id%TYPE
declare
       copy__timespan_id	alias for $1;
begin

       return timespan__copy(
		    copy__timespan_id,
		    interval '0 days'
		    );

end;$$ language plpgsql;


--
-- timespan__copy/2
--
create or replace function timespan__copy(
  integer,
  integer
) returns int4 as $$
	-- timespans.timespan_id%TYPE
declare
       copy__timespan_id	alias for $1;
       copy__offset		alias for $2;
begin

       return timespan__copy(
		    copy__timespan_id,
		    to_interval(copy__offset,'days')
		    );

end;$$ language plpgsql;


--
-- timespan__copy/2
--
create or replace function timespan__copy(
  integer,
  interval
) returns int4 as $$
	-- timespans.timespan_id%TYPE
declare
       copy__timespan_id	alias for $1;
       copy__offset		alias for $2; --  default 0
       rec_timespan		record;
       v_interval_id		timespans.interval_id%TYPE;
       v_timespan_id		timespans.timespan_id%TYPE;
begin
       v_timespan_id := null;

       -- Loop over each interval in timespan, creating a new copy
       for rec_timespan in 
            select * 
            from timespans
            where timespan_id = copy__timespan_id
       loop
            v_interval_id := time_interval__copy(
				rec_timespan.interval_id, 
				copy__offset
				);

            if v_timespan_id is null 
	    then
	         -- JS: NOTE DEFAULT BEHAVIOR OF timespan__new
                v_timespan_id := timespan__new(v_interval_id);
            else
	        -- no copy, use whatever is generated by time_interval__copy
                PERFORM timespan__join_interval(
				v_timespan_id, 
				v_interval_id,
				false);
            end if;

       end loop;

       return v_timespan_id;

end;$$ language plpgsql;