/* Author: Kevin Boudloche
*/

(function ($){
	
	function navInit(){
		$("#leftside li").hover(function(){
			$(this).toggleClass('hover');
		});
	}

	function contentInit(){
		$('#infiniteCarousel').infiniteCarousel();
		$('a[rel="lightbox"]').lightBox({
			overlayOpacity: "0.0",
			imageBtnClose: "/img/gallery/lightbox-btn-close.gif",
			imageBtnNext: "/img/gallery/lightbox-btn-next.gif",
			imageBtnPrev: "/img/gallery/lightbox-btn-prev.gif",
			imageBlank: "/img/gallery/lightbox-blank.gif",
			imageLoading: "/img/gallery/lightbox-blank.gif"
		});
		
		$('#mailinglist').submit(function(){
			$.post('/includes/maillist.cfm',$(this).serializeArray(),function(){
				$('#mailinglist').text('Thank you for joining our newsletter.');
			});
			return false;
		});

		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("");
		};
		if (document.getElementById("map_canvas")) {
			// code for dealer locator
			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 '<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 />' : "");
					}
					$.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:"/img/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);
						});
						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);
			}
		}
		var img_viewer = $("#image_viewer");
		if (img_viewer.length) {
			img_viewer.pvprod({
				rightwidth : 125,
				thumbwidth : 100,
				totalwidth : 628,
				totalheight: 300,
				source : "/includes/getImages.cfm?item=" + img_viewer.attr('data-item-number')
			});	
		}
	}

	$(document).ready(navInit);
	$(document).ready(contentInit);

})(jQuery);
