String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}

function genlink()
{
	var aid_el = document.getElementById('aid');
	var pid_el = document.getElementById('pid');
	var sid_el = document.getElementById('sid');
	var resource_el = document.getElementById('resource');
	var link_el = document.getElementById('link');
	var aid = aid_el.value.trim();
	var pid = pid_el.value.trim();
	var sid = sid_el.value.trim();
	var resource = resource_el.value.trim();
	var resource_page = '';
	var resource_code = '';
	var link_code = '<a href="http://www.kqzyfj.com/click-[PID]-[AID]?[SID]url=http://www.hotelchocolat.co.uk/[RESOURCE_PAGE]=[RESOURCE_CODE]" target="_top">Hotel Chocolat</a>';
	var matches = new Array();
	
	//regular expressions
	var prod_regexp = /^http:\/\/www.hotelchocolat.co.uk\/[a-zA-Z0-9-]+-P([0-9]+)\/$/;
	var cat_regexp = /^http:\/\/www.hotelchocolat.co.uk\/[a-zA-Z-]+-C([a-zA-Z0-9_]+)\/$/;
	
	//validate the Advertiser ID
	if(aid.match(/^[0-9]+$/) == null)
	{
		alert('The advertiser ID has not been configured correctly. Please notify a system administrator.');
		return;
	}
	
	//validate the Publisher ID
	if(pid == '')
	{
		alert('Please enter your Publisher ID.');
		pid_el.focus();
		return;
	}
	else if(pid.match(/^[0-9]+$/) == null)
	{
		alert('The publisher ID can only contain numeric digits.\nPlease check that you have entered it correctly.');
		pid_el.focus();
		return;
	}
	
	//validate the Shopper ID
	if(sid.match(/^\w{0,64}$/) == null)
	{
		alert('The shopper ID can only contain letters or digits up to a maximum length of 64 characters.\nPlease check that you have entered it correctly.');
		sid_el.focus();
		return;
	}
	
	if(sid) sid = "SID=" + sid + "&";
	
	//validate the resource URL
	if(resource == '')
	{
		alert('Please paste in a product or category URL.');
		resource_el.focus();
		return;
	}
	
	//identify resource type
	if(matches = prod_regexp.exec(resource)) resource_page = 'product.asp&pf_id';
	else if(matches = cat_regexp.exec(resource)) resource_page = 'category.asp&cat_id';
	else
	{
		alert('The product or category URL that you have provided is not in the correct format\nPlease check that you have copied and pasted it correctly.');
		resource_el.focus();
		return;
	}
	
	//extract resource code
	resource_code = matches[1];
	
	//generate link code
	link_code = link_code.replace('[AID]', aid);
	link_code = link_code.replace('[PID]', pid);
	link_code = link_code.replace('[SID]', sid);
	link_code = link_code.replace('[RESOURCE_PAGE]', resource_page);
	link_code = link_code.replace('[RESOURCE_CODE]', resource_code);
	link_el.value = link_code;
}

function copy_to_clipboard()
{
	var link_el = document.getElementById('link');
	link_el.select();
	range = link_el.createTextRange();
	range.execCommand("Copy");
}
