if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
	addEventListener("load", function() {
		setTimeout(hideURLbar, 0);
	}, false);
}

function hideURLbar() {
	window.scrollTo(0, 1);
}

function getSpinner() {
	return '<div id="spinner">Loading...</div>';
}

function track(code) {
	// omniture
	if (s) {
		s.pageName = ttl +'_>_'+ code;
		s.t();
	}
	// google
	if (pageTracker) {
		pageTracker._trackPageview(document.title + " : " + code);
	}
}





var Menu = Menu || {};
var Menu = {
	
	isOpen: false,
	
	show: function() {
		hideURLbar();
		$('#menu').show();
		$('#menuButton').html('Close');
		this.isOpen = true;
	},
	
	hide: function() {
		$('#menu').hide();
		$('#menuButton').html('Menu');
		this.isOpen = false;
	},
	
	toggle: function() {
		if (this.isOpen) {
			this.hide();
		} else {
			this.show();
		}
	}
};




var Locator = Locator || {};
var Locator = {
	
	zipCode: "",
	
	init: function() {
		if (navigator.geolocation && navigator.userAgent.match(/WebView/i) == null) {
			//this.findLocation();
		}
	},
	
	findLocation: function() {
		navigator.geolocation.getCurrentPosition(this.completeHandler, this.errorHandler);
	},
	
	geoLocation: function() {
		
	},
	
	completeHandler: function(location) {
		$('#results').html(getSpinner());
		$('#locatorPanel').slideUp();
		
		if (JAVA_URL) {
			Locator.displayResults(location.coords.latitude, location.coords.longitude);
		} else {
			var self = this;
			$('#results').load(BASE_URL+'/dealersearch', { lat:location.coords.latitude, lng:location.coords.longitude, accuracy:location.coords.accuracy }, function() { Locator.enableTabs(); });
		}
	},
	
	errorHandler: function(error) {
		$('#results').html('<p>Your location could not be determined. Please enter your zip code.</p>');
	},
	
	add: function(number) {
		if(!isNaN(number) && this.zipCode.length < 5)
		{
			this.zipCode += number;
		}
		this.updateZipField();
	},
	
	remove: function() {
	
		if (this.zipCode.length > 0)
		{
			this.zipCode = this.zipCode.substring(0, this.zipCode.length - 1);
			
			if (this.zipCode.length == 0) {
				this.updateZipField('Enter Zip Code');	
			} else {
				this.updateZipField();
			}
		}
	},
	
	updateZipField: function(label) {
		if (label != null) {
			$('#number').html(label);
		} else {
			$('#number').html(this.zipCode);
		}
	},
	
	displayResults: function(lat, lng) {
		var self = this;
		$.getJSON(JAVA_URL +'/dealersearch.jsp?lat='+ lat +'&lng='+ lng +'&callback=?',
			function(data) {
				var resultsStr = 'Results';
				if (self.zipCode) {
					resultsStr += ' for '+ self.zipCode;
				}
				$('#results').html('<h3 class="sectiontall"><a href="javascript:void(0)" onclick="Locator.reset();">Locator</a> | '+ resultsStr +'</h3>'
						+ '<ul id="resultTabs" class="tabs half"><li><a href="#dealers">Dealers</a></li><li><a href="#demos"><span class="shadow"></span>Demos</a></li></ul><div class="clear"></div>');
								
				var str = '<div id="dealers" class="tabContent">';
				
				$.each(data.dealers, function(i, dealer) {
					str +=
						'<div class="dealer">'
						+'<div class="address">'
						+'<p><strong>'+ dealer.name +'</strong><br />'
						+ dealer.address1 +' '+ dealer.address2 +'<br />'
						+ dealer.city +', '+ dealer.state +' '+ dealer.zipCode;
					if (dealer.phone.length > 9) {
						str += '<br />'+ dealer.phone;
					}
						str += '</p>'
					if (dealer.distance) {
						str += '<div class="distance">Approx. '+ dealer.distance +' Away</a></div>';
					}
						str += '</div><div class="buttons">';
					if (dealer.phone.length > 9) {
						str += '<a href="tel:'+ dealer.phone +'" class="callButton">Call</a>';
					}
						str += '<a href="http://maps.google.com/maps?q='+ escape(dealer.address1 +' '+ dealer.state +' '+ dealer.zipCode)
							+'&iwloc=A&hl=en" class="mapButton" target="_blank">Map</a></div></div>';
											 
				});
				
				str += '</div><div id="demos" class="tabContent">';
				
				$.each(data.demos, function(i, demo) {
					str +=
						'<div class="dealer">'
						+'<div class="address">'
						+'<p><strong>'+ demo.date +'<br />'+ demo.startTime +' to '+ demo.endTime +'</strong></p>'
						+'<p>'+ demo.name +'<br />'
						+ demo.address1 +' '+ demo.address2 +'<br />'
						+ demo.city +', '+ demo.state +' '+ demo.zipCode;
					if (demo.phone.length > 9) {
						str += '<br />'+ demo.phone;
					}
						str += '</p>'
					if (demo.distance) {
						str += '<div class="distance">Approx. '+ demo.distance +' Away</a></div>';
					}
						str += '</div><div class="buttons">';
					if (demo.phone.length > 9) {
						str += '<a href="tel:'+ demo.phone +'" class="callButton">Call</a>';
					}
						str += '<a href="http://maps.google.com/maps?q='+ escape(demo.address1 +' '+ demo.state +' '+ demo.zipCode)
							+'&iwloc=A&hl=en" class="mapButton" target="_blank">Map</a></div></div>';
											 
				});
				
				str += '</div>';
				$('#results').append(str);	
				self.enableTabs();

			});
	},
	
	enter: function() {
		if (this.zipCode.length == 5) {					

			$('#results').html(getSpinner());
			$('#locatorPanel').slideUp();

			var self = this;
			if (JAVA_URL) {
				$.getJSON('http://maps.google.com/maps/geo?q='+ this.zipCode +'&output=json&oe=utf8&sensor=false&key='+ GOOGLE_MAPS_API_KEY +'&callback=?',
					function(data) {
						var lng = data.Placemark[0].Point.coordinates[0];
						var lat = data.Placemark[0].Point.coordinates[1];
						
						self.displayResults(lat, lng);
						
					}
				);
				
			} else {
				var self = this;
				$('#results').load(BASE_URL+'/dealersearch', { zip:this.zipCode }, function() { self.enableTabs() });
			}
		} else if (this.zipCode == '000') {
			alert(navigator.userAgent);
		} else {
			alert('Please enter a valid zip code.');
		}
	},
	
	enableTabs: function() {
		$("#resultTabs").tabs(".tabContent");
	},
	
	reset: function() {
		hideURLbar();
		this.zipCode = '0';
		this.remove();
		$('#locatorPanel').slideDown();
	}
	
}




var Gallery = Gallery || {};
var Gallery = {
	
	imageList: [],
	imageListHoriz: [],
	currentImage: 0,
	active: false,
	
	init: function() {
		if (this.imageList.length <= 1) {
			$('#gallery .prev').hide();
			$('#gallery .next').hide();
		}
		this.active = true;
		this.showImage(this.currentImage);
	},
	
	showImage: function(index) {
		this.currentImage = index;
		var image = this.imageList[index];
		if ($('#main').is('.horizontal')) {
			image = this.imageListHoriz[index];
		}
			
		var img = new Image();
		$('#gallery .imageContainer').html(getSpinner());
		$(img).load(function () {
			$(this).hide();
			$('#gallery .imageContainer').html(this);
			$(this).fadeIn('slow');
		})
		
		.attr('src', image);		
		
	},
	
	prev: function() {
		this.showImage(this.count(-1));
	},
	
	next: function() {
		this.showImage(this.count(1));
	},
	
	refresh: function() {
		this.showImage(this.currentImage);
	},
	
	count: function(offset) {
		this.currentImage += offset;
		if (this.currentImage < 0) {
			this.currentImage = this.imageList.length-1;
		}
		if (this.currentImage > this.imageList.length-1) {
			this.currentImage = 0;
		}
		return this.currentImage;
	}
};



function comparator(a, b)
{
	return b.datesort - a.datesort;
}

function initToggles()
{
	$('.toggle .title').click(function() {
								
		if ($(this).is('.open')) {
			$(this).find('.twisty').removeClass('twistOpen').addClass('twistClose');
			$(this).find('.twisty').attr({'src':BASE_URL+'/images/twisty_down.png'});
			$(this).parent().find('.toggleContent').slideUp();
			$(this).removeClass('open');
		} else {
			$(this).find('.twisty').removeClass('twistClose').addClass('twistOpen');
			$(this).find('.twisty').attr({'src':BASE_URL+'/images/twisty_up.png'});
			$(this).parent().find('.toggleContent').slideDown(function() { /* $.scrollTo($('#bottom')); */ });
			$(this).addClass('open');
		}
							 
	});
	
	$('.toggle .title.open .twisty').attr({'src':BASE_URL+'/images/twisty_up.png'});
	$('.toggle .title.open').parent().find('.toggleContent').slideDown();
}


function twitterFeed(refreshRate) {
	if (refreshRate == null) {
		refreshRate = 5000;
	}
	this.init();
	
	if (refreshRate > 0) {
		var self = this;
		setInterval(function(){ self.init(true); }, refreshRate);
	}
};

twitterFeed.prototype = {
	feedList: ['37360915','48871053','32453930','21257006','41896109','50709355','40114528'],
	feed: [],
	count: 0,
	initialLoadTotal: 100,
	i: 0,
	
	init: function(refreshFeed) {
		var self = this;
		$.getJSON('http://twitter.com/statuses/user_timeline/'+ this.feedList[self.i] +'.json?callback=?',
			function(data) {
				if (refreshFeed == true) {
					$('#twitterFeed #tweets').empty();
					self.count = 0;
				}
				$.each(data, function(i, item) {
					item.datesort = new Date(Date.parse(item.created_at)).getTime();
					self.feed.push(item);
				});
				
				if (self.i < self.feedList.length-1) {
					self.i++;
					self.init();
				} else {
					self.feed.sort(comparator);
					self.populate(self.initialLoadTotal);
				}
			}
		);
	},
	
	populate: function(total) {
		if(this.feed.length > 0) {
			$('#twitterFeed #tweets').html('');
			var self = this;
			$.each(this.feed, function(i, item) {
				var date = self.parseDate(item.created_at);
				
				$('#twitterFeed #tweets').append(
				 '<div class="tweet"><div class="image"><a href="http://www.twitter.com/'+ item.user.screen_name +'" class="title" target="_blank"><img src="'+ item.user.profile_image_url +'" /></a></div>'
				+'<div class="text"><p><a href="http://www.twitter.com/'+ item.user.screen_name +'" class="title" target="_blank">'+ item.user.name +'</a><br />'+ self.parseText(item.text) +'</p>'
				+'<a href="http://twitter.com/'+ item.user.screen_name +'/status/'+ item.id +'" class="date" target="_blank">'+ date.dateString +' '+ date.timeString +'</a></div></div>'
				);
				self.count++;
				if (self.count == total || i == self.feed.length-1) {
					return false;
				}
			});
		} else {
			$('#twitterFeed #tweets').append('<p>No Tweets were found</p>');
		}
	},
	
	parseText: function(text) {
		return text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) { return url.link(url); });
	},
	
	parseDate: function(date) {
		var dateObj = {};
		var d = new Date(Date.parse(date));
		var hour = d.getHours();
		if (hour > 12) hour -= 12;
		
		dateObj.dateString = (d.getMonth()+1) +'/'+ d.getDate() +'/'+ d.getFullYear().toString();
		dateObj.timeString = hour +':'+ this.formatNumber(d.getMinutes()) + (d.getHours() < 12 && d.getHours() > 0 ? ' AM' : ' PM');
		
		return dateObj;
	},
	
	formatNumber: function(num) {
		return num < 10 ? '0'+num : num;	
	}
};











$(function() {
		   
	$('#menu .overlay').click(function() {
		Menu.hide();
	});
	$("#productTabs").tabs(".tabContent", { history: true, onClick: hideURLbar });
	initToggles();
		   
});

