//the purpose of this script is to identify the proper environment, to allow variable code to be executed, and to include various files required in different environments

var envCode = 'web'; //start with web as default
webMatch = new RegExp(/arupconsult\./); //not used at this time
saMatch = new RegExp(/file:\/\//);
devMatch = new RegExp(/dev-www\.arupconsult|cert-www\.arupconsult/);
prevMatch = new RegExp(/arup-cms/);

//determine environment -> web, standalone, dev, preview
if(saMatch.test(window.location)) {
	//document is on standalone
	envCode = "sa";
}
if(devMatch.test(window.location)) {
	//document is on Dev or Cert
	envCode = "dev";
}
if(prevMatch.test(window.location)) {
	//document is on preview 01 or 02
	envCode = "prev";
}

// load autocomplete resources
if(envCode == "web" || envCode == "dev") {
	ac_source = "/resources/ac.php"; //use ajax call to pull up autocomplete
} else {
	local_ac_source = local_ac_source.replace(/^\//, "");//remove leading slash from path... (theory of relativity)
	document.write('<script type="text/javascript" src="' + local_ac_source + '"></script>');
	//recursive function for sorting
	ac_sort = function (a, b) {
		x=a.substring(0,1).charCodeAt(0);//get ascii value of first character
		y=b.substring(0,1).charCodeAt(0);
		if(x>=97 && x<=122) {x = x - 31.5;}//adjust lower case characters to interleave with upper case (A a B b C c) ect...
		if(y>=97 && y<=122) {y = y - 31.5;}
		if(x==y){ //move right one chararcter in strings when initial chars match
			return ac_sort(a.substring(1,a.length), b.substring(1,b.length)); //recurse
		}
		return x-y;//compare
	}
	//autocomplete function
	ac_source = function(query, ac_response) { //filter and sort ac_data
		var maxLength = 5; //max number of results to return via javascript search
		var output1 = [];//primary matches (first word matches)
		var output2 = [];//secondary matches (word other than first matches)
		var ac_regex1 = new RegExp("^"+query.term,"i")//any match that starts at beginning of string
		var ac_regex2 = new RegExp("\\b"+query.term,"i")//any match that starts with a word boundary
		//filter data
		for(ac_item in ac_data){
			if(ac_regex1.test(ac_data[ac_item])){
				output1.push(ac_data[ac_item]);
			} else if(ac_regex2.test(ac_data[ac_item])){
				output2.push(ac_data[ac_item]);
			}
		}
		//sort data
		if(output1.length) output1.sort(ac_sort);
		if(output2.length) output2.sort(ac_sort);
		//merge data
		output1 = output1.concat(output2);
		//truncate  data
		if(output1.length > maxLength) output1.length = maxLength;
		//return data
		ac_response(output1);
	}
}
