﻿G4TV.UrlParams = function(qs, keySeparator, valueSeparator) {
    this.qs = '';
	this.paramsKeys = new Array();
	this.paramsValues = new Array();
	this.keySep = typeof(keySeparator) === "undefined" ? "&" : keySeparator;
	this.valSep = typeof(valueSeparator) === "undefined" ? "=" : valueSeparator;


    if (qs === null) {
        qs = location.search.substring(1);
    }
    
    this.qs = qs;

    // Turn "+" back to " "
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split(this.keySep); // parse out name/value pairs separated via &
	            	
    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
	    var pair = args[i].split(this.valSep);
		var name = decodeURIComponent(pair[0]);
        		
		var value = (pair.length==2) ? decodeURIComponent(pair[1]) : name;
        		
        this.paramsKeys.push(name);
		this.paramsValues[name] = value;
	}
};

function getParam(key, default_) {
    if (typeof(this.paramsValues[key]) === 'string') {
	    value = this.paramsValues[key];
	    return (value !== null) ? value : (typeof(default_) != 'undefined' ? default_ : null);
	} else {
	    return typeof(default_) != 'undefined' ? default_ : null;
	}	 
}

function getParamInt(key, default_) {
    return parseInt(this.get(key, default_));
}
	 
function getParamString(prefix) {
    // Use this for # or ? prefixes
    str = (typeof(prefix) !== 'undefined') ? prefix : '';
	   
    for(i=0; i<this.paramsKeys.length; i++) {
        key = this.paramsKeys[i];
        if (key.length > 0) {
            str += key + this.valSep + this.paramsValues[key] + this.keySep;
        }
    }
        
    return str.replace(/&$/,"");
}
	 
function checkParam(key) {
    return (typeof(this.paramsValues[key]) === 'string') ? true : false;
}

function addParam(name, value) {
    this.paramsKeys.push(name);
    this.paramsValues[name] = value;
}

function setParam(name, value) {
    this.paramsValues[name] = value;
}
   
function removeParam(name) {	    
    for(i=0; i<this.paramsKeys.length; i++) {
        key   = this.paramsKeys[i];
        value = this.paramsValues[key];
            
        if (key == name) {
            this.paramsKeys.splice(this.paramsKeys.indexOf(name), 1);
            this.paramsValues.splice(this.paramsValues.indexOf(value), 1);
        }
    }
}
G4TV.UrlParams.prototype.get = getParam;
G4TV.UrlParams.prototype.getInt = getParamInt;
G4TV.UrlParams.prototype.getParamString = getParamString;
G4TV.UrlParams.prototype.check = checkParam;
G4TV.UrlParams.prototype.add = addParam;
G4TV.UrlParams.prototype.set = setParam;
G4TV.UrlParams.prototype.remove = removeParam;
