function sitestat(ns_l){ns_l=getSiteStatUrl(ns_l);
if(document.images){ns_1=new Image();ns_1.src=ns_l;}else 
document.write('<img src="../new/'+ns_l+'" width="1" height="1" alt="">');} 
function ns_onclick (a, url, name, type, winopt, site){ 
var ns_l="http://uk.sitestat.com/chloride/" + site + "/s?"; 
ns_l+=name;ns_l+='&ns_type='+type+'&ns_action=view'; 
ns_l+='&ns__t='+(new Date()).getTime();if(!url)url=a.href; 
var ns_0=document.referrer;if(ns_0.lastIndexOf('/')==ns_0.length-1) 
ns_0=ns_0.substring(ns_0.lastIndexOf('/'),0); 
if (ns_0.length>0)ns_l+='&ns_referrer='+escape(ns_0); 
winopt=winopt||"";var 
target=(a&&a.target&&a.target!="")?(a.target.substring(0,1)=="_")?a.target.substring(1):a.target:"self";
var ns_i=new 
Image();if(target&&url){if(window[target]){window.ns_softclick_timer=function(target,url) 
{return function(){ns_i.onload=ns_i.onerror=function(){return;}; 
window[((window[target])?target:"self")].location.href=url;}}(target,url); 
window.setTimeout('ns_softclick_timer()',5000);ns_i.onload=ns_i.onerror=window.ns_softclick_timer;}else{ 
window.open(url,target,winopt);}}ns_i.src=ns_l;return false;}
function getSiteStatUrl(ns_l){return ns_l+='&ns__t='+(new 
Date()).getTime();ns_pixelUrl=ns_l; 
ns_0=document.referrer; 
ns_0=(ns_0.lastIndexOf('/')==ns_0.length-
1)?ns_0.substring(ns_0.lastIndexOf('/'),0):ns_0; 
if(ns_0.length>0)ns_l+='&ns_referrer='+escape(ns_0);}
var statUrl="";var site="";var errorCode=0;
var lookup=new Object();
lookup['/es/argentina/']='chloride-argentina';
lookup['/en-au/australia/']='chloride-australia';
lookup['/pt-br/brazil/']='chloride-brazil';
lookup['/zh-cn/china/']='chloride-china';
lookup['/en-gb/corporate/']='chloride-corporate';
lookup['/en-gb/chloride-corporate/']='chloride-corporate';
lookup['/fr/france/']='chloride-france';
lookup['/de/masterguard/']='chloride-germany';
lookup['/it-it/italia/']='chloride-italy';
lookup['/pl-pl/poland/']='chloride-poland';
lookup['/pt-pt/portugal/']='chloride-portugal';
lookup['/en-gb/singapore/']='chloride-singapore';
lookup['/es/spain/']='chloride-spain';
lookup['/en-gb/thailand/']='chloride-thailand';
lookup['/tr-tr/turkey/']='chloride-turkey';
lookup['/en-gb/uae/']='chloride-uae';
lookup['/en-gb/uk/']='chloride-uk';
lookup['/en/usa/']='chloride-usa';
lookup['/en-gb/vietnam/']='chloride-vietnam';
lookup['chloridena.com']='chloride-usa';
lookup['/ru-ru/russia/']='chloride-russia';

function AddStats()
{
    ns_pixelUrl = GetStatUrl();
	sitestat(ns_pixelUrl); 
	AddFormCode();
	AddFileClicks();
}

function GetStatUrl(){return GetStatUrlPageErr(jQuery.url.attr("source"), 0);}
function GetStatUrlErr(error){return GetStatUrlPageErr(jQuery.url.attr("source"), error);}
function GetStatUrlPage(url){return GetStatUrlPageErr(url, 0);}
function GetStatUrlPageErr(url, error)
{
	// Store the error code
	errorCode = error;	
	if (GetUrl('/es/argentina/', url, true)) return statUrl;
	if (GetUrl('/en-au/australia/', url, true)) return statUrl;
	if (GetUrl('/pt-br/brazil/', url, true)) return statUrl;
	if (GetUrl('/zh-cn/china/', url, true)) return statUrl;
	if (GetUrl('/en-gb/corporate/', url, true)) return statUrl;
	if (GetUrl('/en-gb/chloride-corporate/', url, true)) return statUrl;
	if (GetUrl('/fr/france/', url, true)) return statUrl;
	if (GetUrl('/de/masterguard/', url, true)) return statUrl;
	if (GetUrl('/it-it/italia/', url, true)) return statUrl;
	if (GetUrl('/pl-pl/poland/', url, true)) return statUrl;
	if (GetUrl('/pt-pt/portugal/', url, true)) return statUrl;
	if (GetUrl('/en-gb/singapore/', url, true)) return statUrl;
	if (GetUrl('/es/spain/', url, true)) return statUrl;
	if (GetUrl('/en-gb/thailand/', url, true)) return statUrl;
	if (GetUrl('/tr-tr/turkey/', url, true)) return statUrl;
	if (GetUrl('/en-gb/uae/', url, true)) return statUrl;
	if (GetUrl('/en-gb/uk/', url, true)) return statUrl;
	if (GetUrl('/en/usa/', url, true)) return statUrl;
	if (GetUrl('/en-gb/vietnam/', url, true)) return statUrl;
	if (GetUrl('/ru-ru/russia/', url, true)) return statUrl;
	if (GetUrl('chloridena.com', url, false)) return statUrl;

	// Default for any other page
	SetStatUrl("", 'chloride-other', 'page'); return statUrl;
}

function GetUrl(country, url, useDirectory)
{
	jQuery.url.setUrl(url);

	var directory = jQuery.url.attr("directory").toLowerCase();	
	if (useDirectory)
	{
		if (directory.search(country) != -1)
		{
			site = lookup[country];
			directory = directory.replace(country, '');
			SetStatUrl(directory, 'page');
			return true;
		}
	}
	else
	{
		var host = jQuery.url.attr("host");
		if (host != null &&
			host.toLowerCase().search(country) != -1)
		{
			site = lookup[country];
			SetStatUrl(directory, 'page');
			return true;
		}
	}
	site = 'chloride-other';
	return false;
}

function SetStatUrl(directory, page)
{
	// Change the slashes to dots
	directory = FormatDirectory(directory, page);
	statUrl = "http://uk.sitestat.com/chloride/" + 
		site + "/s?" + 
		directory + page;
		
	if (errorCode > 0)
	{
		statUrl = statUrl + '&ns_http_status=' + errorCode;
	}
	statUrl = statUrl + GetSearchResults();		
}

function FormatDirectory(directory, page)
{
	directory = directory.toLowerCase().replace(/\//g,'.');
	if (directory.replace(/\./g, '').length == 0)
	{
		directory = "home";
	}
	// Add a final dot if missing and the page isn't empty
	if (directory.charAt(directory.length - 1) != '.' &&
		page.length > 0)
	{
		directory += '.';
	}
	return directory;
}

function GetSearchResults()
{
	var result='';
	// Find the search box
	if ($('input[@id$=SearchQuery]').length > 0)
	{
		// Get the search phrase
		var phrase = $('input[@id$=SearchQuery]').attr('value');
		if (phrase.length > 0)
		{
			result += '&ns_search_term=' + phrase;
			
			// Attempt to find the search results table
			// (with the dangerous assumption that this will be the only table on the page)
			if ($('table').length > 0)
			{
				result += '&ns_search_result=' + $("td:contains('%')").length;
			}
			else
			{
				result += '&ns_search_result=0';
			}
		}
	}
	// Add the results count
	return result;
}

function AddFileClicks()
{
	// Find all links ending in pdf
	$('a[@href$=pdf]').click( function() { return LogFileClick(this, 'pdf'); } );
	$('a[@href$=PDF]').click( function() { return LogFileClick(this, 'pdf'); } );
	$('a[@href$=xls]').click( function() { return LogFileClick(this, 'xls'); } );
	$('a[@href$=XLS]').click( function() { return LogFileClick(this, 'xls'); } );
}

function LogFileClick(anchor, extension)
{
	// Get the data for calling the stats script
	var counterName = FormatDirectory($(anchor).attr('href'), '');
	// Remove the leading .
	if (counterName.charAt(0) == '.')
	{
		counterName = counterName.replace('.','');
	}
	// Add the onclick and convert spaces to minuses
	counterName = counterName.replace('.','.onclick.').replace(/ /g,'-');
	return ns_onclick(anchor, '', counterName, extension, null, site);
}

function AddFormCode()
{
	/* 
	As the site is ASP.NET, every page has a form.
	There are four input controls on a basic page,
	__EVENTTARGET, __EVENTARGUMENT, __VIEWSTATE and the search box.
	*/
	
	//	If the current page has only 4 inputs, then go no further. 
	if ($('input').length > 4)
	{
		// See if it's the login form
		if (GetFullIdFromEnding('Loginbox_Username').length > 0)
		{
			AddLoginFormCode();
		}
		else if (IsGenericForm())
		{
			AddGenericFormCode();
		}
	}	 
}

function IsGenericForm()
{
	return $('.FormSubmit').length > 0;
}

var ControlNameBase = '_ctl';

function AddGenericFormCode()
{
	// The CMS generates field names dynamically
	// (e.g. ctl00$FullRegion$ctl00$FormControl$_ctl2).
	// The last chunk of the control name seems to increment by two,
	// so we'll loop round until the control is the submit button
	var visibleFields = '';
	var hiddenFields = '';
	var passwordFields = '';

	var control = null;
	
	for (var i = 2; null != (control = GetObjectFromEnding(ControlNameBase + i)); i += 2)
	{
		// If it's the submit button, then stop adding controls
		if (control.length > 0 && control.attr('type').toLowerCase() == 'submit')
		{
			break;
		}
		// Otherwise add the control name to the correct parameter
		switch (control.attr('type').toLowerCase())
		{
			case 'password':
				passwordFields += (passwordFields.length > 0 ? ';' : '') + control.attr('id'); break;
			case 'hidden':
				hiddenFields += (hiddenFields.length > 0 ? ';' : '') + control.attr('id'); break;
			default:
				visibleFields += (visibleFields.length > 0 ? ';' : '') + control.attr('id'); break;
		}
	}
	AddFormFieldsCode(visibleFields, hiddenFields, passwordFields);
}

function AddLoginFormCode()
{
	var visibleFields = 
		GetFullIdFromEnding('Loginbox_Username') + ';' +
		GetFullIdFromEnding('PersistCookie');
	var hiddenFields = '';
	var passwordFields = GetFullIdFromEnding('Loginbox_Password');
	AddFormFieldsCode(visibleFields, hiddenFields, passwordFields);
}

function AddFormFieldsCode(visible, hidden, password)
{
	new ns_API.form("aspnetForm").addSubmitEvent(visible, hidden, password); 
	new ns_API.form("aspnetForm").addAbandonEvent(visible, hidden, password); 
}

function GetObjectFromEnding(ending)
{
	if ($('input[@id$=' + ending + ']').length > 0)
	{
		return $('input[@id$=' + ending + ']');
	}
	if ($('select[@id$=' + ending + ']').length > 0)
	{
		return $('select[@id$=' + ending + ']');
	}
	if ($('textarea[@id$=' + ending + ']').length > 0)
	{
		return $('textarea[@id$=' + ending + ']');
	}
	return null;
}

function GetFullIdFromEnding(ending)
{
	var object = GetObjectFromEnding(ending);
	if (object != null)
	{
		return object.attr('id');
	}
	return '';
}

