XLR = {
	THUMB_COUNT: 6,
	THUMB_WIDTH: 145,
	HOME_MARKER: new google.maps.MarkerImage('http://google-maps-icons.googlecode.com/files/home.png'),
	STORE_MARKER: new google.maps.MarkerImage('xlear_marker.png'),
	origin: {},
	stores: [],
	geo: new google.maps.Geocoder()
};

XLR.initVideoNav = function(username)
{
	$.ajax({
		url: 'http://gdata.youtube.com/feeds/api/playlists/2775741D426B46BB?v=2&alt=json',
		dataType: 'jsonp',
		success: XLR.updateVideoList
	});
}

XLR.updateVideoList = function(data, status, xhr) {
    var list = $('#video-list').html('');
    window.testdata = data;
    $.each(data.feed.entry, function(i, vid) {
		var href=vid.link[0].href;
		var start = href.indexOf('=') + 1;
		var stop = href.indexOf('&');
		var id = href.substring(start, stop);
		var title = vid.title.$t;
		
        list.append(
            $('<li />')
                .attr('data-id', id)
                .html(
                     $('<img />')
                          .attr('src', 'http://i2.ytimg.com/vi/' + id + '/default.jpg'))
						.click(function() {
							XLR.player.cueVideoById(id);
							$('#facebook-link').attr('href', 'http://www.facebook.com/sharer.php?u=http%3A%2F%2Fyoutu.be%2F' + id);
							$('#twitter-link').attr('href', 'http://twitter.com/share?url=http%3A%2F%2Fyoutu.be%2F' + id + '&via=' + title);
							$('#video-title').html('<span class="bracket">[&nbsp;</span> ' + title + ' <span class="bracket">&nbsp;]</span>');
						})); 
    });
	
	list.prepend(list.children().last().clone(true));
	list.append(list.children().slice(1,XLR.THUMB_COUNT+1).clone(true));

    list.css({
        left: - XLR.THUMB_WIDTH,
        width: list.children().length * XLR.THUMB_WIDTH
    });

	XLR.initClickHandlers();
}

XLR.initClickHandlers = function()
{
	var list = $('#video-list');
	
	$('#video-right').click(function()
	{
		var w = XLR.THUMB_WIDTH;
		list.animate({left: '-=' + w}, 400, function()
		{
			if (-parseInt(list.css('left')) >= list.width() - w * XLR.THUMB_COUNT)
			{
				list.css('left', -w + 'px');
			}
		});
	});
	
	$('#video-left').click(function()
	{
		var w = XLR.THUMB_WIDTH;
		list.animate({left: '+='+w}, 400, function()
		{
			if (parseInt(list.css('left')) >= 0)
			{
				list.css('left', -list.width() + w * (XLR.THUMB_COUNT + 1) + 'px');
			}
		});
	});
	
//	$('#video-list li').click(function()
//	{
//		XLR.player.cueVideoById(this.getAttribute('data-id'));
//		document.getElementById('facebook-link').href = 'http://www.facebook.com/sharer.php?u=http%3A%2F%2Fyoutu.be%2F'+this.getAttribute('data-id');
//		document.getElementById('twitter-link').href = 'http://twitter.com/share?url=http%3A%2F%2Fyoutu.be%2F'+this.getAttribute('data-id')+'&via=Xylitol_Experts&text=Check%20out%20this%20cool%20video';
//		
//		document.getElementById('video-title').text = '[' + title.$t + ']';
//	});
};

XLR.initVideoPlayer = function(data, status, xhr)
{
	var params = {allowScriptAccess: 'always',
				  			  wmode: 'opaque',
					allowfullscreen: 'true'};
	var atts = {id: 'youtube-player'};
	initialVideoId = 'nr_P38gZ6ug';
	swfobject.embedSWF('http://www.youtube.com/e/'+initialVideoId+'?enablejsapi=1&playerapiid=video-player', 'video-player', 425, 356, '8', null, null, params, atts);
	document.getElementById('facebook-link').href = 'http://www.facebook.com/sharer.php?u=http%3A%2F%2Fyoutu.be%2F'+initialVideoId;
	document.getElementById('twitter-link').href = 'http://twitter.com/share?url=http%3A%2F%2Fyoutu.be%2F'+initialVideoId+'&via=Xylitol_Experts&text=Check%20out%20this%20cool%20video';
	XLR.player = document.getElementById('youtube-player');
}



//Locator Map
XLR.runLocationQuery = function(event) {
	event.preventDefault();
	event.stopPropagation();
	var address = $('#location-form input').val();
	XLR.geo.geocode({address:address}, function(results, status) {
		if (results.length == 0) {
			//TODO handle zero results
		}
		else {
			var loc = results[0].geometry.location;
			XLR.updateCurrentLocation(loc.lat(), loc.lng());
		}
	});
};

XLR.updateMap = function() {
	XLR.bounds = new google.maps.LatLngBounds(XLR.origin.location, XLR.origin.location);
	
	for (var i = 0; i < 10 && i < XLR.stores.length && parseInt(XLR.stores[i].distance) < 50; i++) {
		XLR.bounds.extend(XLR.stores[i].location);
	
	}
	XLR.map.fitBounds(XLR.bounds);
};

XLR.clearAllStores = function() {
	for (var i = 0; i < XLR.stores.length; i++) {
		google.maps.event.clearListeners(XLR.stores[i].marker, 'click');
		XLR.stores[i].marker.setMap(null);
	}
};

XLR.hideAllBubbles = function() {
	for (var i = 0; i < XLR.stores.length; i++) {
		XLR.stores[i].info.close();
	}
};

XLR.handleRecordsResponse = function(data, status, xhr) {
	XLR.clearAllStores();
	XLR.stores = data;
	var html = '';
	
	for (var i = 0; i < data.length; i++) {
		var div = '<div class="results" data-index="' + i + '">';
		div += '<span class="store-name">' + data[i].customer_name + '</span>';
		div += '<span class="store-phone">' + data[i].phone + '</span>';
		div += '<span class="store-street">' + data[i].street + '</span>';
		div += '<span class="store-city">' + data[i].city + ', ' + data[i].state + ' ' + data[i].postal_code + '</span>';
		div += '<span class="store-distance">distance: ' + data[i].distance + '</span>';
		div += '</div>';
		
		data[i].location = new google.maps.LatLng(data[i].latitude, data[i].longitude);
		data[i].marker = new google.maps.Marker({
			map: XLR.map,
			position: data[i].location,
			icon: XLR.STORE_MARKER,
			visible: true
		});
		data[i].info = new google.maps.InfoWindow({
			content: div,
			position: data[i].location
		});
		
		google.maps.event.addListener(data[i].marker, 'click', function(store) {
			return function() {
				XLR.hideAllBubbles();
				store.info.open(XLR.map, store.marker);
			};
		}(data[i]));
		
			html += div;
		
		
		// View All option to show all results
		
	}
	
	$('#store-results').html(html);
	
	$('#store-results div').click(function() {
		var i = this.getAttribute('data-index');
		XLR.hideAllBubbles();
		XLR.stores[i].info.open(XLR.map, XLR.stores[i].marker);
	});
	
	XLR.updateMap();
};

XLR.updateCurrentLocation = function(lat, lng) {
	XLR.origin.location = new google.maps.LatLng(lat, lng);
	
	if (XLR.origin.marker) {
		XLR.origin.marker.setPosition(XLR.origin.location);
	}
	else {
		XLR.origin.marker = new google.maps.Marker({
			map: XLR.map,
			position: XLR.origin.location,
			icon: XLR.HOME_MARKER,
			visible: true
		});
	}
	
	$.ajax({
		url: 'http://xlear.mapistry.net/libs/ws/records.fcg?json=1&nearest=20&clat=' + lat + '&clng=' + lng + '&page=0',
		dataType: 'jsonp',
		success: XLR.handleRecordsResponse
	});
};

XLR.initEventHandlers = function() {
	$('#location-form').submit(XLR.runLocationQuery);
};

XLR.initMap = function() {
	var canvas = document.getElementById('map-canvas');
	var options = {
		zoom: 3,
		center: new google.maps.LatLng(40, -95),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	XLR.map = new google.maps.Map(canvas, options);
	
	$.ajax({
		url: 'http://xlear.mapistry.net/geo_ip/?json=1',
		dataType: 'jsonp',
		success: function(data) {
			XLR.updateCurrentLocation(data.latitude, data.longitude);
		}
	});
};

XLR.init = function()
{
	XLR.initVideoPlayer();
	XLR.initVideoNav('XlearInc');
	XLR.initMap();
	XLR.initEventHandlers();
	
	$('#btn-viewAll').toggle(
		function(){$('#store-results').addClass('expanded')},
		function(){$('#store-results').removeClass('expanded')}
		);
	
	var storeList = $('#store-results');
	var scrollPast = storeList.offset().top;
	$(window).scroll(function() {
		if($(this).scrollTop() > scrollPast - 40 && storeList.hasClass('expanded')) {
			$('#map-canvas').css({position: 'fixed', top: 40});
		} else {
			$('#map-canvas').css({position: 'relative', top: 1});
		};
	});
	/*
	var startInterval = function() { 
		var items = [];
		var currentItem = 0;
		return setInterval(function() {
			$('#carousel-container').scrollTo('#slider1 li#' + items[currentItem] + '-content', 500);
			$('.product').removeClass('current');
			$('#thumbnav li#' + items[currentItem]).addClass('current');
				
			currentItem++;
			if(currentItem >= items.length) { 
				currentItem = 0;
			}
		}, 10000);
	};
	
	var intervalId = false;
	
	// Swap out top section with associated content
	$('.product').click(function() {
		$('.product').removeClass('current');
		$(this).addClass('current');
		$('#carousel-container').scrollTo('#slider1 li#' + this.id + '-content', 500);
		if(intervalId) { 
			clearInterval(intervalId);
			intervalId = startInterval();
		}
	});
	
	intervalId = startInterval();
	*/
}

$(document).ready(XLR.init);
