/* HitBox download tagging */

// An anonymous function that is executed as soon as it's parsed by the browser
(function() {
    // Purpose: This function will setup javascript files/dependencies if via AJAX
    // Input:  lib_path - This is the path to the js file to include
    //         call_back_fn - This is an optional call back function to be executed after JS file is sourced.
    function get_lib(lib_path, call_back_fn) {		
        if (window.XMLHttpRequest) {              
            AJAX=new XMLHttpRequest();              
        } else {                                  
            AJAX=new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (AJAX) {
            AJAX.open("GET", lib_path, false);                             
            AJAX.send(null);

            
            if (window.execScript) {
                  window.execScript( AJAX.responseText);
            }else{
              var fn = function() {
                window.eval.call( window, AJAX.responseText );
              };
              fn();
            }

            if (call_back_fn){
	          call_back_fn();
            }

        } else {
            return false;
        }                         
    };

	if (typeof(jQuery) == 'undefined'){ 
            get_lib('/assets/js/jquery/jquery-1.2.1.pack.js');
    }

	if (typeof(report_campaign_trax) == 'undefined'){ 
        get_lib('/assets/js/campaign_trax.js', xrx_hbx_dt);
    }
	
	// if both libraries have been sourced already, just execute the function.
	xrx_hbx_dt();
})();

function xrx_hbx_dt(){
	jQuery.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|buy\.xerox\.com|direct\.xerox\.com|xeroxdirect\.com|www\.graphiccommunications-estore\.xerox\.com|\/perl-bin\/exit.pl\?|\/Exit\/|channelintelligence\.com|members\.ppcommunity\.com|blogs\.xerox\.com',
			href_exclude_regex: 'www\.xerox\.com|office\.xerox\.com|opbu\.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);
						report_campaign_trax(hbx_vars, anchor_elem, options); 
						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 {
						jQuery(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');
				jQuery.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 jQuery('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);
		}
	};
};
