﻿getUrlEncodedKey = function(key, query) {
    if (!query)
        query = window.location.search;
    var re = new RegExp("[?|&]" + key + "=(.*?)&");
    var matches = re.exec(query + "&");
    if (!matches || matches.length < 2)
        return "";
    return decodeURIComponent(matches[1].replace("+", " "));
}

setUrlEncodedKey = function(key, value, query) {

    query = query || window.location.search;
    var q = query + "&";
    var re = new RegExp("[?|&]" + key + "=.*?&");
    if (!re.test(q))
        q += key + "=" + encodeURI(value);
    else
        q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
    q = q.trimStart("&").trimEnd("&");
    return q[0] == "?" ? q : q = "?" + q;
}

getUrlWithAid = function(url, aid) {
    if (url.indexOf('?') > 0) {
        return url.substring(0, url.indexOf("?")) +
            setUrlEncodedKey("aid", aid, url.substring(url.indexOf("?")));
    }
    else {
        return url + '?aid=' + aid;
    }
}

String.prototype.trimEnd = function(c) {
    if (c)
        return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
    return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function(c) {
    if (c)
        return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
    return this.replace(/^\s+/, '');
}
String.prototype.escapeRegExp = function() {
    return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};

$(document).ready(function() {
    var aid = getUrlEncodedKey("aid", null);
    if (aid != "") {
        var url_match = new RegExp();
        url_match.compile("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");

        $("a")
        .each(function() {
            var href = this.href;
            if (href.indexOf("#") != -1) {
                return;
            }

            if (url_match.test(href)) {
                this.href = getUrlWithAid(this.href, aid);
            }
        });

        $("form")
        .each(function(index, value) {
            $(this).append("<input type='hidden' id='aid" + (index + 1) + "' name='aid' value='" + aid + "' />");            
        });
    }
});



