function preload() {
	$('<img>').attr('src', 'img/bg_subnav_top.png');
	$('<img>').attr('src', 'img/bg_subnav.png');
	$('<img>').attr('src', 'img/bg_subnav_btm.png');
	$('<img>').attr('src', 'img/bg_subnav_about.gif');
	$('<img>').attr('src', 'img/bg_subnav_talk_vet.gif');
	$('<img>').attr('src', 'img/bg_subnav_vet_finder.gif');
	$('<img>').attr('src', 'img/bg_subnav_infestation.gif');
	$('<img>').attr('src', 'img/bg_subnav_lifecycle.gif');
	$('<img>').attr('src', 'img/bg_subnav_flea_facts.gif');
	$('<img>').attr('src', 'img/bg_subnav_qa.gif');
	$('<img>').attr('src', 'img/bg_subnav_heartworm_info.gif');
	$('<img>').attr('src', 'img/bg_subnav_roundworm.gif');
	$('<img>').attr('src', 'img/bg_subnav_whipworm.gif');
	$('<img>').attr('src', 'img/bg_subnav_hookworm.gif');
	$('<img>').attr('src', 'img/btn_get_directions.png');
	$('<img>').attr('src', 'img/btn_show_directions.gif');
	$('<img>').attr('src', 'img/icon_link_arrow_back.gif');
}


/*
 * Main Sentinel functions
 */
var Sentinel = {
	map: null,
	ib: null,
	markers: new Array(),
	vetsObject: new Array(),
	vetCount: -1,
	vetLimit: 10,
	vetCurrent: -1,
	currFlashAddress: "/",
	
	// Functions
	init: function(){
		Sentinel.initNavigation();
	},
	
	initNavigation: function() {
		$('a.close, #logo a, #overlay').bind('click', function(e){
//		$('a.close, #overlay').bind('click', function(e){
			e.preventDefault();
			$.address.value(Sentinel.currFlashAddress);
		});			
	},
	
	initGoogleMaps: function() {
		$.ajax({
//			url: "GetVetsNear.xml",
			url: "VetFinderService.asmx/GetVetsNear",
//			url: "proxy.php",
			type: "GET",
			data: 'searchZipcode=',
			dataType: "xml",
			error: function() {  
				alert('Sorry, we were unable to retrieve the list of veterinatians. Please try again.');
				Sentinel.resizeOverlay();
			},					
			success: function(xmlResults) {
				Sentinel.loadVeterinarians(xmlResults);
			}
		 }
		);	
		
		$('#zipcodeSearch').submit(function(e) {
			e.preventDefault();
			var zip = $('#zip_code').val();
			if (/^\d{5}(-\d{4})?(?!-)$/.test(zip)) {
				_gaq.push(['_trackEvent', 'map', 'zipcode', zip]);

				$.ajax({
					url: "VetFinderService.asmx/GetVetsNear",
//					url: "proxy.php",
					type: "GET",
					data: 'searchZipcode='+zip,
					dataType: "xml",
					error: function() {  
						alert('Sorry, we were unable to retrieve the list of veterinatians. Please try again.');
					},					
					success: function(xmlResults) {
						Sentinel.loadVeterinarians(xmlResults);
					}
				 });			
			} else {
				alert('Please enter a valid ZIP Code');
			}
		});
	},

	loadVeterinarians: function(xmlResults) {
		Sentinel.vetCount = $(xmlResults).find('Locations').attr('count');
		var mapZip = $(xmlResults).find('Locations').attr('zipcode');
		var mapLat = $(xmlResults).find('Locations').attr('latitude');
		var mapLong = $(xmlResults).find('Locations').attr('longitude');

		var vets =  $(xmlResults).find('Location');
		Sentinel.vetsObject = new Array();
		
		if (mapZip) $('.vet_list h2').html('Local Veterinarians Found for Zip Code : <span>'+mapZip+'</span>');
		else  $('.vet_list h2').html('Local Veterinarians Found in Your Area');

		if (mapLat && mapLong) {
			var latlng = new google.maps.LatLng(mapLat, mapLong);
			var mapOptions = {
				zoom: 13,
				center: latlng,
				mapTypeControl: false,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			Sentinel.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
			
			Sentinel.markers = new Array();
			
			var infoBoxOptions = {
				disableAutoPan: false,
				maxWidth: 282,
				pixelOffset: new google.maps.Size(-5, -163),
				boxStyle: {background: "url('img/icon_info_tip.png') 0px 122px no-repeat",width: "282px"},
				closeBoxMargin: "18px 15px 2px 2px",
				closeBoxURL: "img/btn_close.gif",
				infoBoxClearance: new google.maps.Size(30, 10)
			};
			
			Sentinel.ib = new InfoBox(infoBoxOptions);
			
			var vetList = "";
			
		   var bound = new google.maps.LatLngBounds();
			
			var numVets = (vets.length < Sentinel.vetLimit) ? vets.length : Sentinel.vetLimit;
			
			if (vets.length == 0) {
				vetList = "<h3 style=\"padding-top:10px\">Sorry, no veterinarians were found.</h3>";
			}
			for (var i=0; i < numVets; i++) {
				Sentinel.vetsObject[i] = {
					'id' : $(vets[i]).find('Customer_ID').text(),
					'name' : $(vets[i]).find('Clinic_Name').text(),
					'vet' : $(vets[i]).find('Vet_Name').text(),
					'address' : $(vets[i]).find('Street_Address').text(),
					'city' : $(vets[i]).find('City').text(),
					'state' : $(vets[i]).find('State').text(),
					'zip' : $(vets[i]).find('Zip_Code').text(),
					'phone' : $(vets[i]).find('Phone_Number').text(),
					'url' : $(vets[i]).find('URL').text(),
					'lat' : $(vets[i]).find('Latitude').text(),
					'long' : $(vets[i]).find('Longitude').text()
				}
				
				var markerLatLng = new google.maps.LatLng(Sentinel.vetsObject[i].lat, Sentinel.vetsObject[i].long);

//				alert(google.maps.geometry.spherical.computeDistanceBetween(markerLatLng, latlng)/1609.344);
				Sentinel.markers[i] = new google.maps.Marker({
					position: markerLatLng,
					icon: 'img/marker_'+(i+1)+'.png',
					title: Sentinel.vetsObject[i].name
				});
				
			   bound.extend(Sentinel.markers[i].getPosition());
				
				Sentinel.markers[i].setMap(Sentinel.map);
				
				google.maps.event.addListener(Sentinel.markers[i], 'click', function(e) {
					for (var i=0; i < Sentinel.markers.length; i++) {
						if (this == Sentinel.markers[i])	Sentinel.popupInfoWindow(i);
					}
				});
				
				var islast = (i+1 == numVets) ? " last" : "";
				vetList += "<li class=\"vet_"+(i+1)+ islast +"\">";
            vetList += "<h3>"+Sentinel.vetsObject[i].name+"</h3>";
            vetList += "<p>"+Sentinel.vetsObject[i].address+", "+Sentinel.vetsObject[i].city+", "+Sentinel.vetsObject[i].state+" "+Sentinel.vetsObject[i].zip + "</p>";
            vetList += "<a href=\"#\" class=\"view\">View on Map</a>";
            vetList += "</li>";
			}
			
			if (vets.length > 0) {
				if (vets.length > 1) Sentinel.map.fitBounds(bound);
			    Sentinel.map.setCenter(bound.getCenter());
			}
			
			$('.vet_list ul').html(vetList);
			
			$('.view').click(function(e) {
				e.preventDefault();
				e.stopPropagation();
				var index = $('.view').index(this);
				$('#main_content').scrollTop(0);
				Sentinel.popupInfoWindow(index);
			});
			
		} else {
			alert('Sorry, your location was unable to be found. Please try again');
		}
		Sentinel.resizeOverlay();
	},
	
	popupInfoWindow: function(index) {
		var vet = Sentinel.vetsObject[index];
		Sentinel.vetCurrent = vet.id;
		_gaq.push(['_trackEvent', 'map', 'vet', vet.id]);
		
		var boxText = "<div class=\"infoBox\">";
		boxText += "<div class=\"vetDetails\">";
		boxText += "<h2>"+vet.name+"</h2>";
		boxText += "<div class=\"infoDetails\">";
		boxText += "<h3>"+vet.vet+"</h3>";
		boxText += "<address>"+vet.address + "<br />" + vet.city + ", " + vet.state + " " + vet.zip+"</address>";
		var extraInfo = vet.phone;
		if (vet.url) {
			var vetUrl = (vet.url.indexOf("http") == -1) ? "http://" + vet.url : vet.url;
			extraInfo += "<br /><a href=\""+vetUrl+"\" target=\"_blank\">"+vet.url+"</a>";
		}
		boxText += "<p class=\"tel\">"+extraInfo+"</p>";
		boxText += "</div>";
		boxText += "<div class=\"btns\"><a href=\"#\" class=\"get_directions\" onclick=\"Sentinel.showGetDirections(event);return false;\">Get Directions</a></div>";
		boxText += "</div>";
		boxText += "<div class=\"getDirections\">";
		boxText += "<h2>Get Directions</h2>";
		boxText += "<form id=\"form_directions\" action=\"http://maps.google.com/maps\" method=\"get\" target=\"_blank\">";
		boxText += "<div class=\"directionsForm\">";
		boxText += "<label for=\"saddr\">Start</label>";
		boxText += "<input type=\"text\" name=\"saddr\" id=\"saddr\" class=\"input_saddr\" value=\"Enter your starting location address\" onfocus=\"Sentinel.startAddressFocus();\" onkeyup=\"Sentinel.startAddressChange(event);\" />";
		boxText += "<label>Destination</label>";
		boxText += "<input type=\"text\" name=\"destination\" id=\"destination\" disabled=\"true\" value=\""+vet.address + ", " + vet.city + ", " + vet.state + " " + vet.zip+"\" />";
		boxText += "<input type=\"hidden\" name=\"daddr\" id=\"daddr\" value=\""+vet.address + ", " + vet.city + ", " + vet.state + " " + vet.zip+"\" />";
		boxText += "<a class=\"show_directions show_directions_disabled\">Show Directions</a>";
		boxText += "</div>";
		boxText += "<div class=\"btns\"><a href=\"#\" class=\"back\" onclick=\"Sentinel.hideGetDirections(event);return false;\">Go Back To Veterinarian Details</a></div>";
		boxText += "</form>";
		boxText += "</div>";
	
		Sentinel.ib.setContent(boxText);
		Sentinel.ib.open(Sentinel.map, Sentinel.markers[index]);
	},
	
	resizeOverlay: function() {
		
		
		if (Sentinel.vetCount != -1) {
			var numVets = (Sentinel.vetCount < Sentinel.vetLimit) ? Sentinel.vetCount : Sentinel.vetLimit;
			$('.vet_count').html(numVets);
		} else {
			$.ajax({
//				url: "proxy.php",
				url: "VetFinderService.asmx/GetVetsNear",
				type: "GET",
				data: 'searchZipcode=',
				dataType: "xml",
				error: function() {},					
				success: function(xmlResults) {
					Sentinel.getVetCount(xmlResults);
				}
			 }
			);				
		}
		var resizeHeight = ($('#flash_container').height() > $('#main_content .container').height() + 76) ? $('#flash_container').height() : $('#main_content .container').height() + 76;
		$('#overlay').height(resizeHeight);
		//console.log("resizeOverlay " + resizeHeight + " Flash container height " + $('#flash_container').height() + " main content + 76 " + ($('#main_content .container').height() + 76));
		if ($.browser.msie) {
			$('#main_content a:not(.normal)').each(function() {
				var linkhref = $(this).attr('href');
				var linkArray = linkhref.split("/");

				if (linkArray.length > 2) {
					linkhref = linkArray[linkArray.length-1];
					$(this).attr('href', linkhref);
				}
			});
		}
		
		$('#main_content a:not(.normal, .close)').address();
		$('a.normal').click(function() {
			if (this.href && this.href != "#") {
				_gaq.push(['_trackEvent', 'exit', 'plannedexit', this.href]);
			}
		});
	},
	
	getVetCount: function(xmlResults) {
		Sentinel.vetCount = $(xmlResults).find('Locations').attr('count');
		var numVets = (Sentinel.vetCount < Sentinel.vetLimit) ? Sentinel.vetCount : Sentinel.vetLimit;
		$('.vet_count').html(numVets);
	},
	
	showGetDirections: function(e) {
		_gaq.push(['_trackEvent', 'map', 'directions-input', Sentinel.vetCurrent]);

		var event = e || window.event;
		if (event.stopPropagation) event.stopPropagation();
		else if(window.event) window.event.cancelBubble=true;
		$('.vetDetails').hide();
		$('.getDirections').show();
	},

	hideGetDirections: function(e) {
		var event = e || window.event;
		if (event.stopPropagation) event.stopPropagation();
		else if(window.event) window.event.cancelBubble=true;
		$('.vetDetails').show();
		$('.getDirections').hide();
	},
	
	startAddressFocus: function() {
		if ($('#saddr').val() == 'Enter your starting location address') $('#saddr').val('');
	},
	
	startAddressChange: function(e) {
		if ($('.show_directions_disabled').length > 0) {
			$('.show_directions').click(function(e) {
				e.preventDefault();
				e.stopPropagation();
				if ($('#saddr').val() != '' && $('#saddr').val() != 'Enter your starting location address') {
					_gaq.push(['_trackEvent', 'map', 'directions-results', Sentinel.vetCurrent]);
					$('#form_directions').submit();
				} else {
					alert('Please enter a starting address');
				}
			});
			$('.show_directions_disabled').removeClass('show_directions_disabled');
		}
	}
	
};


jQuery(document).ready(function(){
	$.address.crawlable(true);

	preload();
	Sentinel.init();
	
	$.address.change(function(event) {
		event.preventDefault();
		$('#main_nav .current').removeClass('current');
		var linkhref = event.value;
		var parms = "";

		if (linkhref.indexOf('?') != -1) {
			parms = linkhref.substring(linkhref.indexOf('?'), linkhref.length);
			linkhref = linkhref.substring(0, linkhref.indexOf('?'));
		}
		
		linkhref = linkhref.replace(/%E2%80%90/g,"-");

		// IE fix
		if (linkhref.indexOf("!/") != -1) linkhref = linkhref.replace("!/", "");
		if (linkhref != "/" && linkhref.indexOf('episode') == -1 && linkhref.indexOf('montage') == -1 && linkhref.indexOf('loop') == -1) {
//			$('#main_content').show();
			$('#main_content').scrollTop(0);

			if ((linkhref.indexOf("about-sentinel") != -1) || (linkhref.indexOf("talk-to-vet") != -1) || (linkhref.indexOf("vet-finder") != -1) || (linkhref.indexOf("rebate") != -1))  {
				$('.nav_one_tablet a').addClass('current');
			} else if ((linkhref.indexOf("dirty-truth") != -1) || (linkhref.indexOf("flea-life-cycle") != -1) || (linkhref.indexOf("flea-facts") != -1) || (linkhref.indexOf("interview") != -1)) {
				$('.nav_fleas a').addClass('current');
			} else if (linkhref.indexOf("heartworms") != -1) {
				$('.nav_heartworms a').addClass('current');
			} else if ((linkhref.indexOf("roundworms") != -1) || (linkhref.indexOf("whipworms") != -1) || (linkhref.indexOf("hookworms") != -1)) {
				$('.nav_parasites a').addClass('current');
			}
			
			var loadingHTML = '<div id="content"><div class="loadingMsg">loading...</div></div><div class="footer"></div>';

			if ($('#main_content').is(':visible')) {
				$('#content .nav li, #content .banner, #content .footer a').stop().fadeOut(500);

				if ($('#content .article').length) {
					$('#content .article').stop().fadeOut(500, function(){
						if (linkhref.indexOf("vet-finder") != -1) {
							$('#content_holder').load('.' + linkhref + ".html" + parms, function() {
								$('#content .nav li, #content .banner, #content .article, #content .footer a').fadeIn(500);
								 Sentinel.initGoogleMaps();
							});
						} else {
							$('#content_holder').load('.' + linkhref + ".html" + parms, function() {
								$('#content .nav li, #content .banner, #content .article, #content .footer a').fadeIn(500);
								Sentinel.resizeOverlay();
							});
						}
					});
				} else {
					if (linkhref.indexOf("vet-finder") != -1) {
						$('#content_holder').load('.' + linkhref + ".html" + parms, function() {
							$('#content .nav li, #content .banner, #content .article, #content .footer a').fadeIn(500);
							 Sentinel.initGoogleMaps();
						});
					} else {
						$('#content_holder').load('.' + linkhref + ".html" + parms, function() {
							$('#content .nav li, #content .banner, #content .article, #content .footer a').fadeIn(500);
							Sentinel.resizeOverlay();
						});
					}
				}
			} else {
				if (linkhref.indexOf("vet-finder") != -1) {
					$('#content_holder').load('.' + linkhref + ".html" + parms, function() {
						$('#main_content').show();
						$('.footer_border').fadeIn(500);

						$('#content_overlay').css('top', $('#main_content').height());
						$('#content_overlay').animate({top:'0'}, 500);
						Sentinel.initGoogleMaps();
					});
				} else {
					$('#content_holder').load('.' + linkhref + ".html" + parms, function() {
						$('#main_content').show();

						$('#content_overlay').css('top', $('#main_content').height());
						$('#content_overlay').animate({top:'0'}, 500);
						$('.footer_border').fadeIn(500);
						
						Sentinel.resizeOverlay();
					});
				}
			}
		} else {
			Sentinel.currFlashAddress = linkhref;
			$('.footer_border').fadeOut(500);
			if ($('#main_content').is(':visible')) {
				$('#main_content').scrollTop(0);
				$('#content_overlay').animate({top:$('#main_content').height()}, 500, function() {$('#main_content').hide();});
			}
		}
	});
	
	$('a:not(.normal, .close)').address();
	$('a.normal').click(function() {
		if (this.href && this.href != "#") {
			_gaq.push(['_trackEvent', 'exit', 'plannedexit', this.href]);
		}
	});

});

