// fb like
FB.init({
	status : true, // check login status
	cookie : true, // enable cookies to allow the server to access the session
	xfbml  : true  // parse XFBML
});

var map;
var mapLoadedCallback;
var tilesLoadedCallback;
var mapSteps = [ 'Fetching Map Data ...', 'Initializing Map...' ];
var property_info = [];
var markers = [];
var mapStatusLabel = false;
var markerClusterer = null;

$(document).ready(function(){
	
	/*
	 * expand more
	 *
	 */
	$('a.more').click(function(){
		if ($(this).attr('rel') != '') {
			var sel = '#' + $(this).attr('rel');
			var div = $(sel);
			if (div.css('display') == 'none') {
				// show
				div.slideDown('fast');
			} else {
				// hide
				div.slideUp('fast');			
			}
			return false;
		}
	});
	
	/*
	 * expand description
	 *
	 */
	$('a#full_description').toggle(
		function() {
			var h = $('#description_content').height();
			$('#description_container').animate({ 
        height: h + 'px'
      }, 500, '', function(){
				// $.scrollTo( $('a#full_description'), 500 );
			});
			return false;
		},
		function() {
			$('#description_container').animate({ 
        height: '30px'
      }, 1000 );
			return false;
		}
	);
	
	/*
	 * jCarousel
	 * @see http://sorgalla.com/projects/jcarousel/
	 */
	jQuery('#mycarousel').jcarousel();
	
	/*
	 * thumb behaviors
	 */
	$('#mycarousel li.thumb_item a').click(function(){
		var anc = $(this);
		var cap = anc.attr('title');
		var num = anc.attr('name');
		var src = anc.attr('rel');
		var zoo = anc.attr('_zoom');
		
		var img = $('#gallery_zoom_image');
		img.attr('src', src);
		img.attr('alt', cap);
		img.parent().attr('title', cap);
		img.parent().attr('rel', zoo);
		
		$('#gallery_zoom_number').html( anc.parent().attr('jcarouselindex') );
		$('#gallery_zoom_caption').html( cap );
		
		return false;
		
		/*
		img.attr('src', src).load(function(){
	  	alert('Image Loaded');
		});
		*/																
	});
	
	$('#gallery_zoom_image').parent().click(function(){
		popup($(this).attr('rel'), 650, 650);
	});
		
	/*
	 * vote up / down
	 *
	 */
	$('#vote_up').click(function(){
		var id = $(this).attr('rel');		
		if (id != '') {
			$('#vote_wait').show();
			$('#vote_info').hide();
			$.getJSON('/ajax/vote/up/' + id, function(json){
				if (json.errors) {
					// error
					alert( json.errors[0] );
				} else {
					// success: update stats
					$('#vote_total').html( json.success.rank );
					$('#vote_total_up').html( json.success.up );
					$('#vote_total_down').html( json.success.down );					
					// disable buttons
					$('#vote_down').remove();
					$('#vote_up').css('background-position', '0 -56px').attr('rel', '');
				}
				$('#vote_wait').hide();
				$('#vote_info').show();
			});
		}
		return false;
	});
	$('#vote_down').click(function(){
		var id = $(this).attr('rel');	
		if (id != '') {
			$('#vote_wait').show();
			$('#vote_info').hide();
			$.getJSON('/ajax/vote/down/' + id, function(json){
				if (json.errors) {
					// error
					alert( json.errors[0] );
				} else {
					// success: update stats
					$('#vote_total').html( json.success.rank );
					$('#vote_total_up').html( json.success.up );
					$('#vote_total_down').html( json.success.down );					
					// disable buttons
					$('#vote_up').remove();
					$('#vote_down').css('background-position', '-28px -56px').attr('rel', '');				
				}
				$('#vote_wait').hide();
				$('#vote_info').show();
			});
		}
		return false;
	});
		
	/*
	 * contact owner via greybox
	 *
	 */
	$('#contact_button').click(function(){
		GB_hide();
		var t = $(this).attr('title');
		GB_ANIMATION = true;
		GB_show(t, $(this).attr('rel'), 520, 750);
		return false;
	});
	
	/*
	 * s2f via greybox
	 *
	 */
	$("a#send_to_friend").click(function(){
		GB_hide();
		var t = 'Send to a Friend';
		GB_ANIMATION = true;
		GB_show(t, $(this).attr('rel'), 520, 700);
		return false;
	});
	
	/*
	 * popup large map
	 *
	 */
	$('#large_map').click(function(){
		GB_hide();
		var t = $(this).attr('title');
		
		// pass in map sizing via URL. this is done b/c width+height are best hard-set w/ inline style tag on map div.
		// margins are calc'ed like so: 
		//  - 50px x 2 = 100px, margins from iframe to parent window
		//  - 25px x 2 = 50px, margins from inner iframe to map div
		//  - 10px x 2 = 20px, extra pading for iframe borders, etc.
		var m_total = 170;
		var w = ( $(window).width() - m_total );
		var h = ( $(window).height() - m_total );		
		var url = $(this).attr('rel') + '&w=' + w + '&h=' + h;
		
		// no animation - loading map into a hidden iframe screws up the map center
		GB_ANIMATION = false;
		GB_show(t, url, h, w);
		return false;
	});
	
	/*
	 * implement spinboxes, datepickers, masked inputs, multiselects
	 *
	 */
	$("input.datepicker").datePicker( {clickInput: true, verticalOffset: 24} );
	
	/*
	 * implement pulldown map behaviors
	 *
	 */
	if ( ! GBrowserIsCompatible() ) {
		
		$('#expand_map').hide();
		
	} else {
		
		// expand/collapse map div
		$('#expand_map').click(function(){

			if ( $('#destination_map').hasClass( 'destination-map-expanded' ) ) {
				
				// close: slide up
				$('#mapcontainer').animate({ height: "130px" }, 'fast', 'swing', function(){
					// fade in static map
					$('#staticmap').fadeIn('fast', function(){
						// done
						$('#destination_map').removeClass('destination-map-expanded');																			
					});
				});
				
			} else {
				// open
				// fade out static map
				$('#staticmap').fadeOut('fast', function(){

					// on complete, expand the mapcontainer to 470px high
					// this will reveal the loading div
					$('#mapcontainer').animate({ height: "470px" }, 'fast', 'swing', function(){
						
						$('#destination_map').addClass('destination-map-expanded');

						if ( ! map ) {
							// 1st time load 
							updateMapStatus( 0 );
							var url = "/map/nearby?lat=" + center.lat + "&lon=" + center.lon;
							$.getScript(url, function(){
								loadmap();
							});
						}

					}); // end mapcontainer height animation

				}); // end static map fadeout
			}
			return false;
		});

		$('body').unload(function(){
			GUnload();
		});
	}
	
});

// load+show map
function loadmap() {
	updateMapStatus( 1 );

	var mapdiv 	= $('#destination_map');
	
	var mapOptions = {
		googleBarOptions : {
			style : "new",
			adsOptions : {
				client: "partner-pub-3618432979403570",   // the Client ID of your Google AdSense for Search account (under Adsense -> MyAccount)
				channel: "3381600716",										// the channel number of your Google AdSense for Search account (skipjump-map)
				adsafe: "high",
				language: "en"
			}
		}
	}
	
	map = new GMap2( mapdiv[0], mapOptions );
	
	if (center) {
		map.setCenter(new GLatLng(center.lat, center.lon), center.alt);
	} else {
		// hardcode default, USA center
		map.setCenter(new GLatLng(36.65, -93.33), 2);
	}
				
	// add controls
	// map.addControl( new GMapTypeControl() );
	// map.addControl( new GLargeMapControl() );
	// map.setUIToDefault();
	
	var uiOpt = new GMapUIOptions( new GSize(770, 425) )
	uiOpt.controls.scalecontrol = false;
	
	// uiOpt.controls.maptypecontrol = false;
	// uiOpt.controls.menumaptypecontrol = true;

	map.setUI( uiOpt );	
	map.enableGoogleBar();

	//mapLoadedCallback = GEvent.addListener(map, "load", initializeMarkers);

	tilesLoadedCallback = GEvent.addListener(map, "tilesloaded", initializeMarkers);
}

function mapLoaded() {
	updateMapStatus( 2 );
	GEvent.removeListener( mapLoadedCallback );
}

// from markerclusterer example
// http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/examples/advanced_example.html
function initializeMarkers() {
	// updateMapStatus( 3 );
	
	var icon = new GIcon(G_DEFAULT_ICON);
	icon.image = "/assets/images/gmap_markers/24x32_green.png";
	// default size is 20x34
	icon.iconSize = new GSize(24,32);
	for (var i = 0; i < data.count; ++i) {
		
		// property values from json file
		var values = {id:data.listings[i][0], lat:data.listings[i][1], lon:data.listings[i][2]};
		
		// create a marker obj
		var latlng = new GLatLng(values.lat, values.lon);
		var marker = new GMarker(latlng, {icon: icon});

		// append values to our object
		marker.value = values;
		
		// assign a callback for when markerclusterer adds this marker to the map
		marker.callback = function( marker ){
			//var html = "<div>" + marker.value.id + ", lat: " + marker.value.lat + ", lon: " + marker.value.lon + "</div>";
			
			// add a click event, to grab property info
			var url  = '/map/ajax/lookup/' + marker.value.id;
			GEvent.addListener(marker, "click", function() {
				if (property_info[marker.value.id] != null) {						
					marker.openExtInfoWindow(
						map,
						"skipjump_infowin",
						property_info[marker.value.id],
						{beakOffset: 3}
					);
				} else {
					// open dummy window for loading text...
					marker.openExtInfoWindow(
						map,
						"skipjump_infowin",
						'<div class="loading">Loading Property Details... </div>',
						{beakOffset: 3}
					);
					$.get(url, {}, function(html){
						marker.closeExtInfoWindow( map );
						if (html == '') {
							// handle property not found
							alert('Property not found.');
						} else {
							property_info[marker.value.id] = html;
							marker.openExtInfoWindow(
								map,
								"skipjump_infowin",
								html,
								{beakOffset: 3}
							);
						}
					}, 'html');
				}
			});
			
			// add mouseover/out highlites
			GEvent.addListener(marker, "mouseover", function() {
				marker.setImage( "/assets/images/gmap_markers/24x32_green-hilite.png" );
			});
			GEvent.addListener(marker, "mouseout", function() {
				marker.setImage( icon.image );
			});
			
		};
		
		// add marker to the stack...
		markers.push(marker);
		
	}
	
	// map is loaded. some clean up
	if (mapLoadedCallback) GEvent.removeListener( mapLoadedCallback );
	if (tilesLoadedCallback) GEvent.removeListener( tilesLoadedCallback );

	refreshMap();
}

function refreshMap() {
	if (markerClusterer != null) {
		markerClusterer.clearMarkers();
	}
	/*
	var zoom = parseInt(document.getElementById("zoom").value, 10);
	var size = parseInt(document.getElementById("size").value, 10);
	var style = document.getElementById("style").value;
	*/
	zoom = null;
	size = null;
	style = null;
	markerClusterer = new MarkerClusterer(map, markers, {maxZoom: zoom, gridSize: size, styles: styles[style]});

	removeLoadingPanel();
}

function removeLoadingPanel() {
	$('#mapwait').css('z-index', '0');
}

function updateMapStatus( step ) {
	
	if (! mapStatusLabel) {
		mapStatusLabel = $('#mapstatus');
	}

	var tot = mapSteps.length
	var trk = (step + 1) + "/" + tot + ": ";
	var txt = trk + mapSteps[ step ];

	mapStatusLabel.html( mapSteps[ step ] );
}

// handle stepping thumbs back in infowindow
// expects param 'o' = a jquery obj representing the thumb container
function infowindow_prev( o ) {

	var imgs = o.find('p');
	var curr = Number( o.attr('_current') );
	var prev = curr - 1;	
	if (prev < 0) prev = imgs.length - 1;
	
	imgs.hide();
	$( imgs[prev] ).show();	
	o.attr('_current', prev);
	
	return false;
}

// handle stepping thumbs fwd in infowindow
// expects param 'o' = a jquery obj representing the thumb container
function infowindow_next( o ) {
	
	var imgs = o.find('p');
	var curr = Number( o.attr('_current') );
	var next = curr + 1;
	if (next > imgs.length - 1) next = 0;
	
	imgs.hide();
	$( imgs[next] ).show();	
	o.attr('_current', next);
	
	return false;
}

var styles = [[{
	url: '../images/people35.png',
	height: 35,
	width: 35,
	opt_anchor: [16, 0],
	opt_textColor: '#FF00FF'
},
{
	url: '../images/people45.png',
	height: 45,
	width: 45,
	opt_anchor: [24, 0],
	opt_textColor: '#FF0000'
},
{
	url: '../images/people55.png',
	height: 55,
	width: 55,
	opt_anchor: [32, 0]
}],
[{
	url: '../images/conv30.png',
	height: 27,
	width: 30,
	anchor: [3, 0],
	textColor: '#FF00FF'
},
{
	url: '../images/conv40.png', 
	height: 36,
	width: 40,
	opt_anchor: [6, 0],
	opt_textColor: '#FF0000'
},
{
	url: '../images/conv50.png',
	width: 50,
	height: 45,
	opt_anchor: [8, 0]
}],
[{
	url: '../images/heart30.png',
	height: 26,
	width: 30,
	opt_anchor: [4, 0],
	opt_textColor: '#FF00FF'
},
{
	url: '../images/heart40.png', 
	height: 35,
	width: 40,
	opt_anchor: [8, 0],
	opt_textColor: '#FF0000'
},
{
	url: '../images/heart50.png',
	width: 50,
	height: 44,
	opt_anchor: [12, 0]
}]];