﻿if (window.P == null) window.P = "";
if (window.E == null) window.E = "";

var Utf8 = 
{
	// public method for url encoding
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// public method for url decoding
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
    }
}



function GetHttp(u, c, t)
{
    var x = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
    x.open("GET", u, true);
    x.onreadystatechange = function()
    {
		if (x.readyState==4&&x.status==200&&x.responseText)c(x.responseText, t, u);
		else if (x.readyState == 4) c("{failed}{0}");
    }
    x.send(null);
}

function lockChanges()
{
	countries.onchange = function(){};
	states.onchange = function(){};
	cities.onchange = function(){};
}

function unlockChanges()
{
	countries.onchange = countryChanged;
	states.onchange = stateChanged;
	cities.onchange = cityChanged;
}

function GetQueryStringValue(queryString, key, defValue)
{
	if (defValue == null) defValue = "";
	
	queryString = "&" + queryString.split("?").pop() + "&";
	var parts = queryString.split("&" + key + "=");
	return parts.length > 1 ? Utf8.decode(unescape(parts[1].split("&")[0]).split('+').join(' ')) : defValue;
}


function countryChanged()
{
	if (countries.lastText == null) countries.lastText = "";
	var text = countries.options.length == 0 ? "" : countries.options[countries.selectedIndex].text;
	if (countries.lastText == text) return;
	countries.lastText = text;

	lockChanges();
	states.options.length = 0;
	cities.options.length = 0;
	unlockChanges();
	setTimeout(executeLocations, 0);
}

function stateChanged()
{
	if (states.lastText == null) states.lastText = "";
	var text = states.options.length == 0 ? "" : states.options[states.selectedIndex].text;
	if (states.lastText == text) return;
	states.lastText = text;


	lockChanges();
	cities.options.length = 0;
	unlockChanges();
	setTimeout(executeLocations, 0);
}

function cityChanged()
{
	if (cities.lastText == null) cities.lastText = "";
	var text = cities.options.length == 0 ? "" : cities.options[cities.selectedIndex].text;
	if (cities.lastText == text) return;
	cities.lastText = text;

	setTimeout(executeLocations, 0);
}



function showInternetError()
{
	showMsg('msgCannotSearch');		
}

function responseLocations(response)
{
	if (response.indexOf("Success") != 0)
	{
		showInternetError();
		setTimeout(executeLocations, 2000);
		return;
	}
	
	var lines = response.split("\n");
	var countryLabelText = GetQueryStringValue(lines[0], "CountryLabel");
	var stateLabelText = GetQueryStringValue(lines[0], "StateLabel");
	var cityLabelText = GetQueryStringValue(lines[0], "CityLabel");
	var hasStates = GetQueryStringValue(lines[0], "HasStates");
	var countryCode = GetQueryStringValue(lines[0], "CountryCode");
	var stateCode = GetQueryStringValue(lines[0], "StateCode");
	var cityCode = GetQueryStringValue(lines[0], "CityCode");

	lockChanges();

	// Populate the Combo Boxes
	countries.options.length = 0;
	states.options.length = 0;
	cities.options.length = 0;

	states.options[states.options.length] = new Option("", "");
	cities.options[cities.options.length] = new Option("", "");


	var countryIndex = -1, stateIndex = -1, cityIndex = -1;
	var mode;
	var results;
	for (var i=0;i<lines.length;i++)
	{
		if (lines[i].charAt(0) == "[") mode = lines[i];
		else
		{
			if (mode == "[COUNTRIES]")
			{
				var parts = lines[i].split(':');
				if (parts.length == 2)
				{
					countries.options[countries.options.length] = new Option(parts[1], parts[0]);
					if (parts[0].toUpperCase() == countryCode.toUpperCase())
					{
						countryIndex = countries.length - 1;
					}
				}
			}
			else if (mode == "[STATES]")
			{
				var parts = lines[i].split(':');
				if (parts.length == 2)
				{
					states.options[states.options.length] = new Option(parts[1], parts[0]);
					if (parts[0].toUpperCase() == stateCode.toUpperCase())
					{
						stateIndex = states.length - 1;
					}
				}
			}
			else if (mode == "[CITIES]")
			{
				var parts = lines[i].split(':');
				if (parts.length == 2)
				{
					cities.options[cities.options.length] = new Option(parts[1], parts[0]);
					if (parts[0].toUpperCase() == cityCode.toUpperCase())
					{
						cityIndex = cities.length - 1;
					}
				}
			}
			else if (mode == "[RESULTS]")
			{
				results = lines[i];
			}
		}
	}
	
	
	
	countries.selectedIndex = countryIndex;
	states.selectedIndex = stateIndex;
	cities.selectedIndex = cityIndex;
	
	unlockChanges();

	// Show / Hide the Combo Boxes
	countryLabel.innerHTML = countryLabelText;
	countryLabel.style.visibility = 'visible';
	countries.style.visibility = 'visible';

	if (hasStates == "1" && (countryCode == 'US' || countryCode == 'CA'))
	{
		stateLabel.innerHTML = stateLabelText;
		stateLabel.style.visibility = 'visible';
		states.style.visibility = 'visible';
	}
	else
	{
		stateLabel.style.visibility = 'hidden';
		states.style.visibility = 'hidden';
	}

	
	cityLabel.innerHTML = cityLabelText;
	cityLabel.style.visibility = 'visible';
	cities.style.visibility = 'visible';
	
	// Display the More Fields Message
	hideMsgs();
	
	if (selText(states) == "" && selText(cities) == "")
	{
		/*if (hasStates != "1")
		{
			showMsg("msgSelectCity");
		}
		else
		{
			showMsg("msgSelectStateMajorCity");
		}*/
	}

	
	hideResults();
	if (document.getElementById("msg").style.display == 'none')
	{
		if (results == "Error: Too many course to display.")
		{
			if (selText(states) == "" && selText(cities) == "")
			{
				if (hasStates != "1")
				{
					showMsg("msgSelectCity");
				}
				else
				{
					showMsg("msgSelectStateMajorCity");
				}
			}
			else
			{
				showMsg("msgTooMany");
			}
		}
		else if (results == "")
		{
			showMsg("msgNoResults");
		}
		else
		{
			showResults(results);
		}
	}
}

filterTextCache = "";
filterDivs = null; 
function filter()
{
	return trim10(filterText.value);
}

function filterList(text)
{
	if (trim10(filterTextCache.toLowerCase()) == trim10(text.toLowerCase()))
	{
		return;
	}
	filterTextCache = text;
	
	
	var divs = filterDivs;
	if (text == "")
	{
		for (var i=0;i<divs.length;i++)
		{
			divs[i].style.display = '';
		}
	}
	else
	{
		var filteredData = new Array();
		var prevItemIs_P = false;
		text = text.toLowerCase();
		for (var i=0;i<divs.length;i++)
		{
			var item = divs[i];
			if (item.innerHTML.toLowerCase().indexOf(text) != -1)
			{
				if (item.style.fontWeight == "bold")
				{
					if (prevItemIs_P)
					{
						filteredData.pop();
					}
					filteredData.push(item);
					prevItemIs_P = true;
					i++;
					for (;i<divs.length;i++)
					{
						var item = divs[i];
						if (item.style.fontWeight == "bold")
						{
							i--;
							break;
						}
						else
						{
							filteredData.push(item);
							prevItemIs_P = false;
						}
					}
				}
				else
				{
					filteredData.push(item);
					prevItemIs_P = false;
				}
			}
		}
		if (prevItemIs_P)
		{
			filteredData.pop();
		}
		for (var i=0;i<divs.length;i++)
		{
			divs[i].style.display = 'none';		
		}
		for (var i=0;i<filteredData.length;i++)
		{
			filteredData[i].style.display = '';		
		}
	}
}


function Filter_update()
{
	if (filter() == "" || filter() == "Enter Course Name to Filter Search") filterText.value = "";
	filterList(filter());
}
function Filter_blur()
{
	if (filter() == "")
	{
		filterText.style.color = "#666666";
		filterText.style.fontWeight = "bold";
		filterText.value = "Enter Course Name to Filter Search";
	}
}
function Filter_focus()
{
	if (filter() == "Enter Course Name to Filter Search")
	{
		filterText.style.color = "#333333";
		filterText.style.fontWeight = "normal";
		filterText.value = "";
	}
}

function trim10(str) 
{
	var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
	for (var i = 0; i < str.length; i++) 
	{
		if (whitespace.indexOf(str.charAt(i)) === -1) 
		{
			str = str.substring(i);
			break;
		}
	}
	for (i = str.length - 1; i >= 0; i--) 
	{
		if (whitespace.indexOf(str.charAt(i)) === -1) 
		{
			str = str.substring(0, i + 1);
			break;
		}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function showResults(results)
{
	resultsBox.style.display = '';
	filterText.style.display = '';
	filterText.value = "";
	Filter_blur();
	filterText.onkeypress = Filter_update;
	filterText.onkeydown = Filter_update;
	filterText.onkeyup = Filter_update;
	filterText.onfocus = Filter_focus;
	filterText.onblur = Filter_blur;

	filterTextCache = "";
	
	
	var count = 0;
	var lastLocation = "";
	var html = "";
	results = results.split('?');
	for (var i=0;i<results.length;i++)
	{
		var name = GetQueryStringValue(results[i], "n");
		var city = GetQueryStringValue(results[i], "c");
		var state = GetQueryStringValue(results[i], "s");
		var stateAbbr = GetQueryStringValue(results[i], "j");
		var country = GetQueryStringValue(results[i], "t");
		var holes = GetQueryStringValue(results[i], "h");
		var kCode = GetQueryStringValue(results[i], "k");
		if (kCode == "" || kCode == "0")
		{
			if (country == "") country = "US";
			var location = city;
			if (lastLocation != location)
			{
				
				html += "<div style='font-weight:bold'>" + location + "</div>";
				lastLocation = location;
			}
			if (E != null)
			{
				var x = GetQueryStringValue(results[i], "x");
				var Ee = E.split("#X#").join(x);
			}
			else
			{
				var Ee = "";
			}
			html += "<div>" + fixName(name) + "</div>"
			count++;
		}
	}
	resultsBox.innerHTML = html;
	filterDivs = resultsBox.getElementsByTagName("DIV");	
	
	showMsg("msgCourseCount");
	
	var country = countries.options[countries.selectedIndex].value;
	
	if (country == 'US' || country == 'CA')
	{
		document.getElementById('msgCourseCount').innerHTML = count + ' Course' + (count==1?'':'s') + ' Mapped in ' + states.options[states.selectedIndex].text;
	}
	else
	{
		document.getElementById('msgCourseCount').innerHTML = count + ' Course' + (count==1?'':'s') + ' Mapped in ' + countries.options[countries.selectedIndex].text;
	}
	
	
}

function fixName(name)
{
	var modified = false;
	var parts = name.split(" - ");
	if (parts.length == 2)
	{
		var facility = parts[0].replace(/^\s*/, "").replace(/\s*$/, "");
		var courseName = parts[1].replace(/^\s*/, "").replace(/\s*$/, "");
		if (facility.toLowerCase().indexOf(courseName.toLowerCase()) == 0)
		{
			name = facility;
		}
	}
	return name;
}


function hideResults()
{
	resultsBox.style.display = 'none';
	filterText.style.display = 'none';
}

function selText(box)
{
	if (box.selectedIndex == -1) return "";
	return box.options[box.selectedIndex].text;
}

function selValue(box)
{
	if (box.selectedIndex == -1) return "";
	return box.options[box.selectedIndex].value;
}

function executeLocations()
{
	var country = selValue(countries);
	if (country == "" && window.siteRegion != null && window.siteRegion != "")
	{
		country = window.siteRegion;
	}
	if (countries.length == 0)
	{
		if (window.siteRegion != null && window.siteRegion != "")
		{
			country = window.siteRegion;
		}
		else
		{
			country = "US";
		}
	}
	
	if (country == "UK") country = "GB";
	
	var state = selValue(states);
	var cityCode = selValue(cities)
	var city = selText(cities);
	
	if (state == "" && country == "US") state = "FL";
	if (state == "" && country == "CA") state = "ON";
	
	if (countries.style.visibility != 'hidden')
	{
		showMsg('msgSearching');
		hideResults();
	}
	lockChanges();
	var requestUrl = P + "CourseLocationsLocal.aspx?CountryCode=" + escape(country) + "&StateCode=" + escape(state) + "&CityCode=" + escape(cityCode) + "&City=" + escape(city) + "&OnlyValidCountries=1&Extended=" + escape(extended);
	GetHttp(requestUrl, responseLocations);
}


var msgDivs = ["msgContacting", "msgSelectStateMajorCity", "msgSearching", "msgSelectCity", 
	"msgSelectStateProvinceMajorCity", "msgSelectProvinceMajorCity", "msgCannotSearch", 
	"msgTooMany", "msgNoResults", "msgCourseCount"];
function hideMsgs()
{
	for (var i=0;i<msgDivs.length;i++) 
	{
		document.getElementById(msgDivs[i]).style.display = 'none';
	}
	document.getElementById("msg").style.display = 'none';
}
function showMsg(id)
{
	hideMsgs();
	document.getElementById(id).style.display = 'block';
	document.getElementById("msg").style.display = 'block';
}

//writeForm();


window.countries = document.getElementById('countries');
window.states = document.getElementById('states');
window.cities = document.getElementById('cities');
window.countryLabel = document.getElementById('countryLabel');
window.stateLabel = document.getElementById('stateLabel');
window.cityLabel = document.getElementById('cityLabel');
window.resultsBox = document.getElementById('courses-rows');
window.filterText = document.getElementById('filterText');

showMsg("msgContacting");
executeLocations();



