/* 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.
    // Change History:
    // 1.0 - Created by Lbell
    // 1.1 - Added status/readystate check for safety Lbell
    // 1.2 - Added try/catch for extra safety lbell
    // 1.3 - Changed jQuery pack to min version lbell
    function get_lib(lib_path, call_back_fn) {		
        if (window.XMLHttpRequest) {              
            AJAX=new XMLHttpRequest();              
        } else {                                  
            AJAX=new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (AJAX) {
            try {
                AJAX.open("GET", lib_path, false);  //Synch call                            
                AJAX.send(null);
                
                if ( AJAX.status == 200 && AJAX.readyState == 4) { //Success
                    if (window.execScript) { //IE 
                          window.execScript( AJAX.responseText);
                    }else{
                      var fn = function() { //Everyone else
                        window.eval.call( window, AJAX.responseText );
                      };
                      fn();
                    }

                    if (call_back_fn){
	                  call_back_fn();
                    }

                }else{
                    return false; 
                }
            }
            catch(err)
            {
                return false;
            }

        } else {
            return false;
        }                         
    };

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

	if (typeof(report_campaign_trax) == 'undefined'){ 
        get_lib('/assets/js/campaign_trax.js', xrx_hbx_dt);
    }
})();

(function($){
	var settings = {
		xoglang:    'en_US',
		hbx_ws_url: '/perl-bin/hbx_ws.pl',
		href_regex: '/redirect\.jsp|/product_details\.jsp|/[A-Za-z_0-9\-\.]+\.pdf|\.ppt|\.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|xerox\.tradeups\.com|gulfprint\.xeroxems\.reghq\.com|www\.misco\.it|www\.xtandit\.nl|www\.computacenter\.fr|www\.xerox-store\.fr|www\.ac-xerox\.be|www\.atea\.no|www\.documentworld\.de|www\.gartner\.com|www\.xeroxtienda\.com\.mx|twitter\.com|lojavirtual\.xerox\.com\.br',
		href_exclude_regex: 'www\.xerox\.com|office\.xerox\.com|opbu\.xerox\.com|consulting\.xerox\.com|xerox\.com\/digital-printing\/|javascript\:',
		debug: false
	};
	var methods = {
		init: function(options) {
			if (options.debug) console.log("SETTINGS: "+settings);
			$.extend(settings, options);
			if (settings.debug) console.log("SETTINGS: "+settings);
			var HREF_REGEX    = new RegExp(settings.href_regex,'i');
			var EXCLUDE_REGEX = new RegExp(settings.href_exclude_regex+'|'+location.host,'i');
			if (settings.debug) {
				console.log('regex='+HREF_REGEX.source+' exclude regex='+EXCLUDE_REGEX.source);
				console.log( ( window.xrx_hbx_proxy != null && window.xrx_hbx_proxy.xrxPageView != null ) || ( window._hbPageView != null ) );
			}
			if ( ( window.xrx_hbx_proxy != null && window.xrx_hbx_proxy.xrxPageView != null ) || ( window._hbPageView != null ) ) {
				return $('a').filter(function(index){
					var match =  !(this.href == null || this.href == '') && (HREF_REGEX.test(this.href) || !EXCLUDE_REGEX.test(this.href))
					if (settings.debug) console.log(match+' => '+this.href);
					return match;
				}).bind('click', click_handler);
			}
		},
		track: function () {
			$(this).bind('click', click_handler);
		}
	};
	$.fn.xrx_hbx_dt = function(method) {
		if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else if ( methods[method] ) {
			return this.each(function() {
				return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
			});
		}
	};
	var click_handler = function(e) {
		var anchor_elem = e.target;
		if (settings.debug) console.log('target elem is a '+anchor_elem.tagName);
		while ( anchor_elem.tagName.toLowerCase() != 'a' ) {
			if (settings.debug) console.log('looking at parent elem '+anchor_elem.parentNode.tagName);
			anchor_elem = anchor_elem.parentNode;
		}
		if (settings.debug) console.log('anchor elem is a '+anchor_elem.tagName);
		var ping_hbx = function(hbx_vars) {
			if (settings.debug) console.log('hbx_vars.page='+hbx_vars.page+' hbx_vars.mlc='+hbx_vars.mlc+' hbx_vars.scpagename='+hbx_vars.scpagename);
			if ( hbx_vars.page != null && hbx_vars.mlc != null ) {
				// here we call HitBox with a function from their API
				if ( window.xrx_hbx_proxy != null && window.xrx_hbx_proxy.xrxPageView != null ) {
					var sc_suppress = ( hbx_vars.scpage == '__dont_send__' ) ? true : false;
					xrx_hbx_proxy.xrxPageView(hbx_vars.page, hbx_vars.mlc, hbx_vars.scpage, sc_suppress);
				} else {
					_hbPageView(hbx_vars.page, hbx_vars.mlc);
				}
				report_campaign_trax(hbx_vars, anchor_elem, settings); 
			}
		};
		var error_handler = function(xhr,msg,err) {
			if (settings.debug) console.log('error handler with msg('+msg+') and error('+err+')');
		};
		if (settings.debug) console.log('making AJAX request to url('+settings.hbx_ws_url+'?url='+anchor_elem.href+'&xoglang='+settings.xoglang+')');
		$.ajax({
			url:      settings.hbx_ws_url,
			async:    false,
			type:     'GET',
			dataType: 'jsonp',
			success:  ping_hbx,
			error:    error_handler,
			data:     {
				url:     anchor_elem.href,
				xoglang: settings.xoglang
			}
		});
		return true;
	};
})(jQuery);

