//
// Get IP to Geolocation / Region from Google API
// Matches a sampling of surrounding regions and cities
// author: mcn 1/6/2009
// copyright: page1solutions.com
//

//var debug = true;
var debug = false;

var clientCity  = ""; 
var clientState = ""; 

google.load("maps", "2");

function initialize() {
	
	if (google.loader.ClientLocation && google.loader.ClientLocation.address.city && google.loader.ClientLocation.address.region) {
		clientCity  = google.loader.ClientLocation.address.city.toUpperCase();
		clientState = google.loader.ClientLocation.address.region.toUpperCase();
	}
}

initialize();

var terms       = [clientCity, clientState];
var locations   = { 'denver': ['DENVER', 'CO', 'COLORADO', 'UTAH', 'UT', 'NEW MEXICO', 'NM', 'WYOMING', 'WY', 'KANSAS', 'KS'], 
                    'portland': ['PORTLAND', 'OR', 'VANCOUVER', 'OREGON', 'OR', 'WASHINGTON', 'WA', 'CALIFORNIA', 'CA', 'IDAHO', 'ID'], 
                    'indianapolis': ['INDIANAPOLIS', 'IN', 'INDIANA', 'IN', 'CHICAGO', 'ILLINOIS', 'IL', 'OHIO', 'OH', 'TX'] };              
//
// Match a term in array against the given array of words, 
// 	Return true if found, false otherwise.
//                  
function match_within (terms, words) {

	var matched = false;
	var wsize   = words.length;
	var tsize   = terms.length;

	if (wsize == 0 || tsize == 0) {
		return false;
	}
		
	for ( var i = 0; i < wsize; i++ ) {
	
		for ( var j = 0; j < tsize; j++ ) {
			var pat = new RegExp( words[i] );
			matched = pat.test( terms[j] );
			
			if (debug) {
				//alert("match word pattern: " + words[i] + " with term: " + terms[j] + " result: " + matched); //IE
				//console.log("match word pattern: " + words[i] + " with term: " + terms[j] + " result: " + matched);
			}
			if (matched == true) return true;
		}
	}
	return false;
}

//
// If a term is matched within the words for a webclient's city/state, 
//	redirect the client to the appropriate page
//
switch (true) {

	case ( match_within(terms, locations['denver']) ) :
		window.location.replace("http://www.2020institute.com/denver/denver-why_2020.html"); 
		break;
	
	case ( match_within(terms, locations['portland']) ) :
		window.location.replace("http://www.2020institute.com/portland/portland-why_2020.html"); 
		break;

	case ( match_within(terms, locations['indianapolis']) ) : 
		window.location.replace("http://www.2020institute.com/indy/indy-why_2020.html"); 
		break;

	default: 
		//window.location.replace("http://www.2020institute.com/index.html"); //can cause redirect loop if not disabled after testing.
}