jQuery(document).ready(function($){

	var cookies = document.cookie;

    if (cookies.indexOf('ap_landing_page') == -1) {
        if (document.referrer.length > 1) document.cookie = "ap_referer="+document.referrer+"; path=/";
        document.cookie = "ap_landing_page="+window.location.href+"; path=/";
        document.cookie = "ap_screen_width="+$(window).width()+"; path=/";
    }
    
    document.cookie = "ap_lastpage="+document.location.href+"; path=/";
	

    $("body").on("click", "a", function(e){
       
		if (!this.href.match(/^http/) || (this.hostname == window.location.hostname)) return true;
		
		var all_networks_regexp = new RegExp(affiliatePower.all_networks_regexp);
		
		if (!this.href.match(all_networks_regexp)) return true;
		
		e.preventDefault();
		
		var source_url = window.location.href;
		var target_url = jQuery(this).attr('href');
		
		var testmode;
		if (source_url.indexOf('ap_testmode') > -1) testmode = true;
		else testmode = false;
		
		if (!testmode && (e.target.hasAttribute("target") || this.hasAttribute("target"))) var new_window = window.open('about:blank', '_blank');
		
		var data = { action: 'ap_save_clickout', source_url: source_url, target_url: target_url};
		jQuery.post(affiliatePower.ajaxurl, data, function(response) {
			var arr_response = response.split('~');
			if (arr_response[1]) {
				target_url = arr_response[1];
			}
			
			if (testmode) {
			    var result;
			    if (target_url.match(/10[0-9]{5}/)) result = 'Looks good!';
			    else result = 'Looks bad! No Clickout Id found!';
			    alert(result + ' Target URL: '+ target_url);
			    return; //don't actually forward to target_url
			}
			
			if (new_window) new_window.location.href = target_url;
			else document.location.href = target_url;
		});	
	});
});