/* HitBox download tagging */
(function($){
	$.fn.xrx_hbx_dt = function(options) {
		options = jQuery.extend({
			xoglang:    'en_US',
			hbx_delay:  100,
			hbx_ws_url: '/perl-bin/hbx_ws.pl',
			href_regex: '/redirect\.jsp|/product_details\.jsp|/[A-Za-z_0-9\-]+\.pdf|\.doc|\.swf|\.flv|\.zip|\.mp3|\.wmv|www\.gisx\.com|www\.xdss\.com|www\.direct\.xerox\.com|www\.graphiccommunications-estore\.xerox\.com|\/perl-bin\/exit.pl\?|\/Exit\/|channelintelligence\.com|euro_contactme\.pl|members\.ppcommunity\.com|blogs\.xerox\.com',
			href_exclude_regex: 'www\.xerox\.com|consulting\.xerox\.com|xerox\.com\/digital-printing|javascript\:',
			debug: false
		}, options);
		var HREF_REGEX    = new RegExp(options.href_regex,'i');
		var EXCLUDE_REGEX = new RegExp(options.href_exclude_regex+'|'+location.host,'i');
		if (options.debug) {
			console.log('regex='+HREF_REGEX.source+' exclude regex='+EXCLUDE_REGEX.source);
			console.log(window._hbPageView!=null);
		}
		if ( window._hbPageView != null ) {
			var click_handler = function(e) {
				e.returnValue = false;
				var anchor_elem = e.target;
				if (options.debug) console.log('target elem is a '+anchor_elem.tagName);
				while ( anchor_elem.tagName.toLowerCase() != 'a' ) {
					anchor_elem = anchor_elem.parentNode;
				}
				if (options.debug) console.log('anchor elem is a '+anchor_elem.tagName);
				var ping_hbx = function(hbx_vars) {
					if (options.debug) console.log('hbx_vars.page='+hbx_vars.page+' hbx_vars.mlc='+hbx_vars.mlc);
					if ( hbx_vars.page != null && hbx_vars.mlc != null ) {
						// here we call HitBox with a function from their API
						_hbPageView(hbx_vars.page, hbx_vars.mlc);
						if (options.debug) console.log('setTimeout for ('+options.hbx_delay+') ms');
						// seems we need to wait a little while for _hbPageView to complete
						setTimeout(continue_request, options.hbx_delay);
					} else {
						continue_request();
					}
				};
				var continue_request = function() {
					var target = anchor_elem.target;
					if (options.debug) {
						console.log('would go to '+anchor_elem.href+' with target '+target+' '+target.length);
					} else {
						$(anchor_elem).unbind('click', click_handler);
						if ( target != null && target.length > 0 ) {
							window.open(anchor_elem.href, target);
						} else {
							window.location = anchor_elem.href;
						}
					} 
				};
				if (options.debug) console.log('making AJAX request');
				$.ajax({
					url:      options.hbx_ws_url,
					async:    false,
					dataType: 'json',
					success:  ping_hbx,
					error:    continue_request,
					data:     {
						url:     anchor_elem.href,
						xoglang: options.xoglang
					}
				});
				return false;
			};

			return $('a').filter(function(index){
				var match =  !(this.href == null || this.href == '') && (HREF_REGEX.test(this.href) || !EXCLUDE_REGEX.test(this.href))
				if (options.debug) console.log(match+' => '+this.href);
				return match;
			}).bind('click', click_handler);
		}
	};
})(jQuery);


