// JavaScript Document
var start_data = '';
var searched_data = '';
var gmap;

function CAP_showLoading(){
  new Element('div').addClass('search_alert').setText('Searching Property Listings').injectInside($('gmap_panel'));
}

function CAP_doSearch(){
	var search_options = new Object();
	if($('cap_beds_min').value != '') search_options['min_bedrooms'] = $('cap_beds_min').value;
	if($('cap_beds_max').value != '') search_options['max_bedrooms'] = $('cap_beds_max').value;
	if($('cap_baths_min').value != '') search_options['min_bathrooms'] = $('cap_baths_min').value;
	if($('cap_baths_max').value != '') search_options['max_bathrooms'] = $('cap_baths_max').value;
	if($('cap_size_min').value != '') search_options['min_size'] = $('cap_size_min').value;
	if($('cap_size_max').value != '') search_options['max_size'] = $('cap_size_max').value;
	if($('cap_price_min').value != '') search_options['min_price'] = $('cap_price_min').value;
	if($('cap_price_max').value != '') search_options['max_price'] = $('cap_price_max').value;
	if($('cap_house_type').value != '') search_options['unit_type'] = $('cap_house_type').value;
	if($('r2').checked == true){
		search_options['extra'] = 'subdivision';
		if($('cap_subdivision').value != '') search_options['subdivision'] = $('cap_subdivision').value;
	}else if($('r3').checked == true){
		search_options['extra'] = 'school';
		search_options['school_type'] = $('cap_school_type').value;
		switch(search_options['school_type']){
			case "high":
				if($('cap_school_high').value != '') search_options['school_name'] = $('cap_school_high').value;
				break;
			case "middle":
				if($('cap_school_middle').value != '') search_options['school_name'] = $('cap_school_middle').value;
				break;
			case "elementary":
				if($('cap_school_elementary').value != '') search_options['school_name'] = $('cap_school_elementary').value;
				break;
			default:
				break;
		}
	}else
		search_options['extra'] = 'none';
		
	// The search message should search
	CAP_showLoading();
	
	var search_msg = Json.toString(search_options);
	new Ajax(sroot+'homes/data/cap_table.php',{
		postBody:'search='+escape(search_msg),
		onComplete: function table_search_return(r,x){
			// Generate and store the table
			var json_item = Json.evaluate(r);
			searched_data = json_item;
			var table = GenerateTable(json_item);
			$('mytable').empty();
			$(table).injectInside($('mytable'));
			_Start_Effect_GrowTable($(table));
			$('gmap_panel').empty();
			GenerateMap($('gmap_panel'),json_item);
		}
	}).request();
}

function subGPoints(a,b) {return new GPoint(a.x-b.x, a.y-b.y);}

/*
	Generates the HTML necessary for the popup window
*/
function GenerateMHInfoWindow(pto) {
	var tmpDiv = new Element('div');
	// Generate the tabbing controls
	var scrollNext = new Element('div');
	scrollNext.setProperty('id','tab_scrollnext');
	var scrollBack = new Element('div');
	scrollBack.setProperty('id','tab_scrollback');
	scrollNext.injectInside(tmpDiv);
	scrollBack.injectInside(tmpDiv);
	
	// Generate the tabs from the chunks
	var tabsDiv = new Element('div');
	var relDiv = new Element('div');
	tabsDiv.setProperty('id','tabs');
	relDiv.injectInside(tabsDiv);
	
	// Generate the summary tab (on by default)
	var ts = new Element('span');
	var tl = new Element('a');
	var tp = new Element('div');
	tp.addClass('tab_page');
	tp.injectInside(tmpDiv);
	tp.setStyle('display','block');
	tl.injectInside(ts);
	tl.setText('Summary');
	ts.injectInside(relDiv);
	
	// the subdivision header
	var subinfo = new Element('div');
	subinfo.injectInside(tp);
	subinfo.addClass('sistyle');
	subinfo.setStyles({
		position: 'absolute',
		top: '5px',
		height: '22px',
		width: '100%',
		paddingTop: '3px',
		color: '#FFFFFF',
		fontWeight: 'bold',
		textAlign:'center'
	});
	subinfo.setText(pto['chunk'][0]['subtitle']);
	
	// create the thumbpan for the tabPage
	var atp = new Element('div');
	atp.addClass('thumb_panel');
	atp.injectInside(tp);
	atp.setStyle('background-image','url('+pto['chunk'][0]['thumb_big2']+')');
	atp.setStyles({
		top: '30px',
		height: '210px'
	});
	
	// create the infopane for the tabPage
	var aip = new Element('div');
	aip.addClass('info_panel');
	aip.injectInside(tp);
	aip.setStyles({
		top: '30px',
		height: '210px',
		overflow: 'auto'
	});
	
	// Create the specialized info_panel used by the subdivision information
	tl.addEvent('click',function(reldik,tabpag){
		$ES('span',reldik).each(function(el){
				el.addClass('alt');
		});
		this.removeClass('alt');
		// Set all display pages to none.
		$ES('div.tab_page',$('mhframe_contents')).each(function(el){
			el.setStyle('display','');
		});
		tp.setStyle('display','block');
	}.bind(ts,[relDiv, tp]));
	
	aip.setHTML('<div class="ipitem" style="font-weight:bold" >' + pto['chunk'].length + ' '+ (pto['chunk'].length > 1 ? "homes" : "home") +' matched your search:</div>');
	
	// Generate each of the REAL tabs
	for(var i=0; i<pto['chunk'].length; i++){
		//var tabDiv = new Element('div');
		var tabSpan = new Element('span');
		var tabLink = new Element('a');
		tabLink.injectInside(tabSpan);
		tabLink.setText(pto['chunk'][i]['ttitle']);
		tabSpan.injectInside(relDiv);
		tabSpan.addClass('alt');
		
		var tabPage = new Element('div');
		tabPage.addClass('tab_page');
		tabPage.injectInside(tmpDiv);

		// the subdivision header
		var subinfo = new Element('div');
		subinfo.injectInside(tabPage);
		subinfo.addClass('sistyle');
		subinfo.setStyles({
			position: 'absolute',
			top: '5px',
			height: '22px',
			width: '100%',
			paddingTop: '3px',
			color: '#FFFFFF',
			fontWeight: 'bold',
			textAlign:'center'
		});
		subinfo.setText(pto['chunk'][i]['address']);

		
		// create the thumbpan for the tabPage
		var thumbPanel = new Element('div');
		thumbPanel.addClass('thumb_panel');
		thumbPanel.injectInside(tabPage);
		thumbPanel.setStyle('background-image','url('+pto['chunk'][i]['thumb_big']+')');
		thumbPanel.setStyles({
			top: '30px',
			height: '210px'
		});
		if(pto['chunk'][i]['is_pending'] != ''){
			//add overlay - Sale Pending / Sold
			var saleOverlay = new Element('div');
			saleOverlay.addClass('inner_msg_overlay');
			saleOverlay.setStyle('top','90px');
			saleOverlay.injectInside(thumbPanel);
			saleOverlay.setText(pto['chunk'][i]['is_pending']);
		}
		
		// create the infopane for the tabPage
		var infoPanel = new Element('div');
		infoPanel.addClass('info_panel');
		infoPanel.injectInside(tabPage);
		infoPanel.setStyles({
			top: '30px',
			height: '210px',
			overflow: 'auto'
		});
		
		var wrapIt = function(a, b){
			return '<div class="ipitem"><strong>'+a+'</strong><br/>'+b+'</div>';
		}
		var checkVal = function(val){
			return val == "" || val == null || val == 0 ? "N/A" : val;
		}


		infoPanel.setHTML(	
							wrapIt('Home Type:',pto['chunk'][i]['unit_type'])+
							wrapIt('Lot #:', checkVal(pto['chunk'][i]['lot_num']) )+
							wrapIt('Beds/Baths:', checkVal(pto['chunk'][i]['beds']) + ' / ' + checkVal(pto['chunk'][i]['baths']) )+
							wrapIt('Total Area:', checkVal(pto['chunk'][i]['area']) )+
							wrapIt('Sales Price:', checkVal(pto['chunk'][i]['price']) )
						 );
		
		var proplink = new Element('a').setProperty('href',sroot+'subdivisions/'+pto['chunk'][0]['subtitle']+'/lot-'+pto['chunk'][i]['lot_num']+'.html').setHTML('<strong>Click Here to Learn More About '+ pto['chunk'][i]['address'] +'</strong>').injectInside(new Element('div').addClass('ipitem').setStyle('text-align','center').injectInside(infoPanel));
		
		// The tabclick function
		var click_this = function(reldik,tabpag){
			$ES('span',reldik).each(function(el){
				el.addClass('alt');
			});
			this.removeClass('alt');
			// Set all display pages to none.
			$ES('div.tab_page',$('mhframe_contents')).each(function(el){
				el.setStyle('display','');
			});
			// Now show our page
			tabpag.setStyle('display','block');
		}.bind(tabSpan,[relDiv, tabPage])
		
		// Attach an event to the tab
		tabLink.addEvent('click',click_this);
		
		// add the link to the summary
		tlx = new Element('a');
		tlx.setStyle('display','block');
		tlx.setStyle('margin','5px');
		tlx.setText(pto['chunk'][i]['address']);
		tlx.injectInside(aip);
		tlx.addEvent('click',click_this);
	}
	
	// This is the link to the subdivision
	var sublink = new Element('a').setProperty('href',sroot+'subdivisions/'+pto['chunk'][0]['subtitle']+'.html').setHTML('<strong>Click Here to Learn More About '+pto['chunk'][0]['subtitle']+'</strong>').injectInside(new Element('div').addClass('ipitem').addClass('ipitem_bottom_link').setStyle("text-align","center").injectInside(aip));
	
	// Inject a relative positioning div of width 1px for the scroller to detect the width
	var scrollPosMarker = new Element('div');
	scrollPosMarker.setStyle('float','left');
	scrollPosMarker.setStyle('width','1px');
	scrollPosMarker.injectInside(relDiv);
	
	// Inject the temporary div
	tabsDiv.injectInside(tmpDiv);
	
	// Attach events to the scrolling mechanisms
	tabsDiv.scrollx = 0;
	scrollBack.setStyle('display','none');
	scrollNext.addEvent('click',function(){
		this.scrollx = this.scrollx + 100;
		scrollBack.setStyle('display','');
		var fx = new Fx.Scroll(this);
		fx.scrollTo(this.scrollx,0);
	}.bind(tabsDiv));
	scrollBack.addEvent('click',function(){
		this.scrollx = this.scrollx - 100;
		if(this.scrollx <= 0) scrollBack.setStyle('display','none');
		var fx = new Fx.Scroll(this);
		fx.scrollTo(this.scrollx,0);									 	
	}.bind(tabsDiv));
	
	return tmpDiv;
}

function GenerateMap(mapel,mapobj){
	// defaults used by generate map
	var icondir = sroot+'homes/images/special/map01/';
	
	// Create the base ICON to duplicate
    var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);
	
	if(mapobj['points'] && mapobj['points'].length > 0)
	{
		// generate and attach the map
		var map = new GMap2(mapel);
		
		// Disable dragging by default
		//gmap.disableDragging();
		map.disableDoubleClickZoom();
		map.lmcontrol = new GLargeMapControl();
		map.addControl(map.lmcontrol);
		
		var bigLat = parseFloat(mapobj['points']['lat']);
		var smallLat = bigLat;
		var bigLon = parseFloat(mapobj['points']['lon']);
		var smallLon = bigLon;
		
		// Determine the center before we do anything
		var pti = 0;
		for(pti=0; pti<mapobj['points'].length; pti++){
			var pto = mapobj['points'][pti];
			var slat = parseFloat(pto['lat']);
			var slon = parseFloat(pto['lon']);
			// Update the boundings
			bigLat = (bigLat > slat) ? bigLat : slat;
			smallLat = (slat > smallLat) ? smallLat : slat;
			bigLon = (bigLon > slon) ? bigLon : slon;
			smallLon = (slon > smallLon) ? smallLon : slon;			
		}
		
		// We not find the midpoint of each of the items
		map.cLat = ((bigLat + smallLat) / 2);
		map.cLon = ((bigLon + smallLon) / 2);
		map.setCenter(new GLatLng(map.cLat, map.cLon), 11, G_NORMAL_MAP);
		
		// Go through each of the points (Grouped Geographical Coordinates) and create the icons and bind to the templated display
		for(pti=0; pti<mapobj['points'].length; pti++){
			var pto = mapobj['points'][pti];
			var ucount = pto['item_count'];
			var slat = parseFloat(pto['lat']);
			var slon = parseFloat(pto['lon']);
			
			// generate the custom icon
			var custom_icon = new GIcon(baseIcon);
			custom_icon.image = icondir+ucount+'.png';
			var marker = new GMarker(new GLatLng(slat,slon),{ icon: custom_icon});
			
			GEvent.addListener(marker, 'click', function(info){
				map.removeControl(map.lmcontrol);
				delete map.lmcontrol;
				var contents = GenerateMHInfoWindow(info);
				this.openExtInfoWindow(map, "mhframe", '', {beakOffset: 2, suppressMapPan:true});
				contents.getChildren().each(function(el){
					el.injectInside($('mhframe_contents'));
				});
				var point = this.getPoint(); 
				var CDivPixel = map.fromLatLngToDivPixel(map.getCenter()); 
				var pointDivPixel = map.fromLatLngToDivPixel(point);
				var dist = subGPoints(CDivPixel,pointDivPixel);
				map.panBy(new GSize(dist.x-5,dist.y+125));
			}.bind(marker,pto));
		  
			map.addOverlay(marker);
		}
		
		// Attach the events
		
		// This updates the center position when the map is drug
		GEvent.addListener(map, "dragend", function(){
			var ncenter = map.getCenter();
			map.cLat = ncenter.lat();
			map.cLon = ncenter.lng();
		});
		
		GEvent.addListener(map, "extinfowindowclose", function(){
			map.panTo(new GLatLng(map.cLat, map.cLon), 11, G_NORMAL_MAP);
			map.lmcontrol = new GLargeMapControl();
			map.addControl(map.lmcontrol);
		});
		
	}else{
		// Set the map styles
		mapel.setStyle('background-color','#FFFFFF');
		
		var helpDiv = new Element('div');
		helpDiv.setStyles({
			position:'absolute',
			left:'150px',
			top:'200px',
			fontFamily:'Arial',
			fontSize:'18px'
		});
		helpDiv.injectInside(mapel);
		
		helpDiv.setText('No homes matched your search criteria');
		
		// Figure out the center of the map and place your objec
		//mapel.setHTML('No homes matched your search criteria.');
	}
	
	// Return the new map object
	return mapel;
}

function GenerateFirstMap(mapel,mapobj){
	var icondir = sroot+'homes/images/special/map01/';
	
	// Generate the MAP OBJECT
	if(mapobj['points'] && mapobj['points'].length > 0){
		// generate and attach the map
		var map = new GMap2(mapel);
		
		// Disable dragging by default
		//gmap.disableDragging();
		map.disableDoubleClickZoom();
		map.lmcontrol = new GLargeMapControl();
		map.addControl(map.lmcontrol);
		
		var bigLat = parseFloat(mapobj['points']['lat']);
		var smallLat = bigLat;
		var bigLon = parseFloat(mapobj['points']['lon']);
		var smallLon = bigLon;
		
		// Determine the center before we do anything
		var pti = 0;
		for(pti=0; pti<mapobj['points'].length; pti++){
			var pto = mapobj['points'][pti];
			var slat = parseFloat(pto['lat']);
			var slon = parseFloat(pto['lon']);
			// Update the boundings
			bigLat = (bigLat > slat) ? bigLat : slat;
			smallLat = (slat > smallLat) ? smallLat : slat;
			bigLon = (bigLon > slon) ? bigLon : slon;
			smallLon = (slon > smallLon) ? smallLon : slon;			
		}
		
		// We not find the midpoint of each of the items
		map.cLat = ((bigLat + smallLat) / 2);
		map.cLon = ((bigLon + smallLon) / 2);
		map.setCenter(new GLatLng(map.cLat, map.cLon), 11, G_NORMAL_MAP);
		
		// Create the base ICON to duplicate
		var baseIcon = new GIcon();
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);
		
		// Go through each of the points (Grouped Geographical Coordinates) and create the icons and bind to the templated display
		for(pti=0; pti<mapobj['points'].length; pti++){
			var pto = mapobj['points'][pti];
			var ucount = pto['item_count'];
			var slat = parseFloat(pto['lat']);
			var slon = parseFloat(pto['lon']);
			
			// generate the custom icon
			var custom_icon = new GIcon(baseIcon);
			custom_icon.image = icondir+pto['chunk'][0]['units']+'.png';
			var marker = new GMarker(new GLatLng(slat,slon),{ icon: custom_icon});
			
			GEvent.addListener(marker, 'click', function(info){
				// remove the zoom control
				map.removeControl(map.lmcontrol);
				delete map.lmcontrol;
				
				// Open the Info Window
				this.openExtInfoWindow(map, "mhframe", '', {beakOffset: 2, suppressMapPan:true});
				
				// the tabs
				var tabs = new Element('div').injectInside(new Element('div').setProperty('id','tabs').injectInside($('mhframe_contents')));
				var tab = new Element('a').setProperty('href','#').setText(info['chunk'][0]['subtitle']).injectInside(new Element('span').injectInside(tabs));
				var tab_page = new Element('div').addClass('tab_page').setStyle('display','block').injectInside($('mhframe_contents'));
				var sstyle = new Element('div').addClass('sistyle').setStyles({
					position: 'absolute',
					top: '5px',
					height: '22px',
					width: '100%',
					paddingTop: '3px',
					color: '#FFFFFF',
					fontWeight: 'bold',
					textAlign:'center'}).setText(info['chunk'][0]['subtitle']).injectInside(tab_page);
				var info_pan = new Element('div').addClass('info_panel').setStyles({
					'top':'30px',
					'text-align':'center',
					'height':'210px'}).injectInside(tab_page);
				var point1 = new Element('div').addClass('ipitem').setStyle('margin-top','30px').setHTML('<strong>'+info['chunk'][0]['units']+' '+ (info['chunk'][0]['units'] > 1 ? "homes" : "home") +' currently available from:</strong><br/>'+info['chunk'][0]['price']).injectInside(info_pan);
				var point3a = new Element('div').addClass('ipitem').setHTML('<strong>with square footage from:</strong><br/>'+info['chunk'][0]['area']).injectInside(info_pan);
				var sublink = new Element('a').setProperty('href',sroot+'subdivisions/'+info['chunk'][0]['subtitle']+'.html').setText('Click Here to Learn More About '+info['chunk'][0]['subtitle']).injectInside(new Element('div').addClass('ipitem').addClass('ipitem_bottom_link').injectInside(info_pan));
				var thumb = new Element('div').addClass('thumb_panel').setStyles({
					'background-image':'url('+info['chunk'][0]['thumb_big']+')',
					'top':'30px',
					'height':'210px'}).injectInside(tab_page);
				
				
				// Center the window
				var point = this.getPoint(); 
				var CDivPixel = map.fromLatLngToDivPixel(map.getCenter()); 
				var pointDivPixel = map.fromLatLngToDivPixel(point);
				var dist = subGPoints(CDivPixel,pointDivPixel);
				map.panBy(new GSize(dist.x-5,dist.y+125));
			}.bind(marker,pto));
		  
			map.addOverlay(marker);
		}
		
		// Attach the events
		
		// This updates the center position when the map is drug
		GEvent.addListener(map, "dragend", function(){
			var ncenter = map.getCenter();
			map.cLat = ncenter.lat();
			map.cLon = ncenter.lng();
		});
		
		GEvent.addListener(map, "extinfowindowclose", function(){
			map.panTo(new GLatLng(map.cLat, map.cLon), 11, G_NORMAL_MAP);
			map.lmcontrol = new GLargeMapControl();
			map.addControl(map.lmcontrol);
		});
		
	}else{
		// Set the map styles
		mapel.setStyle('background-color','#FFFFFF');
		
		var helpDiv = new Element('div');
		helpDiv.setStyles({
			position:'absolute',
			left:'150px',
			top:'200px',
			fontFamily:'Arial',
			fontSize:'18px'
		});
		helpDiv.injectInside(mapel);
		
		helpDiv.setText('No homes matched your search criteria');
		
		// Figure out the center of the map and place your objec
		//mapel.setHTML('No homes matched your search criteria.');
	}
	
	// Return the new map object
	return mapel;
}

function StartCap(){
	// Speed up DOM searching
	var search_box = $('search_box');
	var search_options = $('cap_narrow',search_box);
	
	// Set up the radio button events
	var r1 = $('r1',search_options);
	var r2 = $('r2',search_options);
	var r3 = $('r3',search_options);
	var change_option = function(){
		$ES('div',search_options).each(function(el)
		{
			el.setStyle('display','none');
		});
		if(this != 0)
			this.setStyle('display','block');
	};
	r1.addEvent('click',change_option.bind(0));
	r2.addEvent('click',change_option.bind($('cap_subdivs'),search_options));
	r3.addEvent('click',change_option.bind($('cap_schools'),search_options));
	
	// Set up the events for the home change
	var school_type = $('cap_school_type',search_options);
	school_type.addEvent('change',function(e){
		var school_set = $ES('select',$('cap_schools'));
		for(var i=1; i<school_set.length; i++){
			school_set[i].setStyle('display','none');
		}
		school_set[this.selectedIndex+1].setStyle('display','');
	}.bindWithEvent(school_type));
	
	// Set up the buttons
	$('submit_button').addEvent('click',CAP_doSearch);
	$('reset_button').addEvent('click',function(){
		var table = GenerateTable(start_data);
		$('mytable').empty();
		table.injectInside($('mytable'));
		$('gmap_panel').empty();
		GenerateFirstMap($('gmap_panel'),start_data);
		_Start_Effect_GrowTable(table);
		$ES('select',$('search_box')).each(function(el){el.selectedIndex = 0;});
	});
	
	// Load up the subdivision data
	new Ajax(sroot+'homes/data/tbl_subdivs.php',{
		postBody:'sample=ok',
		onComplete: function table_start_return(r,x){
			// Store the initial object
			start_data = Json.evaluate(r);
			// Generate and store the table
			var table = GenerateTable(start_data);
			$('mytable').empty();
			table.injectInside($('mytable'));
			_Start_Effect_GrowTable(table);
			$('gmap_panel').empty();
			GenerateFirstMap($('gmap_panel'),start_data);
		}
	}).request();
}

window.addEvent('domready',StartCap);
