function extractSalesCompanyPath() {
    var pathComponents = window.location.pathname.split("/");

    return "/" + pathComponents[1] + "/" + pathComponents[2];
}

function extractSalesCompanyCode() {
    var pathComponents = window.location.pathname.split("/");
    return pathComponents[2].toUpperCase();
}

function fixProductCodeForWebtrends(code) {
    var splittedCode = code.split("_");
    //assume product code is not fixed if it not contains "_" otherwise return just the input
    if (splittedCode.size() == 1) {

        var vpe = "";
        var splitvpe = code.split("-");

        var rootCode = splitvpe[0];

        if (splitvpe.size() > 1) {
            vpe = splitvpe[1];
            var parsedVpe = parseInt(parseFloat(vpe));
            if (parsedVpe == 0 || parsedVpe == 1) {
                vpe = "";
            }
        }

        var rootCodeStripped = parseInt(parseFloat(rootCode));
        var salesCompanyCode = extractSalesCompanyCode();

        var fixedProductCode;
        if (vpe.empty()) {
            fixedProductCode = rootCodeStripped + "_" + salesCompanyCode;
        }
        else {
            fixedProductCode = rootCodeStripped + "-" + vpe + "_" + salesCompanyCode;
        }
        return fixedProductCode;
    }
    else {
        return code;
    }
}

function resetTrackingParams() {

    _tag.DCSext.CartType = "";
    _tag.DCSext.orig_tx_i = "";
    _tag.DCSext.CartType = "";
    _tag.DCSext.Filename = "";
    _tag.DCSext.DownloadType = "";
    _tag.DCSext.Tabname = "";
    _tag.DCSext.Favourite = "";
    _tag.DCSext.FormErrors = "";
    _tag.WT.si_n = "";
    _tag.WT.si_p = "";
    _tag.WT.cg_n = "";
    _tag.WT.cg_s = "";
    _tag.WT.cg_s_3 = "";
    _tag.WT.cg_s_4 = "";
    _tag.WT.cg_s_5 = "";
    _tag.WT.cg_s_6 = "";
    _tag.WT.cg_s_7 = "";
    _tag.WT.oss = "";
    _tag.WT.oss_r = "";
    _tag.WT.tx_u = "";
    _tag.WT.tx_e = "";
    _tag.WT.tx_s = "";
    _tag.WT.pn_sku = "";

}

function trackOrderChunk(txId, txDate, txTime, skus, quantities, prices, entryOriginFlags, origTxId) {
    resetTrackingParams();
    var title = "do_order";
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + title;
    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', title,
            'WT.tx_i', txId,
            'WT.tx_id', txDate,
            'WT.tx_it', txTime,
            'WT.tx_e', 'p',
            'WT.pn_sku', skus,
            'WT.tx_u', quantities,
            'WT.tx_s', prices,
            'DCSext.CartType', entryOriginFlags,
            'DCSext.orig_tx_i', origTxId
            );

}


function trackAddToCart(code, quantity) {
    resetTrackingParams();
    var title = "add_to_cart";
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + title;

    var fixedCode = fixProductCodeForWebtrends(code);

    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', title,
            'WT.tx_e', 'a',
            'WT.pn_sku', fixedCode,
            'WT.si_n', 'shopping',
            'WT.si_p', 'CartAdd',
            'WT.tx_u', quantity);
}

function trackRemoveFromCart(code, quantity) {
    resetTrackingParams();
    var title = "remove_from_cart";
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + title;

    var fixedCode = fixProductCodeForWebtrends(code);

    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', title,
            'WT.tx_e', 'r',
            'WT.pn_sku', fixedCode,
            'WT.tx_u', quantity);

}

function trackProductView(code, quantity) {
    resetTrackingParams();
    var title = "product_view";
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + title;

    var fixedCode = fixProductCodeForWebtrends(code);

    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', _tag.WT.ti,
            'WT.tx_e', 'v',
            'WT.si_n', 'shopping',
            'WT.si_p', 'CartView',
            'WT.pn_sku', fixedCode
            );
}


function trackCartEntryChange(code, oldvalue, newvalue) {


    var diff = newvalue - oldvalue;
    if (diff > 0) {
        trackAddToCart(code, diff);
    }
    else if (diff < 0) {
        trackRemoveFromCart(code, -diff);
    }
}

function trackInternalFileDownload(filename) {
    resetTrackingParams();
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + "download";
    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', _tag.WT.ti,
            'WT.dl', '50',
            'DCSext.Filename', filename,
            'DCSext.DownloadType', 'intern');
}

function trackExternalFileDownload(filename) {
    resetTrackingParams();
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + "download";
    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', _tag.WT.ti,
            'WT.dl', '50',
            'DCSext.Filename', filename,
            'DCSext.DownloadType', 'extern');
}

function trackProductDocumentDownload(location) {
    resetTrackingParams();
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + "download";
    var locationString;
    if ( location == "productGroup" ) { // Productgroup
        locationString = "prodDocFromProductGroup";
    } else if ( location == "orphanedArticle" ) { // Single Article View
        locationString = "prodDocFromSingleArticleView";
    } else {
        locationString = "unknownProdDoc";
    }

    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', _tag.WT.ti,
            'WT.dl', '50',
            'DCSext.DownloadType', locationString);
}

function trackSDSDownload(location) {
    resetTrackingParams();
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + "download";
    var locationString;
    if ( location == "productGroup" ) { // Productgroup
        locationString = "SDSFromProductGroup";
    } else if ( location == "orphanedArticle" ) { // Single Article View
        locationString = "SDSFromSingleArticleView";
    } else if ( location == "boughtArticles" ) { // Bought Articles
        locationString = "SDSFromBoughtArticles";
    } else {
        locationString = "unknownSDS";
    }
    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', _tag.WT.ti,
            'WT.dl', '50',
            'DCSext.DownloadType', locationString);
}

function trackInfocenterDocumentDownload(location) {
    resetTrackingParams();
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + "download";
    var locationString;
    if ( location == "private" ) {
        locationString = "privateViewDocuments";
    } else if ( location == "public" ) {
        locationString = "publicViewDocuments";
    } else {
        locationString = "unknownDocuments";
    }
    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', _tag.WT.ti,
            'WT.dl', '50',
            'DCSext.DownloadType', locationString);
}

function trackAdminReportDownload(report) {
    resetTrackingParams();
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + "download";
    dcsMultiTrack(
            'DCS.dcsuri', dcsuri,
            'WT.ti', _tag.WT.ti,
            'WT.dl', '50',
            'DCSext.DownloadType', report);
}

function trackTabView(tabname) {
    resetTrackingParams();
    dcsMultiTrack('DCS.dcsuri', window.location.pathname,
            'WT.ti', _tag.WT.ti,
            'WT.dl', '52',
            'DCSext.Tabname', tabname);
}


function trackAddToFavorites(code, quantity) {
    resetTrackingParams();
    var title = "favourites";
    var salesCompanyPath = extractSalesCompanyPath();
    var dcsuri = salesCompanyPath + "/" + title;

    var fixedCode = fixProductCodeForWebtrends(code);


    dcsMultiTrack('DCS.dcsuri', dcsuri,
            'WT.ti', _tag.WT.ti,
            'WT.dl', '51',
            'DCSext.Favourite', '1',
            'WT.pn_sku', fixedCode,
            'WT.tx_u', quantity);

}

function cleanStringForWebtrends(input) {
    return input.replace(/\W/g, '_');
}

var errorKeys;
var formId;
var trackedToWebtrends = "";

function checkAndTrackFormError(additionalSuffix, formIdHint) {
    resetTrackingParams();
    if (errorKeys == null) {
        errorKeys = new Array();
    }


    jQuery(".highlightMarker + .highlightInput").each(function(index) {
        var key = cleanStringForWebtrends(this.id);
        var value = cleanStringForWebtrends(jQuery(this).prev().text());

        var keyIndex = jQuery.inArray(key, errorKeys);
        if (keyIndex == -1) {

            if (formIdHint != "") {
                formId = formIdHint;
            }
            else {
                formId = jQuery(this).parents('form:first')[0].id;
            }

            if (formId == null) {
                formId = "undefinedForm";
            }

            errorKeys.push(key.concat(":").concat(value));
        }

    });
    jQuery("#errMsg" + additionalSuffix).each(function(index) {
        var key = cleanStringForWebtrends(this.id);
        var value = cleanStringForWebtrends(jQuery(this).text());

        var keyIndex = jQuery.inArray(key.concat(":").concat(value), errorKeys);
        if (keyIndex == -1) {

            if (formIdHint != "") {
                formId = formIdHint;
            }
            else {
                formId = jQuery(this).parents('form:first')[0].id;
            }

            if (formId == null) {
                formId = "undefinedForm";
            }

            errorKeys.push(key.concat(":").concat(value));

        }
    });
    var webtrendsErrorString = "";
    var stringToAddBase = "";
    for (var i = 0; i < errorKeys.length; i++) {
        var stringToAdd = stringToAddBase.concat(errorKeys[i]);
        if (stringToAddBase == "") {
            stringToAddBase = ";";
        }
        webtrendsErrorString = webtrendsErrorString.concat(stringToAdd);
    }
    if (!webtrendsErrorString.length == 0 && trackedToWebtrends != webtrendsErrorString) {
        console.info("Track to webtrends with formId " + formId + " and errorstring " + webtrendsErrorString);

        var salesCompanyPath = extractSalesCompanyPath();
        var dcsuri = salesCompanyPath + "/" + "Forms";

        dcsMultiTrack('DCS.dcsuri', dcsuri,
                'WT.ti', formId,
                'WT.dl', '54',
                'DCSext.FormErrors', webtrendsErrorString
                );

        errorKeys = null;
        trackedToWebtrends = webtrendsErrorString;
    }
}
