if (typeof jQuery.fn.prop === "undefined") {
	jQuery.fn.prop = jQuery.fn.attr;
}
if (!$.support.opacity) {
	$.fx.off = true;	
}
$(function(){
	$(".nav-menu li").not(".active").hover(function(){
		$(this).toggleClass('active');
	});
	
	String.prototype.PhoneFormat = function(){
		var temp = this.replace(/[^0-9]/g,'').split('');
		temp.splice(0,0,'('); // (0000000000
		temp.splice(4,0,')',' '); // (000) 0000000
		temp.splice(9,0,'-');// (000) 000-0000
		return temp.join("");
	}
	
	// maps api for dealer locator
	if (document.getElementById("map_canvas")) {
		var myOptions = {
			zoom: 4, 
			center: new google.maps.LatLng(38.68551,-98.789062), 
			mapTypeId: google.maps.MapTypeId.ROADMAP     
		};
		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

		function success(position){
			var postData = {
				"dealerType" : $('input:radio[name="dealerType"]:checked').val()
			}
			map.pv.center = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			map.pv.markerArray[0] = new google.maps.Marker({					
				position: map.pv.center, 
				map: map, 
				title:"You are here",
				zIndex: 0
			});
			map.setCenter(map.pv.center);
			
			map.fitBounds(new google.maps.Circle({
				center: map.pv.center,
				fillOpacity: 0,
				strokeOpacity: 0,
				map: map,
				radius: 80000.4
			}).getBounds());
			postData.latitude = map.pv.center.lat();
			postData.longitude = map.pv.center.lng();
			
			var request = $.ajax({
				"url" : "includes/getDealers.cfm",
				data : postData,
				dataType: "json",
				type : "POST"
			});
			
			request.done(function(data){
				function template() {
					return (this.dlrPAS ? "<span style='color: green; font-weight: bold;'>Premier Dealer</span><br />" : "")
						+ '<strong>'
						+ this.dlrName
						+ '</strong><br />'
						+ (this.dlrAdd1 ? this.dlrAdd1 + '<br />' : "")
						+ (this.dlrCity ? this.dlrCity + ', ' : "")
						+ (this.dlrState ? this.dlrState + ' ' : "")
						+ (this.dlrZip ? this.dlrZip + ' ' : "")
						+ (this.dlrCountry ? this.dlrCountry + '<br />' : "")
						+ (!this.dlrPhone ? "" : (this.dlrCountry === 'US' ? this.dlrPhone.PhoneFormat() : this.dlrPhone) + '<br />')
						+ (this.dlrEmail ? this.dlrEmail + '<br />' : "")
						+ (this.dlrWebsite ? this.dlrWebsite + '<br />' : "")
						+ (this.dlrBass || this.dlrAcoustic ? (
							"<strong>Sells or Services These Products:</strong>"
							+ (this.dlrBass ? "<br />Bass Amps" : "")
							+ (this.dlrAcoustic ? "<br />Acoustic Amps" : "")						
						) : "");
				}
				$.each(data.dealers,function(i){
					var markerPos = new google.maps.LatLng(this.dlrLatitude,this.dlrLongitude),
					marker = new google.maps.Marker({
						position: markerPos,
						map: map,
						title: 'Click for Directions',
						icon:"http://www.traceelliot.com/dealers/includes/pins/" + (this.dlrPAS ? "gold_final.png" : "plain_small.png")
					}),
					dealerTextContent = template.call(this),
					infoWindow = new google.maps.InfoWindow({
						content: dealerTextContent,
						disableAutoPan: true
					});
					google.maps.event.addListener(marker, 'mouseover',function(){
						infoWindow.open(map, marker);
						// remove close button after infoWindow is created and added
						//setTimeout(function(){
						//	$("#map_canvas").find('img[src*="iw_close.gif"]').remove();
						//},20);
					});
					google.maps.event.addListener(marker, 'mouseout',function(){
						infoWindow.close();
					});
					google.maps.event.addListener(marker, 'click',function(){
						map.pv.directions.route({
							origin: map.pv.center,
							destination: markerPos,
							travelMode: "DRIVING"
						},function(result){
							map.pv.directionPanel.innerHTML = dealerTextContent;
							map.pv.directionPanel.style.display = "block";
							map.pv.removeAllDirections();
							marker.directions = new google.maps.DirectionsRenderer({
								map: map, 
								directions: result,
								panel: map.pv.directionPanel,
								suppressMarkers: true
							});
						});
					});
					map.pv.markerArray.push(marker);
				});
				var latlngbounds = new google.maps.LatLngBounds()
				var latlngArr = $.map(map.pv.markerArray,function(obj){
					return obj.getPosition();
				});
				for ( var i = 0; i < latlngArr.length; i++ ) {
					latlngbounds.extend( latlngArr[ i ] );
				}
				map.fitBounds(latlngbounds);
			});
		}
		
		function updateMap() {
			map.pv.removeAllMarkers();
			map.pv.markerArray = [];
			if (map.pv.areaCircle) {
				map.pv.areaCircle.setMap(null);	
			}
			map.pv.areaCircle = null;
			
			map.pv.geocoder.geocode({
				"address":$('input:text[name="location"]').val()
			},function(data){
				if (!data.length) return;
				success({ coords: { latitude: data[0].geometry.location.lat(), longitude: data[0].geometry.location.lng()}});
			});
			
		}
		$.extend(map,{
			pv: {
				markerArray: [],
				areaCircle: null,
				userLocation: {
					latitude: 38.68551,
					longitude: -98.789062
				},
				removeAllMarkers: function(){
					for (var i = 0; i < this.markerArray.length; i++) {
						if (this.markerArray[i].directions)	this.markerArray[i].directions.setMap(null);
						this.markerArray[i].setMap(null);
					}
				},
				removeAllDirections: function(){
					for (var i = 0; i < this.markerArray.length; i++) {
						if (this.markerArray[i].directions)	this.markerArray[i].directions.setMap(null);
					}
				},
				geocoder: new google.maps.Geocoder(),
				directions: new google.maps.DirectionsService(),
				directionPanel: document.getElementById('directions'),
				center: null
			}
		});

		var throttle;
		$('input:text[name="location"]').bind('keyup', function(){
			clearTimeout(throttle);
			throttle = setTimeout(function(){
				updateMap.call(null);
			},500);
		});
		$('input:radio[name="dealerType"]').change(updateMap);

		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(success);
		}
	}
});
