﻿function currentUrl(url) {
    this.currentUrl = window.location.href;
    if (url) this.currentUrl = url;
    this.params = [];
    this.addUrl(this.currentUrl);
}
currentUrl.prototype.addUrl = function(url) {
    if (url) {
        var query = url.slice(url.indexOf('?') + 1);
        if (query.length > 0) {
            var hash = []; var hashes = query.split('&');
            if (hash.length > 1)
                for (var i = 0; i < hashes.length; ++i) {
                hash = hashes[i].split('='); this.addKeyValue(hash[0], hash[1]);
            }
        }
    }
}
currentUrl.prototype.addKeyValue = function(key, value) { this.params.push(key); this.params[key] = value; }
currentUrl.prototype.getKey = function(keyIndex) { return this.params[keyIndex]; };
currentUrl.prototype.getValue = function(keyIndex) { return this.params[this.params[keyIndex]]; };
currentUrl.prototype.getKeyValue = function(keyIndex) { return this.getKey(keyIndex) + "=" + this.getValue(keyIndex); }
currentUrl.prototype.serializeAndEncode = function() { return encodeURIComponent(this.serialize()); }
currentUrl.prototype.serialize = function() {
    var queryString = "";
    for (var i = 0; i < this.params.length; i++) {
        if (i != 0) queryString += "&";
        queryString += this.getKeyValue(i);
    }
    return queryString;
}

function register(authority) {
    this.authority = authority;
    this.analyticsUrl = "/tracking/analytics.aspx";
    this.sourceTrackUrl = "/tracking/st.aspx";
    this.sourceTypeKey = "ct";
}
register.prototype.getUrl = function(handlerUrl, parameters) {
    return this.authority + handlerUrl + "?" + parameters;
}
register.prototype.r_hit = function(element, url, parameters) {
    var urlParams = new currentUrl(parameters);
    var currentSearch = window.location.toString().slice(window.location.toString().indexOf('?') + 1);
    var hasSearch = currentSearch.length != 0 && currentSearch != window.location.toString();
    if (hasSearch) urlParams.addKeyValue("q", encodeURIComponent(currentSearch));
    if (document.referrer.length != 0) urlParams.addKeyValue("r", encodeURIComponent(document.referrer));
    element.src = this.getUrl(url, urlParams.serialize());
    return this;
}
register.prototype.r_img = function(url, parameters) {
    var img = document.createElement("img");
    img.style.width = "1px"; img.style.height = "1px";
    document.appendChild(img);
    return this.r_hit(img, url, parameters);
}
register.prototype.r_iframe = function(url, parameters) {
    var iframe = document.createElement("iframe");
    iframe.style.display = "none";
    document.forms[0].appendChild(iframe);
    return this.r_hit(iframe, url, parameters);
}

register.prototype.registerAnalytics = function() {
    return this.r_iframe(this.analyticsUrl, "");
}