/**
* by eskim :)
* Requires Prototype.js 1.5 or higher
*/
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/gi, "");
}
String.prototype.replaceAll = function(str1, str2) {
	var temp_str = "";

	if (this.trim() != "" && str1 != str2) {
		temp_str = this.trim();

		while (temp_str.indexOf(str1) > -1) {
			temp_str = temp_str.replace(str1, str2);
		}
	}

	return temp_str;
}

var UrlComposer = Class.create();
UrlComposer.prototype = {
    
    initialize : function(){
        this.current_url = window.location.href;

        // if parameters exists
        if(this.current_url.split('?').length > 1){
            this.current_query_params = this.current_url.split('?')[1].toQueryParams();		
        }else{
            this.current_query_params = {};
        }
            
        this.frozen_query_params = [];
    },
    
    makeAndGo : function(paramsToMerge, baseUrl, beforeInit, freezingParams){
       var tmp=this.make(paramsToMerge, baseUrl, beforeInit, freezingParams)
       window.location.href = tmp.replaceAll("\%2B", " ");
    },
    
    make : function(paramsToMerge, baseUrl, beforeInit, freezingParams){
        params_copy = $H(this.current_query_params);
        
        if(beforeInit){
           params_copy = $H({});
            
           if(freezingParams){
               freezingParams.each( function(key){
                   params_copy[key] = this.current_query_params[key];
               }.bind(this) );
           }
            
        }

        var newQS = params_copy.merge(paramsToMerge).toQueryString();
       
        var ret = "?"+newQS;
        
        if(baseUrl){
          return baseUrl + ret;
        }
        
        return ret;
    }
    
}	


var urlComposer = new UrlComposer();


// global
function pageLink(page){
    urlComposer.makeAndGo({page:page});
}
function pageLink2(page){
    urlComposer.makeAndGo({page2:page});
}

function changeParam(prop, newval){
    var h = {};
    h[prop] = newval;
    changeParams(h);
}
function changeParams(h){
    urlComposer.makeAndGo(h);
}


