$(window).load(function() {	
	$('#browse_map').trackmytour({
		showPolylines: false,
		getBalloonText: function(point) {		
			var templates = {
				commentBalloonTemplate: "\
					<div class='#{className}'> \
						<span class='floatRight'>Day #{day}</span> \
						<b>#{timestamp}</b> \
						<hr/> \
						<div class='clearfix'>#{comment}</div> \
						<hr/> \
						<p class='faint'>Posted: #{timesince} ago</p> \
						<p><a href='/#{track_id}' target='_blank'>View this tour...</a></p> \
					</div>",
				balloonTemplate: "\
					<div class='#{className}'> \
						<span class='floatRight'>Day #{day}</span> \
						<b>#{timestamp}</b> \
						<hr/> \
						<p class='faint'>Posted: #{timesince} ago</p> \
						<p><a href='/#{track_id}' target='_blank'>View this tour...</a></p> \
					</div>"
			};
		
			if (point.comment.stripTags().length == 0) {
				bText = $.template(templates.balloonTemplate, point);
				bText = $.template(bText, {
					className: 'balloon commentBalloon'
				});
			} else {
				bText = $.template(templates.commentBalloonTemplate, point);
				bText = $.template(bText, {
					className: 'balloon commentBalloon'
				});
			};
	
			return bText;
		}
	});

	var maxhits = 60;
	var days = $.getURLParam('days', 7);
	var tour_type = $.getURLParam('type', 'all'); // $(this).attr('rel');
	// var query_type = 'recent';
	var itemSize = 5;

	var scroll = $(".scrollable").scrollable({
		/* size: itemSize, */
		api: true
	});
		
	$('.prevPage').click(function() {
		scroll.move( -Math.min(itemSize, scroll.getIndex()) );
	});
	
	$('.nextPage').click(function() {
		scroll.move(itemSize);
	});

	function load() {
		$('#browse_map').data('gmap').removeMarkers();
	
		$.getJSON('/fetch/', {
			days: days,
			maxhits: maxhits,
			// query_type: query_type,
			tour_type: tour_type
		}, function(data) {
			scroll.begin();
		
			var $items = $('div.items').empty();
			
			$.each(data, function() {
				var $item = $('<div></div>').addClass('item').attr('id', 'wp' + this.id ); // .appendTo($items);

				if (!this.img) {
					this.img = "/static/images/no-photo.gif";
					this.w = 90;
					this.h = 90;
				};
				
				$('<img>').attr('src', this.img).appendTo($item).scaleToFill({
					scaleWidth: 90,
					scaleHeight: 90,
					imageWidth: this.w,
					imageHeight: this.h
				})
				.parent().css('float','left');
				
				$('<img>').addClass('typeIcon').attr('src', this.tour_type_icon).appendTo($item);
				$('<img>').addClass('typeIcon').attr('src', this.type_icon).attr('title', this.type).appendTo($item);
				$('<p></p>').addClass('trackName').css({'clear':'both'}).html(this.track_name).appendTo($item);
				$('<p></p>').css({'text-align':'right'}).html('by ' + this.user).appendTo($item);
				$('<p></p>').addClass('bottomRight').addClass('faint').html(this.timesince + ' ago').appendTo($item);
				
				scroll.addItem($item);				
			});
	
			$('p.trackName').ellipsis();
			
			// scroll.reload() doesn't update the nextPage correctly.. fix it here.

			if ( $('.item').size() <= itemSize ) {
				$('.nextPage').addClass('disabled');					
			} else {
				$('.nextPage').removeClass('disabled');
			};
			
		      $('#browse_map').data('gmap').addMarkers(data);
		});
	};

	// Why is this called twice?!?!
	$('div.item').live('click', function() {
		$('div.items div.active').removeClass("active");
		var $this = $(this).addClass("active");
		scroll.seekTo( Math.max($this.index()-2,0) );
	});
	

      $('#days a').click(function() {
		$('#days a.selected').removeClass('selected');
		days = $(this).addClass('selected').attr('rel');
		load();
		return false;
	});

	$('#tour_types input').click(function () {
		$('#tour_types input').css('opacity', 0.4);
		tour_type = $(this).css('opacity', 1).attr('rel');
		load();
		return false;
	});
	
	$('#tour_types a').click(function () {
		$('#tour_types input').css('opacity', 1);
		tour_type = $(this).attr('rel');
		load();
		return false;
	});
	
	// highlight the days
	$('#days a[rel="' + days + '"]').addClass('selected');
	
	if ( $('input[rel="' + tour_type + '"]').click().size() == 0 ) {
	   $('#tour_types a').click();
	}; 
});


jQuery.extend({
	getURLParam: function(paramName, defaultValue) {
		var params = String(document.location).toLowerCase()	
		var value = $.toQueryParams(params)[paramName.toLowerCase()]; 
		return value || defaultValue;
	},

	/**
	 * The inverse of the jQuery.param() function.  Returns the URL parameters as a Javascript Object
	 */
	toQueryParams: function(txt) {
		var s = txt || String(document.location)
		var paramsList = s.substring(s.indexOf('?') + 1).split('#')[0].split('&')
		var params = {},
			key, value, pair;

		for (var i = 0; i < paramsList.length; i++) {
			pair = paramsList[i].split('=');
			key = decodeURIComponent(pair[0]);
			value = (pair[1]) ? decodeURIComponent(pair[1]) : undefined;

			if (params[key]) {
				if (typeof params[key] == "string") {
					params[key] = [params[key]];
				}
				params[key].push(value);
			} else {
				params[key] = value;
			}
		}

		return params;
	}
});

jQuery.fn.extend({
	scaleToFill: function(options) {
		options = $.extend({
			scaleWidth: 100,
			scaleHeight: 100,
			imageWidth: 100,
			imageHeight: 100	
		}, options)
			
		return this.each(function() {
			var isPortrait = (options.imageWidth <= options.imageHeight);
			
			if ( isPortrait ) {
				newImageWidth = options.scaleWidth;
				newImageHeight = newImageWidth * (options.imageHeight / options.imageWidth);
			} else {	
				newImageHeight = options.scaleHeight;
				newImageWidth = newImageHeight * (options.imageWidth / options.imageHeight);			
			};
		
			$(this).css({
				width: newImageWidth,
				height: newImageHeight
			}).wrap('<div></div>').parent().css({
				width: options.scaleWidth,
				height: options.scaleHeight,
				margin: 0,
				padding: 0,
				overflow:'hidden'
			});  
		});
	}
});
