/*
* Attach appropriate click event handler to links that needs to be tracked
* Requires jQuery
*/

/**
** Function for attaching GA_Tracking that pushes custom Google Analytics Data to selected Anchor elements.
** @param anchors - the group of jquery anchor elements to attach the handlers to provided that its href attriubute matches jqAnchors
** @param linkRegex - the regex/string to be matched
** @param toPush - the data to be pushed to the gaq object. //can be set to null if gaqPush is set
** @param gaqPush - gets called as gaqPush(this). This is used for overriding the default gaqPush action before the redirection to the href.
*/
var GA_Tracking = function (anchors, linkRegex, toPush, gaqPush) {
    $(anchors).each(function (index, a) {
        var attr = $(a).attr('href');

        if (typeof attr !== 'undefined' && attr !== false) {
            if (attr.match(new RegExp(linkRegex))) {
                //console.log(a);
                //attach an eventhandler
                $(a).click(function (e) {
                    //e.preventDefault(); //dont let it redirect
                    (!gaqPush) ? _gaq.push(toPush) : gaqPush(this);
                    //console.log('click tracking sent');
                    //$(this).attr('target') == '_blank' ? window.open($(this).attr('href'), "_blank") : window.location = $(this).attr('href'); //redirect
                });
            }
        }
    });
};

$(document).ready(
	function () {
	    //PDF
	    GA_Tracking(
			$('a'),
			'(.pdf)$',
            null,
			function (a) {
			    var subIndex = $(a).attr('href').lastIndexOf('/');
			    var subS = $(a).attr('href').substring(subIndex+1);
			    _gaq.push(['_trackEvent', 'File Downloads', 'PDF', subS]);
			}
		);

	    //Any link to another domain that contains brighthouse but isn't brighthouse.co.uk
	    GA_Tracking(
			$('a'),
			"(^((http://)?(([A-Za-z0-9-]+[.])?[A-Za-z0-9-]+(brighthouse)[A-Za-z0-9-.:]+))(/)?$)|" +
			"(^((http://)?(([A-Za-z0-9-]+[.])?(?!brighthouse.co.uk)(brighthouse)[A-Za-z0-9-.:]+))(/)?$)|" +
			"(^((http://)?(([A-Za-z0-9-]+[.])?[A-Za-z0-9-]+(?!brighthouse.co.uk)(brighthouse)[A-Za-z0-9-.:]+))(/)?$)",
			null,
            function (a) {
                _gaq.push(['_trackEvent', 'Useful Exit', 'BrightHouse? Properties', $(a).attr('href')]);
            }
		);
	}
);


