/**
 * Localise Amazon links and widgets for visitors to your page.
 * search for any AMAZON product links and replace with a referral link to the user's local Amazon site
 * The idea is based on work done by Pete Williams, with my modifications to allow it to be used for 
 * widgets as well as links.
 * @author Paul Leader
 * @author Pete Williams
 * @url http://petewilliams.info/blog/2009/07/javascript-amazon-associate-link-localiser/
 */

// these are the Pete Williams's affiliate IDs. They will only be used for localities you do not provide an ID for.
var arrAffiliatesSpares = {
 	'co.uk' : 'pcrev05',
 	'com'	: 'petewill-20',
 	'de'	: 'petewill05-21',
 	'fr'	: 'petewill-21',
 	'ca'	: 'petewill00-20',
 	'jp'	: 'petewill-22'
}


// set your AFFILIATE IDs here. Leave blank any you do not have an account for.
var arrAffiliates = {
	'co.uk' : 'figafo-21',
	'com'	: 'figafo-20',
	'de'	: 'figafo0f-21',
	'fr'	: '',
	'ca'	: 'figafo05-20',
	'jp'	: ''
}

var amazonTld = 'unknown';
var amazonAffiliate = arrAffiliates['com']; // Default to .com
var amazonADS_js;
var amazonASW_js;


/**
 * Set up the variables used to build amazon links later in the page.
 * This needs to be run in the page head as the variables will be used
 * when setting up amazon widgets etc.
*/
function localiseAmazonVars() {
 	if ( typeof google != 'undefined' ) {
		var strCountry = google.loader.ClientLocation.address.country_code;
	} else {
		alert('You need to add the following code to your <head> section:\n<script src="http://www.google.com/jsapi" language="javascript"></script>');
		return;
	} 
	
	// get domain TLD from country code
	switch ( strCountry ) {
		case 'GB':
		case 'IE':
			amazonTld = 'co.uk';
			break;
		case 'AT':
			amazonTld = 'de';
		default:
			// by default, TLD is lowercase of country code. if no associate, then use .com
			amazonTld = ( arrAffiliates[strCountry.toLowerCase()] ? strCountry.toLowerCase() : 'com' );
			break;
	}  
	
	amazonAffiliate = arrAffiliates[ amazonTld ];
	amazonADS_js = '<script type="text/javascript" src="http://www.assoc-amazon.' + amazonTld + '/s/ads.js"></script>';
    amazonASW_js = '<script type="text/javascript" src="http://www.assoc-amazon.' + amazonTld + '/s/asw.js"></script>';
}

/**
 * Identify our location.
 * Run the rewrites at page load.
 */
function amazonSetup() {
    localiseAmazonVars();
    // initialise on page LOAD
    if (window.addEventListener){
        window.addEventListener('load',checkAmazonLinks,false); //W3C
    } else{
        window.attachEvent('onload',checkAmazonLinks); //IE
    }  
}

/**
 * Rewrite simple <a> tags linking to products
*/
function checkAmazonLinks() {
	// set required VARIABLES
	var objRegexAsin	= new RegExp( '\/([A-Z0-9]{10})' );

	// get all LINKS
	var arrLinks = document.getElementsByTagName( 'a' );

	// get appropriate aFFILIATE ID
	strAffiliateId = ( arrAffiliates[amazonTld] ? arrAffiliates[amazonTld] : arrAffiliatesSpares[amazonTld] );

	// LOOP through
	for ( i=0; i<arrLinks.length; i++ ) {

		// is it an AMAZON link
		var intIndex = arrLinks[i].href.toLowerCase().indexOf( 'amazon.' );

		if ( intIndex > 0) {

			// find ASIN
			var arrResults = objRegexAsin.exec( arrLinks[i].href );

			if ( arrResults ) {
				// REPLACE URI
				var strAsin = arrResults[1];
				arrLinks[i].href  = 'http://www.amazon.' + amazonTld + '/exec/obidos/ASIN/' + strAsin + '/' + strAffiliateId;
			}


		}
	}
}



function checkAmazonEmbeds() {
	// set required VARIABLES
	//http://rcm.amazon.com/e/cm?lt1=_blank&amp;bc1=000000&amp;IS2=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=wififo08-20&amp;o=1&amp;p=8&amp;l=as1&amp;m=amazon&amp;f=ifr&amp;md=10FE9736YVPPT7A0FBG2&amp;asins=B001KX504C
    var objRegexAf	= new RegExp( '&t=([a-zA-Z0-9\-]+)&' );
    var objRegexAmTLD  = new RegExp( '\.amazon\.(.+)\/');

	// get all iFrames
	var arrLinks = document.getElementsByTagName( 'iframe' );

	// get appropriate aFFILIATE ID
	strAffiliateId = ( arrAffiliates[amazonTld] ? arrAffiliates[amazonTld] : arrAffiliatesSpares[amazonTld] );

	// LOOP through
	for ( i=0; i<arrLinks.length; i++ ) {
        var url = arrLinks[i].src.toLowerCase();
		// is it an AMAZON link
		var intIndex = url.indexOf( 'amazon.' );

		if ( intIndex > 0) {

			// find the affiliate.
			var affResults = objRegexAf.exec( arrLinks[i].src );
			var strAf = affResults[1];
            // Find the CC
			var ccResults = objRegexAmTLD.exec( arrLinks[i].src );
			var strCC = ccResults[1];

			if ( affResults && ccResults ) {
				// REPLACE URI
				url = url.replace(strAf, strAffiliateId);
				url = url.replace( '.' + strCC, '.' + amazonTld + '/e');
			}
			arrLinks[i] = url;
		}
	} 
}
