// MyHuttig Script (c) Huttig 2009 All Rights Reserved 

var myLat;
var myLon;



// 2 point Distance calulation
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/*  Modified from - Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2009            */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
function get_distance(lat1, lon1, lat2, lon2 ) {
	var R = 3963; // Radius of the earth in miles
	var dLat = (lat2-lat1) * Math.PI / 180;  
	var dLon = (lon2-lon1) * Math.PI / 180; 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
			Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var dist = R * c; // Distance in miles
	return dist
}   
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/*  End Modified Script																				              */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

// Branch Class
var Branch = function(title, lat, lon, zip, href) {
	this.title = title;
	this.lat = lat;
	this.lon = lon;
	this.zip = zip;
	this.href = href;
	if (myLat!=undefined) this.distance = get_distance(myLat, myLon, lat, lon);
	allBranches.push(this);
}

// Branches Array
var allBranches = [];


// Brach Objects
var branch1 = new Branch("Albuquerque", 35.17, -106.59, 87113, "branch.aspx?city=Albuquerque");
var branch2 = new Branch("Auburn", 47.3, -122.26, 98001, "branch.aspx?city=Auburn");
var branch3 = new Branch("Augusta", 44.35, -69.73, 04330, "branch.aspx?city=Augusta");
var branch4 = new Branch("Cape Girardeau", 37.31, -89.54, 63701, "branch.aspx?city=Cape Girardeau");
var branch5 = new Branch("Central Florida", 28.19, -81.61, 33897, "branch.aspx?city=Central Florida");
var branch6 = new Branch("Hooksett", 43.05, -71.44, 03106, "branch.aspx?city=Hooksett");
var branch7 = new Branch("Columbus", 39.47, -82.31, 43127, "branch.aspx?city=Columbus");
var branch8 = new Branch("Dallas", 32.91, -96.89, 75234, "branch.aspx?city=Dallas");
var branch9 = new Branch("Elkhart", 41.68, -85.96, 46515, "branch.aspx?city=Elkhart");
var branch10 = new Branch("Fort Myers", 26.63, -81.83, 33916, "branch.aspx?city=Fort Myers");
var branch11 = new Branch("Greenville", 34.72, -82.42, 29673, "branch.aspx?city=piedmont");
var branch12 = new Branch("Jackson", 32.32, -90.25, 39209, "branch.aspx?city=Jackson");
var branch13 = new Branch("Jacksonville", 30.33, -81.72, 32254, "branch.aspx?city=Jacksonville");
var branch14 = new Branch("Lancaster", 40.06, -76.32, 17601, "branch.aspx?city=Lancaster");
var branch15 = new Branch("Medford", 42.31, -122.88, 97501, "branch.aspx?city=Medford");
var branch16 = new Branch("Nashville", 36.13, -86.73, 37210, "branch.aspx?city=Nashville");
var branch17 = new Branch("Newington", 41.68, -72.72, 06111, "branch.aspx?city=Newington");
var branch18 = new Branch("Phoenix", 33.51, -112.12, 85017, "branch.aspx?city=Phoenix");
var branch19 = new Branch("Riviera Beach", 26.77, -80.07, 33404, "branch.aspx?city=Riviera Beach");
var branch20 = new Branch("Rocky Mount", 35.97, -77.83, 27804, "branch.aspx?city=Rocky Mount");
var branch21 = new Branch("Saco", 43.53, -70.46, 04072, "branch.aspx?city=Saco");
var branch22 = new Branch("Sacramento", 38.55, -121.36, 95826, "branch.aspx?city=Sacramento");
var branch23 = new Branch("Selkirk", 42.55, -73.81, 12158, "branch.aspx?city=Selkirk");
var branch24 = new Branch("Socal", 34.09, -117.58, 91730, "branch.aspx?city=Socal");
var branch25 = new Branch("Taunton", 41.9, -71.1, 02780, "branch.aspx?city=Taunton");
var branch26 = new Branch("Tigard", 45.43, -122.77, 97223, "branch.aspx?city=Tigard");
var branch27 = new Branch("Wilkes-Barre", 41.24, -75.88, 18701, "branch.aspx?city=Wilkes-Barre");


//Compares distances of branches and sets var closest to shortest branch value
function getClosestBranch(branches) {
var closest = branches[0]; 
for (var i = 1; i < branches.length; i++) {
	if (branches[i].distance < closest.distance) {
		closest = branches[i]; 
	}
}
return closest;
}


// Sets cookie to store location name
function setCookie(t,d) {
	// Check for auto override pages
	if (t) {
		//alert(t);
		var matched = allBranches[0]; 
		for (var i = 1; i < allBranches.length; i++) {
			
			if (allBranches[i].title == t) {
				matched = allBranches[i]; 
			}
		} 
		//Script fails here for IE 6
		if (matched.title != t) {
			alert("My Huttig Failed to match a location.  Please try again.");
		} else {
			//delete document.cookie;
			//Set the exp of Cookie for a year
			var days = 365;
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
			//alert(expires);
			document.cookie = 'closest=' + matched.title + expires + '; path=/';
			document.cookie = 'href=' + matched.href + expires + '; path=/';
			
			//GA event tracking
			if (window.gat_ && window.gat_.getTracker_) {_gaq.push(['_trackEvent', 'MyHuttig', 'Set Branch', matched.title]);}
			
			// Cookied location
			var clocation = readCookie();
			if (clocation[0] && d!=false) {
				scroll('0','0');
				//alert("My Huttig Branch is set to " + clocation[0]);
				$('#jsAlert').stop().show().html('<p>MY HUTTIG Branch Set to <span class="orange">' + clocation[0] + '</span></p>').css({opacity:1});
				$('#branchlinks').html('<p style="font-size:.9em"><a href="' + clocation[1] + '" class="button">View ' + clocation[0] + ' Branch Page</a> &nbsp;&nbsp;&nbsp; <a href="cc/" class="button dsearch" style="margin-bottom:0;">View Customer Connections</a> </p>');
				$('#jsAlert').animate({opacity:0},4000, function() { $(this).slideUp(500) });
			}
		}	
	
	
	/* // home page set cookie
	} else {
		//Set the exp of Cookie for a year
		var days = 365;
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		//alert(expires);
		document.cookie = 'closest=' + closest.title + expires + '; path=/';
		document.cookie = 'href=' + closest.href + expires + '; path=/';
		*/
	}
	
}

// Read cookie and return location name & h
function readCookie() {
	//closest=(\w|\s)*;
	//href=(a-zA-Z0-9|\.|\?|=|\w|\s)*;
	var ca = document.cookie.split('closest=');
	if (ca[1]) {
	    ca2 = ca[1].split('; href=');
	    ca2[1] = ca2[1].split(";", 1);
		return ca2; 
		
	} else {
		return null;
	}
}

function setBranch() {
	// Replace My HTG branch with cloest branch title & href
	$('#branch').html('<span>' + closest.title + '</span>');
	$('#branch').attr('href', closest.href);
}

function popUp() {
	// Add City and Branch to Popup
	
	/* $('span.mybranch').html(closest.title); */
	
	// initialize pop up on load
	$(window).load(function() {
		//if (myCity != '') {
			$('#myhtg-popup').fadeIn("slow");
			$('#myhtg-popup a').click(function() {
				$(this).parent().fadeOut("slow");
			});
		//}
	});
}

// Cookied location
var clocation = readCookie();

// Declare closest object
var closest

// Initialize location script
function intLocation() {
	// Intiate if lat or cookie are found
	//if (myLat || clocation) { 
	
		// Load branches to comparison function
		closest = getClosestBranch(allBranches);
			 
		if (clocation) {
			closest.title = clocation[0];
			closest.href = clocation[1];
			setBranch();
		} else {
			//setCookie();
			popUp();
			//setBranch();
		}	
	//}
}

// create overides for Lat and Lon with GEO Location
function foundLocation(position) {
	myLat = position.coords.latitude;
	myLon = position.coords.longitude;
	myCity = '';
	intLocation();
	$('#myhtg-popup p').html('Based on IP location technology, we think the closest Huttig Branch to your location is <span class="mybranch">' + closest.title + '</span>');
	$('#myhtg-popup').fadeIn("slow");
	$('#myhtg-popup a').click(function() {
		$(this).parent().fadeOut("slow");
	});
	//alert('Found location: ' + myLat + ', ' + myLon);
} function noLocation() {
	return
}


