/*jslint strict:true, evil: true, onevar: true, nomen: false  */ /*global $, jQuery, console, hbx, window, ndm, document  */

"use strict";

/*
    Function: jQuery.fn.CG_addTracking
    Simple function to add rel attributes to links for tracking purposes
*/

jQuery.fn.CG_addTracking = function() {
    /* Loop through all links on the page and add a rel attribute if it doesn't have one that tells us where the link has come from */
    var fullURL = document.location.toString(),
        urlPrefix,
        urlFolders,
        linkText,
        linkParent,
        linkParentId,
        relAttr,

    CG_checkSpecChars = function(pText){
        var specChars = ["%20"," ",".",">",",","<","\"","'","CG_"],
            sc=0
            ;
        for(sc=0; sc<specChars.length;sc++){
            pText = pText.split(specChars[sc]).join("");
        }
        return pText;
    },

    CG_checkURLQuery = function(checkDef){
        var urlQuery = document.location.search,
            qryDefs = urlQuery.split("&"),
            qd=0,
            qValPair,
            qVal = ""
        ;

        for(qd=0; qd<qryDefs.length;qd++){
            if(qryDefs[qd].indexOf(checkDef) !== -1){
                qValPair = qryDefs[qd].split("=");
                qVal = qValPair[1];
            }
        }
        return qVal;
    };

    urlFolders = fullURL.split("/");
    //Ignore the first two folders because these are the domain and the last folder
    urlFolders.splice(0,3);
    urlFolders.pop();

    //Rejoin urlFolders with an _
    urlPrefix = [
        urlFolders.join("-"),
        "-"+CG_checkURLQuery("type")
    ].join("");

    $("a").each(function(){
        //If the link doesn't have a rel attribute add one
        if(!$(this).attr("rel")){
            linkText = $(this).text();
            linkParent = $(this).parent();

            while(linkParent.attr("id") === "" && !linkParent.attr("class")){
                linkParent = linkParent.parent();
            }

            if(linkParent.attr("id")!==""){
                linkParentId = linkParent.attr("id");
            }else{
                linkParentId = linkParent.attr("class").split(" ").join("_");
            }

            relAttr = "track-"+CG_checkSpecChars(urlPrefix+"--"+linkParentId+"-"+linkText);
            $(this).attr("rel",relAttr);
        }
    });
};

$(document).CG_addTracking();