/* Author: 

*/

// Hack to get the markes for the directions.
google.maps.Map.prototype.getMarkers = function() {
    return this.markers || [];
};
google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;
google.maps.Marker.prototype.setMap = function(map) {
  if (map) {
  	if (!map.markers) {
  		map.markers = [];
  	}
  	
  	// Modify the icon as they're being added to the map!
	if (this.getIcon) {
		var icon = this.getIcon();
		for (var prop in icon) {
			if (!icon[prop] || !icon[prop].indexOf) continue;
			if (icon[prop].indexOf('marker_greenA') > -1) {
				this.setIcon('/css/i/1.png');
			}
			if (icon[prop].indexOf('marker_greenB') > -1) {
				this.setIcon('/css/i/2.png');
			}
			if (icon[prop].indexOf('marker_greenC') > -1) {
				this.setIcon('/css/i/3.png');
			}
			if (icon[prop].indexOf('marker_greenD') > -1) {
				this.setIcon('/css/i/4.png');
			}
		}
	}

  	
      map.markers[map.markers.length] = this;
  } else {
  	// remove it?
  }
  this._setMap(map);
}

function formatSuggestionText(input) {
	return input.replace(/`([^`]*)`/ig, '<em>\$1</em>');
}

function contextualDistance(meters,units) {
    switch(units) {
        default:
        case 'km':
            if(meters < 1) return 'nearby';
            if(meters < (100)) return ' < 100 m';
            if(meters < (500)) return ' < 500 m';
            if(meters < (1000)) return '< 1 km';
            return (meters / 1000).toFixed(2) + ' km';
            break;
        case 'mi':
            var yards = 1.0936133 * meters;
            if(yards < 1) return 'nearby';
            if(yards < (100)) return ' < 100 yd';
            if(yards < (1760/2)) return ' < 1/2 mi';
            if(yards < (1760)) return '< 1 mi';
            return (yards / 1760).toFixed(2) + 'mi';
            break;
        
    }
}

function updateUnits( units ) {
    $.cookie('units', units, {expires: 7, path: '/'});
    $('.distance[data-meters]').each(function(){
        var e = $(this);
        e.html(contextualDistance(e.data('meters'),units));
    });
    
}


jQuery(document).ready(function($) {

    // Prepare
    var History = window.History; // Note: We are using a capital H instead of a lower h
    if ( History.enabled ) {
        // Bind to StateChange Event
        History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
            var State = History.getState(); // Note: We are using History.getState() instead of event.state
            
            switch (State.data.type) {
                case "location-change":
                                
                    $.cookie('latitude', State.data.latitude, {expires: 7, path: '/'});
                    $.cookie('longitude', State.data.longitude, {expires: 7, path: '/'});
                    $.cookie('address', State.data.name, {expires: 7, path: '/'});
                    $.cookie('units', State.data.units, {expires: 7, path: '/'});
                    
                    if (State.data.name) {
                        $('#influencers').data('location-name',State.data.name);
                        updateInfluencerText('Your location is <em>%LOCATION%</em>', State.data.name);
                    } else {
                        updateInfluencerText('Your location is unknown');
                    }
                    
                    if ($('#influencers').data('location-name')) {
                       	$('#suggestions-wrapper').html('<div id="page-loading">Thinking about great local suggestions around <em>' + $('#influencers').data('location-name') + '</em></div>');
                    } else {
                       	$('#suggestions-wrapper').html('<div id="page-loading">Thinking about great local suggestions.</div>');                    
                    }            
                case "suggestions":
                    if (LOZZAL_BASE == 'similar' || LOZZAL_BASE == 'focus') LOZZAL_BASE = 'all';
                    
                    if(!LOZZAL_THEME_ID) LOZZAL_THEME_ID = 100;
                    $.cookie('latitude', State.data.latitude, {expires: 7, path: '/'});
                    $.cookie('longitude', State.data.longitude, {expires: 7, path: '/'});
                
                    updateSuggestionList(
                        State.data.latitude,
                        State.data.longitude,
                        State.data.hash,
                        State.data.offset,
                        State.data.limit,
                        LOZZAL_THEME_ID
                    );
                    break;
                case "similar":
                
                    $('body').animate({scrollTop:0}, 'slow');
                    
                    LOZZAL_BASE = 'similar';
                    
                    $.cookie('latitude', State.data.latitude, {expires: 7, path: '/'});
                    $.cookie('longitude', State.data.longitude, {expires: 7, path: '/'});
                    
                    updateSuggestionSimilar(
                        State.data.latitude,
                        State.data.longitude,
                        State.data.id,
                        State.data.hash,
                        State.data.offset,
                        State.data.limit,
                        History.extractId(State)
                    );
                    break;
                case "focus":

                    $('body').animate({scrollTop:0}, 'slow');

                    LOZZAL_BASE = 'focus';
                    
                    $.cookie('latitude', State.data.latitude, {expires: 7, path: '/'});
                    $.cookie('longitude', State.data.longitude, {expires: 7, path: '/'});

                    if(!State.data.name && State.data.hash == null) {
                        $('#suggestions-wrapper').html('<div id="page-loading">Thinking about great local suggestions.</div>');
                        geocodeLatLng(State.data.latitude, State.data.longitude);
                    }
                    
                    updateSuggestionFocus(
                        State.data.latitude,
                        State.data.longitude,
                        State.data.id,
                        State.data.hash,
                        State.data.offset,
                        State.data.limit,
                        History.extractId(State)
                    );
                    break;
            }
            
            /*
            if (State.url.indexOf('/' + LOZZAL_BASE + '/') >= 0) {
                var allVars = State.url.split('/');
                log(allVars);
                //updateSuggestionList(hash,offset,limit)
                if (allVars[5] && !$('#suggestions-wrapper').hasClass('loading')) {
                    //updateSuggestionList(allVars[5],allVars[6],25);
                }
            } else if (State.url.indexOf('/similar/') >= 0) {
                var allVars = State.url.split('/');
                log(allVars);
                // /simlar/id/lat,lng/hash/offset
                //updateSuggestionSimilar(id,hash,offset)
                if (allVars[5] && !$('#suggestions-wrapper').hasClass('loading')) {
                    //updateSuggestionSimilar( allVars[5], allVars[7], allVars[8] )
                }
            }
            */
            
        }); 
    }

	/*********************************
	 * Init templates
	 *********************************/
  	
	$.template("tmpl-loading", '<p class="loading"><span>${message}</span></p>');
	
	$.template("tmpl-default", '<p>${message}</p>');


    $.template("tmpl-suggestions", '\
    <ul>\
    {{each suggestions}}\
        <li class="bubble suggestion" data-id="${id}">\
          	<p><a href="i/${id}">{{html formatSuggestionText(text)}}</a><span class="distance" data-meters="${dist}">${dist}</span></p>\
          	<a href="/similar/${id}/${influencers.lat},${influencers.lon}" class="similar" data-id="${id}">More Ideas Like This</a>\
        </li>\
    {{/each}}\
    </ul>\
    <nav>\
        <ul>\
    <!--<li class="less"><a class="button big highlight" href="#">Less</a></li>-->\
    <li class="more"><a class="button big highlight" href="#">More</a></li>\
    </ul>\
    </nav>\
    ');

	$.template("tmpl-directions-leg", '\
	<div class="leg">\
	<h3 class="start" data-lat="${start_location.lat()}" data-lng="${start_location.lng()}">{{html start_label}}</h3>\
	<p>${start_address}</p>\
	<ol>\
	{{each steps}}<li class="step"><span class="instruction">{{html instructions}}</span> <span class="dist">${distance.text}</span></li>{{/each}}\
	</ol>\
	</div>\
	');

	$.template("tmpl-directions-leg-last", '\
	<div class="leg">\
	  	<h3 class="end" data-lat="${end_location.lat()}" data-lng="${end_location.lng()}">{{html end_label}}</h3>\
	  	<p>${end_address}</p>\
	</div>\
	');


	$.template("tmpl-directions-step", '\
	\
	');

	
	$.template("tmpl-imageset", '\
		<div class="image">\
		{{if thumb_url}}\
			{{if full_url}}\
				<a href="${full_url}" rel="photo-viewer"><img src="${thumb_url}"></a>\
			{{else}}\
				<img src="${thumb_url}">\
			{{/if}}\
		{{else}}\
			{{if full_url}}\
				<img src="${full_url}">\
			{{/if}}	\
		{{/if}}\
		{{if attribution}}<cite>${attribution}</cite>{{/if}}\
		</div>\
	');

	//<img class="static-map" src="http://maps.google.com/maps/api/staticmap?center=${loc.lat},${loc.lng}&zoom=12&size=256x128&maptype=roadmap&markers=color:blue|${loc.lat},${loc.lng}&sensor=false"/>	
	$.template("tmpl-bus", '\
		<div class="entity business">\
	    <!-- URL -->\
	    {{if url}}\
	    	<div class="url">\
	    		<span>Official Site:</span> <a href="${url}">${url}</a>\
	    	</div>\
	    {{/if}}\
	    \
	    <div class="actions">\
	        <!-- Map Link -->\
	    	{{if loc && loc.lat && loc.lng}}\
	    		<a href="http://maps.google.com/?q=${name}+at+${addr.street}+${addr.city}+${addr.province}+${addr.postal}" target="_blank" class="button" data-lat="${loc.lat}" data-lng="${loc.lng}">View in Google Maps</a>\
	    	{{/if}}\
                \
                <!-- Focus On This Link -->\
                {{if entity_id}}\
                        {{if user_loc && user_loc.lat && user_loc.lng}}\
                                <a href="/focus/${entity_id}/${user_loc.lat},${user_loc.lng}"\
                                class="button" \
                                data-entity-id="${entity_id}" \
                                data-lat="${user_loc.lat}" \
                                data-lng="${user_loc.lng}">Focus On This</a>\
                        {{/if}}\
                {{/if}}\
			\
			<!-- Details -->\
			{{if detail_url}}\
			    <a href="${detail_url}" class="button">More Info</a>\
			{{/if}}\
		</div>\
		\
		<!-- Details -->\
		{{if detail_url}}\
			<!-- div class="share">\
				<a href="http://twitter.com/share" \
					class="share-twitter" \
					data-text="Lozzal says I should visit ${lbl}"\
					data-url="${detail_url}"\
					data-count="none" \
					data-via="LozzalApp">Tweet</a>\
				<iframe \
					class="share-facebook" \
					src="http://www.facebook.com/plugins/like.php?href=${detail_url}&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=recommend&amp;colorscheme=light&amp;height=21" \
					scrolling="no" \
					frameborder="0" \
					style="border:none; overflow:hidden; width:93px; height:20px;" \
					allowTransparency="true"></iframe>\
			</div -->\
		{{/if}}\
		  \
		</div>\
	');
	
	$.template("tmpl-poi", '\
		<div class="entity poi">\
	    <!-- URL -->\
	    {{if url}}\
	    	<div class="url">\
	    		<span>Official Site:</span> <a href="${url}">${url}</a>\
	    	</div>\
	    {{/if}}\
	    \
	    <div class="actions">\
	        <!-- Map Link -->\
	    	{{if loc && loc.lat && loc.lng}}\
	    		<a href="http://maps.google.com/?q=${name}+at+${addr.street}+${addr.city}+${addr.province}+${addr.postal}" target="_blank" class="button" data-lat="${loc.lat}" data-lng="${loc.lng}">View in Google Maps</a>\
	    	{{/if}}\
			\
                <!-- Focus On This Link -->\
                {{if entity_id}}\
                        {{if user_loc && user_loc.lat && user_loc.lng}}\
                                <a href="/focus/${entity_id}/${user_loc.lat},${user_loc.lng}"\
                                class="button" \
                                data-entity-id="${entity_id}" \
                                data-lat="${user_loc.lat}" \
                                data-lng="${user_loc.lng}">Focus On This</a>\
                        {{/if}}\
                {{/if}}\
			\
			<!-- Details -->\
			{{if detail_url}}\
			    <a href="${detail_url}" class="button">More Info</a>\
			{{/if}}\
		</div>\
		\
		<!-- Details -->\
		{{if detail_url}}\
			<!-- div class="share">\
				<a href="http://twitter.com/share" \
					class="share-twitter" \
					data-text="Lozzal says I should visit ${lbl}"\
					data-url="${detail_url}"\
					data-count="none" \
					data-via="LozzalApp">Tweet</a>\
				<iframe \
					class="share-facebook" \
					src="http://www.facebook.com/plugins/like.php?href=${detail_url}&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=recommend&amp;colorscheme=light&amp;height=21" \
					scrolling="no" \
					frameborder="0" \
					style="border:none; overflow:hidden; width:93px; height:20px;" \
					allowTransparency="true"></iframe>\
			</div -->\
		{{/if}}\
		  \
		</div>\
	');
	  	  	  	  	
	$.template("tmpl-event", '\
	<div class="entity event">\
		{{if poster}}\
				<img src="${poster}">\
		{{/if}}\
		\
		{{if lbl}}\
				<h3>${lbl}</h3>\
		{{/if}}\
		\
		{{if dsc}}<div>${dsc}</div>{{/if}}\
		\
		<div>{{if genres}}<strong>{{each genres}}{{if $index>0 }}, {{/if}}${$value}{{/each}}</strong>,{{/if}} {{if rate}}Rated ${rate}{{/if}}</div>\
		<div>\
		{{if order_url}}<div class="tickets"><a href="${order_url}" class="button">Get Tickets</a></div>{{/if}}\
        <!-- Focus On This Link -->\
        {{if entity_id}}\
                {{if user_loc && user_loc.lat && user_loc.lng}}\
                        <a href="/focus/${entity_id}/${user_loc.lat},${user_loc.lng}"\
                        class="button" \
                        data-entity-id="${entity_id}" \
                        data-lat="${user_loc.lat}" \
                        data-lng="${user_loc.lng}">Focus On This</a>\
                {{/if}}\
        {{/if}}\
        \
		</div>\
		\
		{{if runtime}}<div><span>Runtime:</span> ${runtime} minutes</div>{{/if}}\
		{{if url}}<div><span>Official Site:</span> <a href="${url}">${url}</a></div>{{/if}}\
		{{if director}}<div><span>Director:</span> ${director}</div>{{/if}}\
		{{if release_theatre}}<div><span>Theater Release:</span> ${release_theatre}</div>{{/if}}\
		{{if release_dvd}}<div><span>Release DVD:</span> ${release_dvd}</div>{{/if}}\
		{{if cast}}<div><span>Cast includes:</span><br/>{{each cast}}{{if $index>0 }}, {{/if}}${$value.name}{{/each}}</div>{{/if}}\
		{{if crew}}<div><span>Crew includes:</span><br/>{{each crew}}{{if $index>0 }}, {{/if}}${$value.name}{{/each}}</div>{{/if}}\
		\
		{{if photos}}\
			<ul class="photos clearfix">\
    		{{each photos}}<li><div class="image">\
		 {{if $value.thumb}}\
			{{if $value.full}}\
				<a href="${$value.full}" rel="photo-viewer"><img src="${$value.thumb}"></a>\
			{{else}}\
				<img src="${$value.thumb}">\
			{{/if}}\
		{{else}}\
			{{if $value.full}}\
				<img src="${$value.full}">\
			{{/if}}	\
		{{/if}}\
		{{if $value.attribution}}<cite>${$value.attribution}</cite>{{/if}}\
		</div>\</li>{{/each}}\
			</ul>\
		{{/if}}\
		\
		{{if detail_url}}  \
			<!-- div class="share">    \
			<a href="http://twitter.com/share" \
				class="twitter-share-button" \
				data-text="Lozzal says I should watch ${lbl}"\
				data-url="${detail_url}"\
				data-count="none" \
				data-via="LozzalApp">Tweet</a>\
			<iframe \
			    src="http://www.facebook.com/plugins/like.php?href=${detail_url}&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=recommend&amp;colorscheme=light&amp;height=21" \
			    scrolling="no" \
			    frameborder="0" \
			    style="border:none; overflow:hidden; width:93px; height:20px;" \
			    allowTransparency="true"></iframe>\
			</div -->\
		{{/if}}\
	</div>\
	');
	
	$.template("tmpl-sport-team", '\
	<div class="entity sport-team">\
		{{if poster}}\
				<img src="${poster}">\
		{{/if}}\
		\
		{{if lbl}}\
				<h3>${lbl}</h3>\
		{{/if}}\
		\
		{{if dsc}}<div>${dsc}</div>{{/if}}\
		\
		<div>{{if genres}}<strong>{{each genres}}{{if $index>0 }}, {{/if}}${$value}{{/each}}</strong>,{{/if}} {{if rate}}Rated ${rate}{{/if}}</div>\
		<div>\
		{{if order_url}}<div class="tickets"><a href="${order_url}" class="button">Get Tickets</a></div>{{/if}}\
        <!-- Focus On This Link -->\
        {{if entity_id}}\
                {{if user_loc && user_loc.lat && user_loc.lng}}\
                        <a href="/focus/${entity_id}/${user_loc.lat},${user_loc.lng}"\
                        class="button" \
                        data-entity-id="${entity_id}" \
                        data-lat="${user_loc.lat}" \
                        data-lng="${user_loc.lng}">Focus On This</a>\
                {{/if}}\
        {{/if}}\
        \
		</div>\
		\
		{{if runtime}}<div><span>Runtime:</span> ${runtime} minutes</div>{{/if}}\
		{{if url}}<div><span>Official Site:</span> <a href="${url}">${url}</a></div>{{/if}}\
		{{if director}}<div><span>Director:</span> ${director}</div>{{/if}}\
		{{if release_theatre}}<div><span>Theater Release:</span> ${release_theatre}</div>{{/if}}\
		{{if release_dvd}}<div><span>Release DVD:</span> ${release_dvd}</div>{{/if}}\
		{{if cast}}<div><span>Cast includes:</span><br/>{{each cast}}{{if $index>0 }}, {{/if}}${$value.name}{{/each}}</div>{{/if}}\
		{{if crew}}<div><span>Crew includes:</span><br/>{{each crew}}{{if $index>0 }}, {{/if}}${$value.name}{{/each}}</div>{{/if}}\
		\
		{{if photos}}\
			<ul class="photos clearfix">\
    		{{each photos}}<li><div class="image">\
		 {{if $value.thumb}}\
			{{if $value.full}}\
				<a href="${$value.full}" rel="photo-viewer"><img src="${$value.thumb}"></a>\
			{{else}}\
				<img src="${$value.thumb}">\
			{{/if}}\
		{{else}}\
			{{if $value.full}}\
				<img src="${$value.full}">\
			{{/if}}	\
		{{/if}}\
		{{if $value.attribution}}<cite>${$value.attribution}</cite>{{/if}}\
		</div>\</li>{{/each}}\
			</ul>\
		{{/if}}\
		\
		{{if detail_url}}  \
			<!-- div class="share">    \
			<a href="http://twitter.com/share" \
				class="twitter-share-button" \
				data-text="Lozzal says I should watch ${lbl}"\
				data-url="${detail_url}"\
				data-count="none" \
				data-via="LozzalApp">Tweet</a>\
			<iframe \
			    src="http://www.facebook.com/plugins/like.php?href=${detail_url}&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=recommend&amp;colorscheme=light&amp;height=21" \
			    scrolling="no" \
			    frameborder="0" \
			    style="border:none; overflow:hidden; width:93px; height:20px;" \
			    allowTransparency="true"></iframe>\
			</div -->\
		{{/if}}\
	</div>\
	');
		
	
	$.template("tmpl-movie", '\
	<div class="entity movie">\
    	{{if poster}}\
    			<img src="${poster.thumb}" class="entity-poster-thumb">\
    	{{/if}}\
    	\
    	{{if lbl}}\
    			<h3>${lbl}</h3>\
    	{{/if}}\
    	\
    	{{if dsc}}<div>${dsc}</div>{{/if}}\
    	\
    	<div>\
    	{{if genres}}<strong>{{each genres}}{{if $index>0 }}, {{/if}}${$value}{{/each}}</strong>,{{/if}} \
    	{{if runtime}}${runtime} minutes,{{/if}} \
    	{{if rate}}Rated ${rate}{{/if}}\
    	</div>\
    	<div class="actions">\
    	{{if trailer_urls && trailer_urls[0]}}<a href="${trailer_urls[0]}" class="trailer button">Watch trailer</a>{{/if}}\
    	{{if order_url}}<a href="${order_url}" class="ticket button">Get Tickets</a>{{/if}}\
        <!-- Focus On This Link -->\
        {{if entity_id}}\
                {{if user_loc && user_loc.lat && user_loc.lng}}\
                        <a href="/focus/${entity_id}/${user_loc.lat},${user_loc.lng}"\
                        class="button" \
                        data-entity-id="${entity_id}" \
                        data-lat="${user_loc.lat}" \
                        data-lng="${user_loc.lng}">Focus On This</a>\
                {{/if}}\
        {{/if}}\
        \
    	</div>\
    	\
    	{{if url}}<div><span>Official Site:</span> <a href="${url}">${url}</a></div>{{/if}}\
    	{{if director}}<div><span>Director:</span> ${director}</div>{{/if}}\
    	{{if release_theatre}}<div><span>Released:</span> ${release_theatre} {{if release_dvd}} (on DVD ${release_dvd}){{/if}}</div>{{/if}}\
    	{{if cast}}<div><span>Cast includes:</span><br/>{{each cast}}{{if $index>0 }}, {{/if}}${$value.name}{{/each}}</div>{{/if}}\
    	{{if crew}}<div><span>Crew includes:</span><br/>{{each crew}}{{if $index>0 }}, {{/if}}${$value.name}{{/each}}</div>{{/if}}\
    	\
    	{{if photos}}\
    		<ul class="photos clearfix">\
    		{{each photos}}<li><div class="image">\
		 {{if $value.thumb}}\
			{{if $value.full}}\
				<a href="${$value.full}" rel="photo-viewer"><img src="${$value.thumb}"></a>\
			{{else}}\
				<img src="${$value.thumb}">\
			{{/if}}\
		{{else}}\
			{{if $value.full}}\
				<img src="${$value.full}">\
			{{/if}}	\
		{{/if}}\
		{{if $value.attribution}}<cite>${$value.attribution}</cite>{{/if}}\
		</div>\</li>{{/each}}\
    		</ul>\
    	{{/if}}\
    	\
    	{{if detail_url}}  \
    		<!-- div class="share">    \
    		<a href="http://twitter.com/share" \
    			class="twitter-share-button" \
    			data-text="Lozzal says I should watch ${lbl}"\
    			data-url="${detail_url}"\
    			data-count="none" \
    			data-via="LozzalApp">Tweet</a>\
    		<iframe src="http://www.facebook.com/plugins/like.php?href=${detail_url}&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=recommend&amp;colorscheme=light&amp;height=21" \
    		scrolling="no" \
    		frameborder="0" \
    		style="border:none; overflow:hidden; width:93px; height:20px;" \
    		allowTransparency="true"></iframe>\
    		</div -->\
    	{{/if}}\
	</div>\
	'); 	

	
	// Common helpers
	
	function updateInfluencerText( text, address ) {
	    $('#influencers').data('text', text );
	    if (address) $('#influencers').data('location-name', address );
	    
		var pattern = $('#influencers').data('text');
		var location = $('#influencers').data('location-name');

		if (!pattern || pattern.length == 0) {
			pattern = 'Your location is %LOCATION%';
		} 
		
		if(!location || location.length == 0) return;
		
		$('#influencers').html(pattern.replace('%LOCATION%', '<strong>' + location + '</strong>').replace('%CITY%', '<strong>' + location + '</strong>'));
		
	};
	
	
	if($('body#suggestions').size() > 0) {
	}
	
	
	var itinerary = $('body#itinerary');
  if (itinerary.size() > 0) {
  
  	/*********************************
  	 * Init map
  	 *********************************/
  	
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
            

		var resizePanes = function() {
			var height = $(window).height() - $('#container > header').height() - 2;
			var mapWidth = $(window).width() - $('#info').width();
			$('#map').css({height:height,width:mapWidth});
			$('#info').css('height',height);
			
			google.maps.event.trigger(map, 'resize');
			
			
		};
       
    resizePanes();     
  	
  	$(window).resize(function() {
  	  resizePanes();
  	});

	//new TouchScroll($('#info')[0], {});
  	
  	// init the directions
  	
  	$('a.dirmode').click(function(e){
  		calcRoute($(this).data('dirmode'));
  		return false;
  	});
  	
  	$('#update-directions').click(function(e){
  		calcRoute($('.dirmode[class~="selected"]').data('dirmode'));
  		return false;
  	});
  	
  	
  	google.maps.event.addListener( map, 'bounds_changed', 
		function(e) {
    		// google.maps.event.trigger(map, 'resize');
			
			// Modify the directions panel as necessary.
			$('img[src$=icon_greenA.png],img[src$=icon_greenA_graybg.png]', map).attr({
				src:'/css/i/1.png'
			});
			$('img[src$=icon_greenB.png],img[src$=icon_greenB_graybg.png]', map).attr({
				src:'/css/i/2.png'
			});
			$('img[src$=icon_greenC.png],img[src$=icon_greenC_graybg.png]', map).attr({
				src:'/css/i/3.png'
			});
			$('img[src$=icon_greenD.png],img[src$=icon_greenD_graybg.png]', map).attr({
				src:'/css/i/4.png'
			});
			
		});

  	
  	
	  var directionsDisplay = new google.maps.DirectionsRenderer();
	  directionsDisplay.setMap(map);
	  
	  var directionsService = new google.maps.DirectionsService();
        var startIsCustom = $('#start-route').val().length > 0;
	  
	  function calcRoute( selectedMode ) {
	  
	  	// Update the dirmode ui.
	  	$('.dirmode').removeClass('selected');
	    $('.dirmode[data-dirmode="'+selectedMode+'"]').addClass('selected');
	    $("#directions-summary").html('<div class="loading">Loading…</div>');
	    
	    
	    // Get the start value from the input.
	    var start = $('#start-route').val();
	    
	    // Build a list of points from the markup.
	    var waypts = [];
	    $('#itinerary-stops li[data-latitude]').each(function(i,e) {
	    	var obj = $(e);
	    	// Check for a lat.lng. If one is not present skip the item.
	    	if (obj.data('latitude') != 0 || obj.data('longitude') != 0) {
	    	    var addr = obj.find(".address").html();
    	    	waypts.push({
    	    		location: ( addr && addr.length > 0) ? addr : (obj.data('latitude') + ',' + obj.data('longitude')),
    	    		stopover: true
    	    	});
	    	}
	    });
	    	    
	    // Replace the start if necessary.
	    var startIsCustom = true;
	    
	    if (start == undefined || start == null || start.length == 0) {
	        startIsCustom = false;
	    	var wp = waypts.shift();
	    	start = wp.location;
	    }

        var end;
	    if (waypts.length == 0) {
	    	// There was only one point.
	    	// TODO, modify the markup to suggest entering a start location.
            // Use the last waypoint as the end.
            end = start;
	    } else {
	        // Use the last waypoint as the end.
	        end = waypts.pop().location;
	    
	    }
	    
	    
	    // Build the generic request.
	    var request = {
	        origin: start,
	        destination: end,
	        // Note that Javascript allows us to access the constant
	        // using square brackets and a string value as its
	        // "property."
	        travelMode: google.maps.DirectionsTravelMode[selectedMode]
	    };
	    
	    // Add in the waypoints if there are any.
	    if (waypts.length > 0) {
	    	request.waypoints = waypts;
	    	request.optimizeWaypoints = true;
	    }
	    
	    directionsService.route(request, function(response, status) {
	      if (status == google.maps.DirectionsStatus.OK) {	        
	        
	        // Show any warnings.
	        if (response.routes[0].warnings.length > 0) {
	        
	        	var warn = $("#directions-warnings").empty().show();
	        	$(response.routes[0].warnings).each(function(i,e){
	        		warn.append('<li>' + e + '</li>');
	        	})
	        } else {
		        $("#directions-warnings").hide();
	        }
	        	        
	       	// Draw the lines.
	        directionsDisplay.setDirections(response);
	        
	        // Update the markers in the side bar
	        $('#itinerary-stops .stops h1 .marker').each(function(i,e) {
	            $(this).attr('src','/css/i/' + (i + (startIsCustom ? 2 : 1)) + '.png')
	        });
	        
	        // Pares the directions.
	        
	        var route = response.routes[0];
          var summaryPanel = $("#directions-summary");
          summaryPanel.empty();
                    
          var hasStart = $('#itinerary-stops').size() < route.legs.length;
          var labelIndex = 0;
          
          // For each route, display summary information.
          for (var i = 0; i < route.legs.length; i++) {
	          
	          route.legs[i].start_position = i + 1;
	          route.legs[i].end_position = route.legs[i].start_position + 1;
	          
	          labelIndex = hasStart ? i - 1 : i;
	        	  
	        	if (labelIndex < 0) {
	        		route.legs[i].start_label = '<h3><img src="/css/i/1.png" class="marker">Start</h3>';
	        	} else {
	          	route.legs[i].start_label = $('#itinerary-stops li:nth-child(' + (labelIndex+1) + ') h1').html()
	          }
	          route.legs[i].end_label = $('#itinerary-stops li:nth-child(' + (labelIndex+2) + ') h1').html()
	          
          	summaryPanel.append($.tmpl("tmpl-directions-leg", route.legs[i]));          
          }
          summaryPanel.append($.tmpl("tmpl-directions-leg-last", route.legs[i - 1]));          
              
            
            setTimeout(function(){
                if (map.getZoom() > 17) map.setZoom(17);
            },500);
                                
                    
          resizePanes();
          
	      } else {
	      	var errors = {
		      	INVALID_REQUEST: "The request provided was invalid.",
		      	MAX_WAYPOINTS_EXCEEDED: "	Too many waypoints were provided. The total allowed waypoints is 8, plus the origin and destination.",
		      	NOT_FOUND: "At least one of the origin, destination, or waypoints could not be found. Try entering a different starting location.",
		      	OVER_QUERY_LIMIT: "You have gone over the requests limit in too short a period of time.",
		      	REQUEST_DENIED: "You are not allowed to use the directions service.",
		      	UNKNOWN_ERROR: "A directions request could not be processed due to a server error. The request may succeed if you try again.",
		      	ZERO_RESULTS: "No route could be found between the origin and destination."
	      	};
	      
	      	$("#directions-summary").html(errors[status]);      	
            if(status == "NOT_FOUND") {
                $('#itinerary-stops li[data-latitude]').each(function(i,e) {
                    var obj = $(e);
                    var addr = obj.find(".address").html();
                    geocoder.geocode( {'address': addr}, function(addr_result, addr_status) {
                        if( addr_status == google.maps.GeocoderStatus.ZERO_RESULTS) {
                            var latlng = new google.maps.LatLng(obj.data('latitude'), obj.data('longitude'));
                            geocoder.geocode( {'latLng': latlng}, function(ltn_result, ltn_status) {
                                if (ltn_status == google.maps.GeocoderStatus.OK) {
                                    obj.find(".address").html("Near" + ltn_result[0].formatted_address);
                                    calcRoute( selectedMode );
                                }
                            });
                        }
                    });
                });
            }
            
	      }
	    });
	    
	  }
	  
	  calcRoute( 'DRIVING' );
  	
  	// Setup itinerary.
		var suggestionId = $('body').data('suggestion-id');
		var key = $('body').data('user-key');
		var uid = $('body').data('user-uid');
		
        var latitude = $.cookie('latitude');
        var longitude = $.cookie('longitude');
                
		$('#itinerary-stops li').each(function(i,e) {
			var obj = $(e); 
			
			$.ajax({
			  url: '/request?type=itinerary&id=' + suggestionId + '&idx=' + obj.data('detail-idx'),
			  dataType: 'json',
			  context: obj.find('.details'),
			  success: function( data ){

			    $(this).addClass("done");
			    $(this).empty();
			  
			  	if (data.code != 200) {
			  		return;
			  	}
			    
			    obj.find('h1').prepend('<img src="/css/i/' + (i + (startIsCustom ? 2 : 1)) + '.png" class="marker">');
			    
			    // Create a marker for the map.
			    var myLatlng = new google.maps.LatLng(obj.data('latitude'),obj.data('longitude'));
	        
			    /* 
			    var image = new google.maps.MarkerImage(
			      '/css/i/' + (i + 1) + '.png',
			      new google.maps.Size(32,32),
			      new google.maps.Point(0,0),
			      new google.maps.Point(16,32)
			    );
			    
			    var shadow = new google.maps.MarkerImage(
			      '/css/i/marker-shadow.png',
			      new google.maps.Size(52,32),
			      new google.maps.Point(0,0),
			      new google.maps.Point(16,32)
			    );
			    
			    var shape = {
			      coord: [19,0,20,1,21,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,23,13,23,14,22,15,21,16,20,17,20,18,19,19,19,20,18,21,18,22,17,23,17,24,17,25,17,26,16,27,16,28,16,29,16,30,16,31,14,31,14,30,14,29,14,28,14,27,14,26,13,25,13,24,13,23,12,22,12,21,12,20,11,19,10,18,10,17,9,16,8,15,7,14,7,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,7,5,7,4,8,3,9,2,10,1,11,0,19,0],
			      type: 'poly'
			    };
			    	       
			    var marker = new google.maps.Marker({
							icon: image,
							shadow: shadow,
							shape: shape,
			      position: myLatlng, 
			      map: map
			      });
			      */
			      
			      //map.setCenter(myLatlng);
			    
			    for (i in data.sd.eis) {
				    for (type in data.sd.eis[i]) {
				    	
				    	// data cleaning
				    	
				    	// Fix the url
				    	if (data.sd.eis[i][type].url && data.sd.eis[i][type].url.substring(0,7) != 'http://') {
				    		data.sd.eis[i][type].url = 'http://' + data.sd.eis[i][type].url;
				    	}
				    	
				    	// Formate the time
				    	if (data.sd.eis[i][type].release_theatre) {
				    		var when = new Date(parseInt(data.sd.eis[i][type].release_theatre,10) * 1000 );
				    		//http://blog.stevenlevithan.com/archives/date-time-format
				    		data.sd.eis[i][type].release_theatre = when.format('l, F jS Y');
				    	}
				    	
						// Formate the time
						if (data.sd.eis[i][type].release_dvd) {
							var when = new Date(parseInt(data.sd.eis[i][type].release_dvd,10) * 1000 );
							//http://blog.stevenlevithan.com/archives/date-time-format
							data.sd.eis[i][type].release_dvd = when.format('l, F jS Y');
						}
						
						// Formate the time
						if (data.sd.eis[i][type].startdate) {
							var when = new Date(parseInt(data.sd.eis[i][type].startdate,10) * 1000 );
							//http://blog.stevenlevithan.com/archives/date-time-format
							data.sd.eis[i][type].startdate = when.format('l, F jS Y');
						}
						
						// Formate the time
						if (!data.sd.eis[i][type].detail_url || data.sd.eis[i][type].detail_url.length == 0) {
							data.sd.eis[i][type].detail_url = obj.data('url');
						}
						
                        if(latitude && longitude) {
                            data.sd.eis[i][type].user_loc = {
                                lat: latitude, 
                                lng:longitude
                            };
                        }else {
                            data.sd.eis[i][type].user_loc = data.sd.eis[i][type].loc;
                        }
                        
				    	$.tmpl("tmpl-" + type.replace('_','-'), data.sd.eis[i][type]).appendTo(this);
				    	
				    }
			    }
			    

			    if (obj.data('venue-google') || obj.data('venue-facebook') || obj.data('venue-foursquare')) {

                    var p = $('<p><span>Check-in with:</span> </p>').prependTo(this)
    			    
    			    // Check for the checkin data.
    			    var comma = false;
                    if (obj.data('venue-google')) {
                        $('<a href="#">Google</a>').click(function(){
                            $.ajax({
                                url: '/request?type=checkin&service=google&id=' + obj.data('venue-google') + '&latitude=' + obj.data('latitude') + '&longitude=' + obj.data('longitude'),
                                dataType: 'json',
                                success: function(data){
                                    $( "<div>You have checked in using Google Places</div>" ).appendTo(document).dialog({
                                        modal: true,
                                        buttons: {
                                            Ok: function() {
                                                $( this ).dialog( "close" );
                                            }
                                        }
                                    });
                                }
                            }); 
                            return false;
                        }).appendTo(p);
                        comma = true;
                    }
                    
                    if (obj.data('venue-facebook')) {
                        if (comma) p.append($('<span>, </span>'));
                        $('<a href="#">Facebook</a>').click(function(){
                            $.ajax({
                                url: '/request?type=checkin&service=facebook&id=' + obj.data('venue-facebook') + '&latitude=' + obj.data('latitude') + '&longitude=' + obj.data('longitude'),
                                dataType: 'json',
                                success: function(data){
                                    $( "<div>You have checked in using Facebook Places</div>" ).appendTo(document).dialog({
                                        modal: true,
                                        buttons: {
                                            Ok: function() {
                                                $( this ).dialog( "close" );
                                            }
                                        }
                                    });
                                }
                            }); 
                            return false;
                        }).appendTo(p);
                        comma = true;
                    } else {
                        if (comma) p.append($('<span>, </span>'));
                        p.append($('<a>Enable Facebook</a>').attr('href',$('#itinerary-stops').data('checkin-facebook')));
                        comma = true;
                    }
                    
                    if (obj.data('venue-foursquare')) {
                        if (comma) p.append($('<span>, </span>'));
                        $('<a href="#">Foursquare</a>').click(function(){
                            $.ajax({
                                url: '/request?type=checkin&service=foursquare&id=' + obj.data('venue-foursquare') + '&latitude=' + obj.data('latitude') + '&longitude=' + obj.data('longitude'),
                                dataType: 'json',
                                success: function(data){
                                    $( "<div>You have checked in using Foursquare</div>" ).appendTo(document).dialog({
                                        modal: true,
                                        buttons: {
                                            Ok: function() {
                                                $( this ).dialog( "close" );
                                            }
                                        }
                                    });
                                }
                            }); 
                            return false;
                        }).appendTo(p);
                    } else {
                        if (comma) p.append($('<span>, </span>'));
                        p.append($('<a>Enable Foursquare</a>').attr('href',$('#itinerary-stops').data('checkin-foursquare')));
                        comm = true;
                    }
                    
			    }
			    
			    resizePanes();
			    
			    
			    
			  }
			});
			
		});
		
		
		
  }
   
   var locationDialog = $( '<div id="location-dialog"></div>' ).appendTo(document.body);

    var startLocation = {
        latitude: 37.775871, 
        longitude: -122.418938,
        name: 'San Francisco, CA',
        units: 'mi'
    };
    
    if ($.cookie('latitude') != 0 || $.cookie('longitude') != 0) {
        startLocation = {
            latitude:$.cookie('latitude'), 
            longitude:$.cookie('longitude'),
            name: $.cookie('address') ? $.cookie('address') : '',
            units: $.cookie('units') ? $.cookie('units') : ''
        }
    }

   locationDialog.locationPicker({
       // default to SF
    	location:startLocation,
    	confirm:function(event,location) { 
   				console.log('location', location);
                History.pushState(
                    {
                        type:'location-change',
                        latitude:location.latitude,
                        longitude:location.longitude,
                        name:location.name,
                        units:location.units,
                        hash:null,
                        offset:0,
                        limit:25
                    },
                    location.name ? 'Lozzal: ' + location.name : 'Lozzal: Local Discovery' ,
                    '/' + LOZZAL_BASE + '/' + location.latitude + ',' + location.longitude + '/null/0/25'
                );
                
    	}
    });
    
    var changeLocationHandler = function(){
    
        $('#location-error-dialog').dialog('close');
        
    	// setup below
    	locationDialog.locationPicker("open");
    	return false;	
	};

	$('.changelocation').live('click',changeLocationHandler);
   
    var ajaxHandler = function( data ){
        

        this.removeClass('loading');

        if (data.code != 200) {
            $('<div id="suggestions-error-dialog" title="No Suggestions">\
            	<p>I could not think of any more suggestions.</p> <p>Try a <a href="/location" class="changelocation">different location</a></p>\
            </div>').dialog({
                modal: true,
                buttons: {
                    Ok: function() {
                        $( this ).dialog( "close" );
                    }
                }
            });
            return;
        }
        
        if(LOZZAL_BASE == 'focus') {
            if(data.suggestions && data.influencers.text && data.suggestions.length == 1) {
                $('<div id="suggestions-error-dialog" title="No Suggestions">\
                    <p>We were unable to think of any other suggestions involving '+ formatSuggestionText(data.influencers.text[0]) +' right now. Perhaps try at a different time of day?</p>\
                </div>').dialog({
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                });
                //return;
            }
        }

        this.data('hash',data.hash ? data.hash : 'null');
        this.data('offset',data.offset ? parseInt(data.offset) : 0);

        this.empty().append($.tmpl("tmpl-suggestions", data));
        this.removeClass('loading');
        
        updateInfluencerText(data.influencers.synopsis);
        
        applyPostLoadEvents(data,this);
        
    }
    
    function applyPostLoadEvents(data, wrapper) {
        
        filterId = null;
        if(LOZZAL_BASE == 'similar') {
            filterId = $('#suggestions-wrapper').data('similar-id');
        }
        if(LOZZAL_BASE == 'focus') {
            filterId = $('#suggestions-wrapper').data('focus-id');
        }

        $('ul.meta-themes a').removeClass('selected');
        $('ul.meta-themes a[data-base="' + LOZZAL_BASE + '"]').addClass('selected');
        
        if (data.influencers.text && data.influencers.text.length > 0) {
                if(LOZZAL_BASE == 'focus') {
                        updateInfluencerText('Here are some more ideas that involve ' + formatSuggestionText(data.influencers.text[0]));
                }else{ 
                        updateInfluencerText('Suggestions similar to: "' + formatSuggestionText(data.influencers.text[0]) + '"');
                }
        }
        
        updateUnits($.cookie('units'));
        
        wrapper.find('li.suggestion').click(function(){
            window.location.href = '/i/' + $(this).data('id');
            return false;
        });
        
        wrapper.find('.suggestion .similar').click(function(e) {
          var obj = $(this);
            obj.addClass('loading');
          if(obj.data('id')) {
          
              var previousState = History.getState(); 
          
               History.pushState(
                   {
                       type:'similar',
                       id:obj.data('id'),
                       latitude:previousState.data.latitude,
                       longitude:previousState.data.longitude,
                       offset:0,
                       limit:25
                   }, 
                   'Lozzal: More Similar Ideas',
                   '/similar/' + obj.data('id') + '/' + previousState.data.latitude + ',' + previousState.data.longitude );
          }
          return false;
        });
        
        var parentOffset = data.offset;
        var parentCount = data.count;
        
        // This is commented in iteration x1 to avoid false bindings. we want to remove less button
        /*wrapper.find('.less .button').click(function(){

            if (parentOffset && parentOffset > 0) {
                // load previous set.
                var data = History.getState().data; 
                data.offset = Math.max(0,parentOffset - 25);
                data.type = 'suggestions';
                
                var uri;
                if (LOZZAL_BASE == 'similar' || LOZZAL_BASE == 'focus') {
                    data.type = LOZZAL_BASE;
                    uri = '/' + LOZZAL_BASE + '/' + filterId + '/' + data.latitude + ',' + data.longitude + '/' + (data.hash ? data.hash : 'null') + '/' + data.offset + '/' + data.limit;
                } else {
                    uri = '/' + LOZZAL_BASE + '/' + data.latitude + ',' + data.longitude + '/' + (data.hash ? data.hash : 'null') + '/' + data.offset + '/' + data.limit;
                }
            
               History.pushState(
                   data,
                   data.name ? 'Lozzal: ' + data.name : 'Lozzal: Local Discovery' ,
                   uri
               );
            }
            return false;
        });*/

        wrapper.find('.more .button').click(function(){
            // load next set.
            if (parentCount > 0) {
                var data = History.getState().data; 
                data.offset += parentCount;
                data.type = 'suggestions';
                
                var uri;
                if (LOZZAL_BASE == 'similar' || LOZZAL_BASE == 'focus') {
                   data.type = LOZZAL_BASE;
                   uri = '/' + LOZZAL_BASE + '/' + filterId + '/' + data.latitude + ',' + data.longitude + '/' + (data.hash ? data.hash : 'null') + '/' + data.offset + '/' + data.limit;
                } else {
                    uri = '/' + LOZZAL_BASE + '/' + data.latitude + ',' + data.longitude + '/' + (data.hash ? data.hash : 'null') + '/' + data.offset + '/' + data.limit;
                }
                
                History.pushState(
                    data,
                    data.name ? 'Lozzal: ' + data.name : 'Lozzal: Local Discovery' ,
                    uri
                );
            }
            return false;
        });
        
        if (!data.offset || data.offset <= 0) {
            wrapper.find('.less .button').addClass('inactive');
        } else {
            wrapper.find('.less .button').removeClass('inactive');
        }        
        
        $('body').animate({scrollTop:0}, 'slow');
    };
   
   
   // Event handlers
   // These are called by the history state handler.

    function updateSuggestionSimilar( latitude, longitude, id, hash, offset, limit, stateId ) {
        var wrapper = $('#suggestions-wrapper');


        if (wrapper.data('query-type') == 'similar' && wrapper.data('similar-id') == id && wrapper.data('hash') == hash && wrapper.data('offset') == offset) {
            // already loaded.
            wrapper.removeClass('loading');
            return;
        }
        wrapper.data('query-type','similar');
        wrapper.addClass('loading');
        
        var msg = $('a.similar[data-id="'+id+'"]').parent().find('p a').html();
        if (msg && msg.length > 0) {
           	$('#suggestions-wrapper').html('<div id="page-loading">Thinking about great local suggestions related to "' + msg + '".</div>');
        }            
         
         $.ajax({
             //url: '/request?type=similar&id=' + id + '&latitude=' + latitude + '&longitude=' + longitude,
             url: '/request?type=similar&hash=' + (hash ? hash : 'null') + '&offset=' + offset + '&limit=' + limit + '&latitude=' + latitude + '&longitude=' + longitude + '&id=' + id,
             dataType: 'json',
             context: wrapper,
             success: [function(data) {
                 // grab the suggestion text
                 //this.similarText = $('a.similar[data-id="'+id+'"]').parent().find('p a').html();
                 this.data('similar-id',id);
             }, ajaxHandler, function( data ) {
                // Fix the hash in the history state.
                var State = History.getState();
                if (!State.data.hash) {
                    State.data.hash = data.hash ? data.hash : 'null';
                    State.data.type = 'similar';
                    //if (this.similarText) State.data.similar = this.similarText;
                    History.replaceState(
                        State.data,
                        State.data.name ? 'Lozzal ' + State.data.name : 'Lozzal: Local Discovery' ,
                        '/similar/' + State.data.id + '/' + State.data.latitude + ',' + State.data.longitude + '/' + State.data.hash + '/' + State.data.offset + '/' + State.data.limit
                    );                    
                }
             }],
         }); 
    };
   
    function updateSuggestionFocus( latitude, longitude, id, hash, offset, limit, stateId ) {
        var wrapper = $('#suggestions-wrapper');
        if (wrapper.data('query-type') == 'focus' && wrapper.data('focus-id') == id && wrapper.data('hash') == hash && wrapper.data('offset') == offset) {
            // already loaded.
            wrapper.removeClass('loading');
            return;
        }
        wrapper.data('query-type','focus');
        wrapper.addClass('loading');
        
        var msg = $('a.similar[data-id="'+id+'"]').parent().find('p a').html();
        /*if (msg && msg.length > 0) {
           	$('#suggestions-wrapper').html('<div id="page-loading">Thinking about great local suggestions.</div>');
        } else {
           	$('#suggestions-wrapper').html('<div id="page-loading">Thinking about great local suggestions.</div>');                    
        }*/
         
         $.ajax({
             url: '/request?type=focus&hash=' + (hash ? hash : 'null') + '&offset=' + offset + '&limit=' + limit + '&latitude=' + latitude + '&longitude=' + longitude + '&id=' + id,
             dataType: 'json',
             context: wrapper,
             success: [function(data) {
                 // grab the suggestion text
                 //this.similarText = $('a.similar[data-id="'+id+'"]').parent().find('p a').html();
                 this.data('focus-id',id);
             }, ajaxHandler, function( data ) {
                // Fix the hash in the history state.
                var State = History.getState();
                if (!State.data.hash) {
                    State.data.hash = data.hash ? data.hash : 'null';
                    State.data.type = 'focus';
                    //if (this.similarText) State.data.similar = this.similarText;
                    History.replaceState(
                        State.data,
                        State.data.name ? 'Lozzal: ' + State.data.name : 'Lozzal: Local Discovery' ,
                        '/focus/' + State.data.id + '/' + State.data.latitude + ',' + State.data.longitude + '/' + State.data.hash + '/' + State.data.offset + '/' + State.data.limit
                    );                    
                }
             }],
         }); 
    };
    
    
   function updateSuggestionList( latitude, longitude, hash, offset, limit, theme ) {
        var wrapper = $('#suggestions-wrapper');
        
//        log('data', wrapper.data('hash'), wrapper.data('offset'));
//        log('data in', hash, offset);
                
        if (wrapper.data('query-type') == 'suggestions' && wrapper.data('hash') && wrapper.data('hash') == hash && wrapper.data('offset') == offset) {
            // already loaded.
//            log('ALREADY LOADED');
            wrapper.removeClass('loading');
            return;
        }
//        log('LOADED');
        wrapper.data('query-type','suggestions');
        
        wrapper.addClass('loading');
        
        $.ajax({
            url: '/request?type=suggestions&hash=' + (hash ? hash : 'null') + '&offset=' + offset + '&limit=' + limit + '&latitude=' + latitude + '&longitude=' + longitude + '&theme=' + theme,
            dataType: 'json',
            context: wrapper,
            success: [function(data) {
                //this.similarText = null;
                this.data('similar-id',null);
            },ajaxHandler,function(data){
                // Fix the hash in the history state.
                var State = History.getState();
                if (!State.data.hash) {
                    State.data.hash = data.hash ? data.hash : 'null';
                    State.data.type = 'suggestions';
                    History.replaceState(
                        State.data,
                        State.data.name ? 'Lozzal ' + State.data.name : 'Lozzal: Local Discovery' ,
                        '/' + LOZZAL_BASE + '/' + State.data.latitude + ',' + State.data.longitude + '/' + State.data.hash + '/' + State.data.offset + '/' + State.data.limit
                    );                
                }
            }]
        });
        	
   };
   
   /*********************************
    * Init location, this is important.
    *********************************/
   
   var geocoder = new google.maps.Geocoder();	
   
   function updateLocation(position) {

    var state = History.pushState(
        {
            type:'location-change',
            latitude:position.coords.latitude,
            longitude:position.coords.longitude,
            name:null,
            hash:null,
            offset:0,
            limit:25
        },
        'Lozzal' ,
        '/' + LOZZAL_BASE + '/' + position.coords.latitude + ',' + position.coords.longitude + '/null/0/25'
    );

     
     geocodeLatLng(position.coords.latitude, position.coords.longitude);
     
   };
   
   function geocodeLatLng(lat,lng) {
       var latlng = new google.maps.LatLng(lat,lng);
       geocoder.geocode({'latLng': latlng}, function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
           if (results[1]) {
              $.cookie('address', results[1].formatted_address, {expires: 7, path: '/'});
              updateInfluencerText( 'Your location is %LOCATION%', results[1].formatted_address);
              for (var i in results[1].address_components) {
                  if (results[1].address_components[i]['short_name'] == 'US') {
                      updateUnits('mi');
                  } else {
                      updateUnits('km');
                  }
              }
           }
         } else {
           //alert("Geocoder failed due to: " + status);
         }
       });
   }
   
   function noLocation() {

    // We only care about the main page. 
    if ($('body#suggestions').size() > 0) {
        $('#influencers').html('<p>I could not find your location.</p>');
         $('<div id="location-error-dialog" title="Location Error">\
         	<p>I could not find your location.</p><a href="/location" class="changelocation button">Enter location manually</a>\
         </div>').dialog();
     }
     
   };

    var focusId =  $('#suggestions-wrapper').data('focus-id');
    if(focusId && focusId != 0) {
        if ($.cookie('latitude') && $.cookie('longitude')) {
            prevState = History.getState();
            if(!isValidFocusState(prevState)) {
                History.replaceState(
                {
                    type:'focus',
                    latitude:$.cookie('latitude'),
                    longitude:$.cookie('longitude'),
                    id:focusId,
                    name:null,
                    hash:null,
                    offset:0,
                    limit:25
                },
                $.cookie('address') ? 'Lozzal: ' + $.cookie('address') : 'Lozzal: Local Discovery' ,
                    '/focus/' + focusId + '/' + $.cookie('latitude') + ',' + $.cookie('longitude') + '/null/0/25'
                    );
            }
        }
    }

   var existingCount = $('#suggestions-wrapper li').size();
   if (existingCount > 0) {
   
        // Content was pre-loaded

        if ($.cookie('latitude') && $.cookie('longitude')) {
            if ($.cookie('address') == null) {
                $('#influencers').html('Loading your location...');
                geocodeLatLng($.cookie('latitude'),$.cookie('longitude'));
            } else if ($('#influencers').html().indexOf('similar') == -1) {
                updateInfluencerText( 'Your location is %LOCATION%', $.cookie('address'));
            }
        } else {
            //$.cookie('latitude', State.data.latitude, { expires: 7, path: '/' });
            //$.cookie('longitude', State.data.longitude, { expires: 7, path: '/' });
        }
        
        // apply the ajax loader
        applyPostLoadEvents({
            latitude:$.cookie('latitude'),
            longitude:$.cookie('longitude'),
            offset:parseInt($('#suggestions-wrapper').data('offset')),
            count:existingCount,
            influencers:{}
        },$('#suggestions-wrapper'));
        
   } else if ($('#suggestions-wrapper').size() > 0) {
          
       // check for an existing location…
       if ($.cookie('latitude') && $.cookie('longitude')) {
           
           if(!focusId) {
               // TODO this breaks the back.
               var state = History.pushState(
                   {
                       type:'location-change',
                       latitude:$.cookie('latitude'),
                       longitude:$.cookie('longitude'),
                       name:$.cookie('address'),
                       units:$.cookie('units'),
                       hash:null,
                       offset:0,
                       limit:25
                   },
                   'Lozzal' ,
                   '/' + LOZZAL_BASE + '/' + $.cookie('latitude') + ',' + $.cookie('longitude') + '/null/0/25'
               );
           }
           
           if ($.cookie('address') == null) {
               $('#influencers').html('Loading your location...');
               geocodeLatLng($.cookie('latitude'),$.cookie('longitude'));
           }
           
       } else if (Modernizr.geolocation) {
           // No cookie, use geolocaiton.
            $('#influencers').html('Loading your location...');
            navigator.geolocation.getCurrentPosition(updateLocation,noLocation);
            //updateLocation({coords:{latitude:43.643001,longitude:-79.387207}});
       } else {
           // ask them where they are
           noLocation();
       }
   }
   
   function isValidFocusState(State) {
       if(State.data.latitude && State.data.longitude) {
           return true;
       }
       return false;
   }

});
