/**
* @projectDescription 	Poly9's polyvalent URLParser class
*
* @author	Denis Laprise - denis@poly9.com - http://poly9.com
* @version	0.1
* @namespace	Poly9
*
* Usage: var p = new URLParser('http://user:password@poly9.com/pathname?arguments=1#fragment');
* p.getHost() == 'poly9.com';
* p.getProtocol() == 'http';
* p.getPathname() == '/pathname';
* p.getQuerystring() == 'arguments=1';
* p.getFragment() == 'fragment';
* p.getUsername() == 'user';
* p.getPassword() == 'password';
*
* See the unit test file for more examples.
* URLParser is freely distributable under the terms of an MIT-style license.
*/

/**
 * Creates an URLParser instance
 *
 * @classDescription	Creates an URLParser instance
 * @return {Object}	return an URLParser object
 * @param {String} url	The url to parse
 * @constructor
 * @exception {String}  Throws an exception if the specified url is invalid
 */
URL = function(url) {
 this._fields = {'UserName' : 4, 'Password' : 5, 'Port' : 7, 'Protocol' : 2, 'Host' : 6, 'PathName' : 8, 'URL' : 0, 'QueryString' : 9, 'Fragment' : 10};
 this._values = {};
 this._regex = null;
 this.version = 0.1;
 this._regex = /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/;
 for(var f in this._fields) {
  this['get' + f] = this._makeGetter(f);
  this['set' + f] = this._makeSetter(f);
 }
 if (typeof url != 'undefined')
  this._parse(url);
}

/**
 * @method
 * @param {String} url	The url to parse
 * @exception {String} 	Throws an exception if the specified url is invalid
 */
URL.prototype.setURL = function(url) {
  this._parse(url);
}

URL.prototype._initValues = function() {
   for(var f in this._fields)
   this._values[f] = '';
}

URL.prototype._parse = function(url) {
  this._initValues();
  var r = this._regex.exec(url);
  if (!r) throw "DPURLParser::_parse -> Invalid URL"
  for(var f in this._fields) if (typeof r[this._fields[f]] != 'undefined')
   this._values[f] = r[this._fields[f]];
}

URL.prototype._makeGetter = function(field) {
 return function() {
  return this._values[field];
 }
};


URL.prototype._makeSetter = function(field) {
 return function(value) {
  this._values[field] = value;
 }
}

URL.prototype.toString = function() {
    var port = this.getPort();
    if ((port == '' ) || (port == 80)) {
        port = '';
    } else {
        port = ':' + port;
    }


    var query = this.getQueryString();
    query = query == '' ? '' : ('?' + query);

    var userName = this.getUserName();
    var password = this.getPassword();
    var credentials = '';
    if ((userName != '') && (password != '')) {
        credentials = userName + ':' + password + '@';
    }

    var fragment = this.getFragment();
    fragment = fragment == '' ? '' : '#' + fragment;
    return this.getProtocol() + '://' + credentials + this.getHost() + port + this.getPathName() + query + fragment;
};

URL.prototype.getQueryStringParam = function(key) {
    var value = null;
    try {
        var qStrings = this.getQueryString();
        var nameValuePairs;
        if (qStrings.length > 1) {
            nameValuePairs = qStrings.split('&');
        }

        if (nameValuePairs) {
            for (var i = 0, nVP; nVP = nameValuePairs[i]; i++) {
                var pair = nVP.split('=');
                if (pair[0].toLowerCase() == key.toLowerCase()) {
                    pair.splice(0, 1);
                    value = pair.join('=');
                    break;
                }
            }
        }
    } catch (err) {
        // Do nothing.
    }
    return value;
};

URL.prototype.addQueryStringParam = function(key, value) {
    var queryString = this.getQueryString();
    if (queryString) {
        var current = this.getQueryStringParam(key);
        if (current != null) {
            this._values['QueryString'] = this._values['QueryString'].replace(key + '=' + current, key + '=' + value);
        } else {
            this._values['QueryString'] += '&' + key + '=' + value;
        }
    } else {
        this._values['QueryString'] = key + '=' + value;
    }
};