var URL = Class.create();

URL.prototype = {
	initialize: function(location, clearselected){
		if(!clearselected) clearselected = false;
	
		if(location){
			this.location = location;
		} else {
			this.location = document.location.href;	
		}
		
		if($('selected_items') && !clearselected){
			if($('selected_items').value.length > 1){
				this.replacekey('items', $('selected_items').value, true);
			}
		}
	},
	
	get: function(){
		return this.location;
	},
	
	getkey: function(key){
		if(!this.iskey(key)){
			return false;
		}

		tmp = this.get().split('&');
		
		for(i=0; i<tmp.length+1; i++){
			value = tmp[i].split('=');
		
			if(key == value[0] && this.get().indexOf(key+'='+value[1]) != -1){
				return value[1];
			}
		}
	},
	
	replacekey: function(key, value, add){
		if(!this.iskey(key)){
			if(add){
				this.addkey(key,value);
				return true;
			} else {			
				return false;
			}
		}
		
		tmp = this.get().split('&');
		
		for(i=0; i<tmp.length; i++){
			val = tmp[i].split('=');
		
			if(val[0] == key && this.get().indexOf(key+'='+val[1]) != -1){
				this.location = this.location.replace(key+'='+val[1], key+'='+value);
				return true;
			}
		}		
	},
	
	addkey: function(key, value){
		this.location += '&' + key + '=' + value;
	},
	
	iskey: function(key){
		if(this.get().indexOf(key+'=') == -1){
			return false;
		}
		
		return true;
	},
	
	go: function(){
		document.location.href = this.get();
	},
	
	send: function(){
		
		objects = document.getElementsByTagName('H1');
		errors = document.getElementsByClassName('fieldwitherrors');
		
		if(objects.length == 1 && errors == 0){
			t = objects[0].innerHTML.split('<A');
	
			this.location = replaceall('&', '%', this.get());
			this.location = replaceall('?', '$', this.get());
			new Ajax.Request('/history/add', {method:'post', postBody:'title=' + t[0] + '&url=' + this.get()});
		}
	}
}