/*
Copyright 2010 Marc Maurice

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 3 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, see <http://www.gnu.org/licenses/>.
*/

// add a generate link to all forms in the page
for (var i=0; i<document.forms.length; i++) {
	var button = document.createElement('div');
	button.setAttribute('style', 'border: solid blue 2px; padding: 1em;');
	button.innerHTML='Fill the form, then<br /><a href="javascript:generateBlet('+i+')">Click here to generate the bookmarklet !</a>';
	document.forms[i].appendChild(button);
}

function generateBlet(idForm)
{
	var f=document.forms[idForm];

	// get absolute action URL
	var action;
	if (typeof(f.action) == 'string') {
		action = f.action;
	} else {
		// bug firefox? quand on a un input id=action
		// we have to use a tmp form
		ftmp=document.createElement('form');
		ftmp.action = f.getAttribute('action');
		action = ftmp.action;
	}

	var html = '<form name="BletForm" method="POST" action="'+action+'">';

	// loop through input elements
	for (var i=0; i<f.elements.length; i++) {
		var input = f.elements[i];
		// ignore input name=submit elements because they mask the form submit method
		if (input.tagName == 'INPUT' && input.name != "submit") {
			html+= '<input type="hidden" name="'+input.name+'" value="'+input.value+'" />';
		}
	}
	
	html+= '</form>';
	
	var blet="javascript:document.body.appendChild(document.createElement('div')).innerHTML='"+html.replace(/'/g,'\\\'')+"';document.forms['BletForm'].submit();";

	var result = document.createElement('div');
	result.setAttribute('style', 'border: solid blue 2px; padding: 1em;');
	result.innerHTML='Drag this <a href="'+encodeURI(blet)+'">generated bookmarklet</a> in your bookmarks and test it !';
	f.appendChild(result);
}

