/***************************************************************
*  Copyright notice
*
*  (c) 2007 Toscanelli Matthias <mt@accessible.ch>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project 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.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script 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.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/

var DynamicLink = new Class({
	
	initialize: function(elements){
		this.anchors = $$(elements).filter('a');
		this.params = new Hash();
		
		this.anchors.each(function(anchor, idx_anchor){
			var href = anchor.getProperty('href');
			if(!href.test(/^.*#[^&\?]*$/)){
				anchor.removeEvents('click');
				anchor.addEvent('click', function(event){this.fireClick(event, href)}.bind(this));
			}
		}, this);
	},
	
	addParams: function(key, value){
		if($type(key)=='string' && $type(value)=='string'){
			this.params.set(key, value);
		}
	},
	
	removeParams: function(key){
		this.params.erase(key);
	},
	
	fireClick: function(event, href){
		(new Event(event)).stop();
		var sep = (href.test(/\?[^\?]*$/) ? '&' : '?');
		var args = '';
		this.params.each(function(value, key, hash){
			if(value){
				var regex = new RegExp(key.escapeRegExp());
				if(href.test(regex)){
					regex = new RegExp(key.escapeRegExp()+"=[^&]*");
					href = str.replace(regex, key+"="+value);
				}else{
					args += sep + key + "=" + value;
				}
				sep = '&';
			}
		}, this);
		window.location = href + args;
	}
});