/* This script is used to find and select
*  all external links and NCP booking widget buttons 
*  on the page and generate additional page impressions 
*  for Google Analytics tracking [uses jQuery].
*/

/* This function is used to get all external links
   on the page and generate extra tracking impressions
   for Google Analytics.
   Standard exit links are in the format /exit/#outgoing website#/#exit page#/#link text#/
   Advert (MPU, Skyscraper etc) exit links are in the format /exit/advert/#exit page#/click/#outgoing website#/ */
function addExternalLinkTracking() {
    
    // check for all links beginning with 'http' and not referencing the
    // context domain
    $('a[href^="http"]:not([href*="://' + document.domain + '"])').click(function() {

        var trackingLink;
        var linkType = "exit";
        var destinationUrl = urlClean($(this).attr('href'));
        var referringUrl = urlClean(sitecoreUrlClean(document.URL));
        var linkText = $(this).text();
        var image = $(this).children("img:first");

        // check whether the link is around an image -
        // if it is, use the image alt text as the link text
        if (image.length > 0) {
            linkText = image.attr('alt');
        }

        // set the link text to 'no-text' if still empty
        if (linkText.length == 0) {
            linkText = "no-text";
        }

        // check whether the link is within an advert element
        // and call the appropriate tracking function
        if ($(this).parent().hasClass('advert')) {
            linkType = "advert";

            // add click event to the link
            recordExternalAdvertLink(linkType, referringUrl, linkText, $(this).attr('href'), $(this).attr('target'));
            return false;
        }
        else {
            trackingLink = "/" + linkType + "/" + destinationUrl + "/" + referringUrl + "/" + textClean(linkText) + "/";

            // add click event to the link
            pageTracker._trackPageview(trackingLink);
        }
    });
}

/* This method is used to add external link tracking on NCP booking form
   submit buttons. */
function addExternalFormTracking() {
    $("#carParkingWidget input[id$='btnSubmit']").click(function() {

        var trackingLink;
        var linkType = "exit";
        var destinationUrl = urlClean("https://www.ncpairports.co.uk/newbooking/startpage.aspx");
        var referringUrl = urlClean(sitecoreUrlClean(document.URL));
        var linkText = $(this).attr("value");

        trackingLink = "/" + linkType + "/" + destinationUrl + "/" + referringUrl + "/" + textClean(linkText) + "/";

        // add click event to the link
        pageTracker._trackPageview(trackingLink);
    });
}

/* This function is used to record external link clicks from
  within advert elements. It uses Google Analytic's _trackEvent method. */
function recordExternalAdvertLink(linkType, referringUrl, linkText, destinationUrl, target) {
    try {
        var pageTracker = _gat._getTracker("UA-9956351-3");
        pageTracker._trackEvent(linkType, referringUrl, linkText);
        setTimeout('window.open("' + destinationUrl + '","' + target + '");', 100)
    } catch (err) { }
}

/* This function is used to strip out 'http://',
   'https://', 'www.', querystrings, forward slashes
   and .aspx extensions from URLs used in
   Google Analytics external link tracking. */
function urlClean(inputUrl) {

    // remove http:// and https://
    var outputUrl = inputUrl.replace("http://", "").replace("https://", "");

    // remove www.
    if (outputUrl.indexOf("www.") == 0) {
        outputUrl = outputUrl.substring(4, outputUrl.length);
    }

    // remove querystring
    if (outputUrl.indexOf("?") >= 0) {
        outputUrl = outputUrl.substring(0, outputUrl.indexOf("?"));
    }

    // remove anchors
    if (outputUrl.indexOf("#") >= 0) {
        outputUrl = outputUrl.substring(0, outputUrl.indexOf("#"));
    }

    // remove last forward slash
    if (outputUrl.lastIndexOf("/") == outputUrl.length - 1) {
        outputUrl = outputUrl.substring(0, outputUrl.lastIndexOf("/"));
    }

    // remove .aspx extension
    outputUrl = outputUrl.replace(".aspx", "");

    // replace remaining forward slashes with underscores
    outputUrl = outputUrl.replace(/[\/]/g, "_");
    
    return outputUrl;
}

/* This function is used to remove certain pages from Sitecore
   URLs, such as home.aspx and default.aspx to 
   consolidate home page results in Google Analytics. */
function sitecoreUrlClean(inputUrl) {

    // remove index, home and default
    var outputUrl = inputUrl.toLowerCase().replace("home.aspx", "").replace("default.aspx", "");
    
    return outputUrl;
}

/* This function is used to clean any link text
   by removing quotes (double and single) and 
   replacing spaces with hyphens. */
function textClean(inputText) {

    var outputText = inputText.replace(/[\']/g, "")
    .replace(/[‘]/g, "")
    .replace(/[’]/g, "")
    .replace(/[\"]/g, "")
    .replace(/[“]/g, "")
    .replace(/[”]/g, "")
    .replace(/[ ]/g, "-");

    return outputText;
}

$(document).ready(function() {
    addExternalLinkTracking();
    addExternalFormTracking();
});
