var $paginator;

jq(function() {
	
	// MAP EXPAND
	jq('a#map_overlay').colorbox({ width: 800, height: 500, inline: true, href: '#map' });
	
	// STREAMING VIDEO COLORBOX
	setTimeout ( video_media, 1000 );
	
	jq('a.streaming').colorbox({ inline: true, href: '.media' });
	
	// CITY_SEARCH SEARCH - (what, where)
	jq('form#cs').submit(function() {
		var form  = this;

		jq('#cs_results').animate({height:0}, 300);
		jq('#cs_results p, #cs_results ul, #cs_err').empty().not('#cs_results p').fadeOut();
		if ( where_valid(form.where.value) ) {
			jq.getJSON(form.action + "?" + jq(form).serialize(), function(data) {
				if ( data.length ) {
					$paginator = new Paginator('cs_paginator', data, { per_page: 4, page_fn: write_pages });
				
					var page_height      = jq('#cs_results ul:first').outerHeight(true),
							paginate_height = jq('#cs_results .cs_paginator:first').outerHeight(true),
							result_height    = (page_height + 41);
							// the use of # 41 = lame ie hack (outerHeight not working)
					$what  = form.search.value,
					$where = form.where.value;

					jq('#cs_results').animate({ height: result_height }, 300);
				} else
					jq('#cs_err').html('Sorry, no results for "' + form.search.value + '" in ' + form.where.value).show();
			});
		} else
			jq('#cs_err').html("<p>Please enter a valid [city, state] OR [zipcode]</p><p>hint: check your spelling.</p>").show();
		return false;
	});
	
	// FEATURED NEIGHBORHOODS SLIDER
	// next slider button callback
	jq('#feature_nav #next').click(function() {
		var slider = slider_args('next');
		
		if ( slider['pane_id'] == 'pane_3' )
			slide_around('pane_1', 0);
		else
			slide_pane(slider);
		return false;
	});
	
	// previous slider button callback
	jq('#feature_nav #prev').click(function() {
		var slider = slider_args('prev');
				
		if ( slider['pane_id'] == 'pane_1' )
			slide_around('pane_3', -1420);
		else
			slide_pane(slider);
		return false;
	});
	
	jq('.indicator').click(function() {
		var current_pane  	= jq('.current'),
				current_pane_id = current_pane.attr('href'),
				target_pane_id  = jq(this).attr('href');
		
		if ( current_pane_id != target_pane_id ) {
			switch (target_pane_id) {
				case 'pane_1':
					slide_pane({ next_pane_number: 1, margin: 0 });
					break;
				case 'pane_3':
					slide_pane({ next_pane_number: 3, margin: -1420 });
					break;
				default:
					var slider = slider_args(get_direction());
					slide_pane(slider);
					break;
			}
		}
		return false;
	});
	
	jq('#search, #where').focus(function() {
		if ( this.value == this.defaultValue ) {
			this.value = '';
			this.style.color = '#000';
		}
	});
});

function video_media() {
	jq('a.media').media({ autoplay: true, caption: false, width: 320, height: 260 });
}

function where_valid(near) {
	var where = near.split(/,|\s/),
			state_or_zip = where[where.length - 1].toLowerCase();
	return ['dc', 'va', 'virginia', 'md', 'maryland'].include(state_or_zip) || state_or_zip.match(/^\d{5}$/);
}

function get_direction() {
	var current_pane_id = jq('.current').attr('href');
	return current_pane_id == 'pane_1' ? 'next' : 'prev';
}

// called to slide pane from one end to other end
// e.g. 1 - 3, 3 - 1
function slide_around(pane_id, margin) {
	var state = jq('#' + pane_id + ' #callout a').html().split(', ')[1];
	
	jq('.indicator').removeClass('current');
	jq('[href=' + pane_id + ']').addClass('current');
	jq('#slider').stop().animate({ marginLeft: margin }, 700);
	//jq('h2#feature span').html(state);
}

// called to advance slider to next position - [bidirectional]
function slide_pane(slider) {
	jq('.indicator').removeClass('current');
	jq('[href=pane_' + slider['next_pane_number'] + ']').addClass('current');
	jq('#slider').stop().animate({ marginLeft: slider['margin'] }, 700);
	slider['state'] = jq('#pane_' + slider['next_pane_number'] + ' #callout a').html().split(', ')[1];
	//jq('h2#feature span').html(slider['state']);
}

// return slider parameter object to use on advancing slider to next position
function slider_args(direction) {
	var incr, margin;
	
	if ( direction == 'next' )
		incr = 1, margin = '-=710px';
	else
		incr = -1, margin = '+=710px';
		
	var indicator = jq('.current'),
			pane_id = indicator.html(),
			next_pane_number = parseInt(pane_id.sub('pane_', '')) + incr;
				
	return {
		pane_id: pane_id,
		next_pane_number: next_pane_number,
		margin: margin
	};
}

function properties() {
	var city   = city_val(),
			county = county_val(),
			state  = state_val();
			
	jq.getJSON('/service/mapts', { city: city, county: county, state: state }, function(data) { init(data) });
}

function city_val() {
	return jq('input[name=city]').val();
}

function county_val() {
	return jq('input[name=county]').val();
}

function state_val() {
	return jq('input[name=state]').val();
}

// google latlng for center of map
function map_center(properties) {
	var lat_avg = 0,
			lng_avg = 0;
	
	for (var i = 0; i  < properties.length; i++) {
		lat_avg += parseFloat(properties[i]['latitude']);
		lng_avg += parseFloat(properties[i]['longitude']);
	}
	
	return new google.maps.LatLng(lat_avg / i, lng_avg / i);
}

function map_options() {			
	if ( city_val() )
		return { zoom: 12 };
	else if ( county_val() )
		return { zoom: 11 };
	else
		return { zoom: 10 };
}

// add property listing marker to map
function map_markers(props) {	
	for (var i = 0; i < props.length; i++) {
		var marker = new google.maps.Marker({
		      position: new google.maps.LatLng(props[i]['latitude'], props[i]['longitude']),
		      map: $map
			  }),
				contentString = '<div id="prop_info" style="width:340px;height:100px;"><a href="' + props[i]['url'] + '"><img src="/converter?img=' + props[i]['image'] + '&width=85&height=85&center-crop=1" alt="' + props[i]['name'] + '" /></a><div class="bus_info"><h5>' + props[i]['name'] + '</h5><p>' + props[i]['address'] + '<br/>' + props[i]['city'] + ', ' + props[i]['state'] + ' ' + props[i]['zip'] + '<br/>' + props[i]['phone'] + '<br/><a href="' + props[i]['url'] + '">view details</a></p><br/></div></div>',
				infowindow = new google.maps.InfoWindow({ content: contentString });
				
		add_infowindow(marker, infowindow);
		// google.maps.event.addListener(marker, 'click', function() { infowindow.open($map, marker) });
	}
}

function add_infowindow(marker, infowindow) {
	google.maps.event.addListener(marker, 'click', function() { infowindow.open($map, marker) });
}

function write_pages() {
	var list = jq('#cs_results ul'),
			data = this.entries;
	
	for ( var i = 0, data_count = data.length; i < data_count; i++ ) {
		list.eq(Math.floor(i / this.per_page)).append('<li><span class="rating"><a href="#" class="r_'+data[i]['rating']+'">rating: '+data[i]['rating']+'</a></span><p><a href="/neighborhood/profile.xml?id='+data[i]['listing_id']+'">'+data[i]['name']+'</a><br />'+data[i]['street']+'<br />'+data[i]['city']+', '+data[i]['state']+'<br />'+data[i]['phone_number']+'</p></li>');
	}
}


// ---------------- prototype ---------------- //
//Event.observe(document, 'dom:loaded', init); 
// ---------------- prototype ---------------- //
// function init()  { 
// 	var neighbor = $('nb_list');
// 	if (neighbor) {
// 		var panels = $$('.panel');
// 		panels.invoke('hide');
// 	}
// }

function toggle_cities(county) {
	var target = $(county);
	var parent = $(county).up();
	var clickText = parent.select('.action').first();
	if (target.visible()) {
		parent.removeClassName('open');
		parent.addClassName('closed');
		clickText.update('view cities');
		
	} else {
		parent.removeClassName('closed');
		parent.addClassName('open');
		clickText.update('hide cities');		
	}
	target.toggle();
}
// ---------------- prototype ---------------- //

if ( jq.browser.msie )
	document.write('<script type="text/javascript" src="/js/swfobject2.js"><\/script>');

