/**
 * Retreive an URL parameter by key name
 * @param string name
 * @return string
 */
jQuery.urlParam = function(name) {
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (! results) { 
		return 0;
	}

	return results[1] || 0;
}

/**
 * PromoCode Pass-Through Script
 *
 * The purpose of this script is to pass the 'PromoCode' value
 * between sites. When a user lands on the site with PromoCode
 * defined, this will be saved to a cookie. There onwards, the
 * href attributes for links to 'store.naturalcures.com' will 
 * be rewritten to contain this promo code.
 */
jQuery(document).ready(function() {
	var promoCode = jQuery.urlParam('PromoCode');

	if(promoCode) {
		jQuery.cookie('PromoCode', promoCode);
	}

	if(jQuery.cookie('PromoCode')) {
		var storeRegex = RegExp('store.naturalcures.com');

		jQuery('a, area').each(function() {
			var href = jQuery(this).attr('href');

			if(href != undefined && href != '') {
				if(href.match(storeRegex)) {
					if(href.match(RegExp('\\?'))) {
						jQuery(this).attr('href', href + '&PromoCode=' + jQuery.cookie('PromoCode'));
					} else {
						jQuery(this).attr('href', href + '?PromoCode=' + jQuery.cookie('PromoCode'));
					}
				}
			}
		});
	}
});

