#	local_storage.tag - Local Storage Generation tag
#	---------------------
#
#	Copyright (c) 2011 Jure Kodzoman, Informa Studio d.o.o.
#
#	This program is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 2 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public
#	License along with this program; if not, write to the Free
#	Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
#	MA  02111-1307  USA.
#

UserTag local_storage Documentation <<EOD

=head1 NAME

local_storage - Store current field values in local storage

=head1 SYNOPSIS

[local-storage fields="fname lname email"]

=head1 DESCRIPTION

Store field values locally on user's computer. Requires HTML5 enabled browser.

=over 4

=item fields

Whitespace separated list of field names

=item refresh

Time in seconds after which the fields will be stored again (defaults to 5 seconds, which is enough for most).

=back

=head1 EXAMPLES


[local-storage fields="fname lname"] - stores fname and lname locally. When you go away from page and come back they will still be there

=back

=head1 AUTHORS

Jure Kodzoman <jure.kodzoman@informastudio.com>


=cut

EOD

UserTag local_storage Order fields refresh
UserTag local_storage Routine <<EOR
sub {
	my ($fields, $refresh) = @_;
	my $out;

	# defaults
	$fields ||= '';
	$refresh ||= 5;


	if (! $fields){
		::logError("Error calling local_storage.tag. Please define at least one field");
		return;
	}

	my @fieldlist = split(/ /,$fields);

	$refresh = $refresh * 1000; # convert to ms

	$out = '<script type="text/javascript"> retrievedata(); function retrievedata(){ ';

	foreach my $field (@fieldlist) {
	::logError("Field is $field");
		$out .= qq{var $field = localStorage.getItem("$field") || ""; document.querySelector("\#$field").value = $field;\n};
	}
	
	$out .= '} function savedata() {';

	foreach my $field (@fieldlist) {
		$out .= qq{var $field = document.querySelector("\#$field").value; localStorage.setItem('$field', $field);\n};
	}

	$out .= "} var myInterval = setInterval(savedata, $refresh); </script>";

	return $out;
}
EOR

