/*
* MapBuilder Integrator 2.1.0
* Copyright(c) 2006-2008, Mashup Technologies, LLC.
* http://mashuptechnologies.com
*/


//Register app.se32bj namespace
Ext.namespace('MapObject.app.CM');

/* Register popup template */
MapObject.widget.MapViewer.prototype.popupTemplate = new Ext.Template(
'<div class="info-window">'+
		'<!-- ImageReady Slices (popup_mockup.psd) -->'+
		'<TABLE WIDTH=331 BORDER=0 CELLPADDING=0 CELLSPACING=0>'+
		'	<TR>'+
		'		<TD>'+
		'			<IMG SRC="{webPath}media/images/popup/popup_mockup_back_01.png" WIDTH=331 HEIGHT=9 ALT=""></TD>'+
		'	</TR>'+
		'	<TR>'+
		'		<TD width="331" background="{webPath}media/images/popup/popup_mockup_back_02.png"><table width="100%" border="0" cellspacing="0" cellpadding="0">'+
		'          <tr>'+
		'            <td><div align="center">'+
		'              <table width="317" height="27" border="0" align="center" cellpadding="0" cellspacing="0">'+
		'                <tr>'+
		'                  <td background="{webPath}media/images/popup/title_bar.png">' +
		'					<div align="center" class="tooltip-style1">{title}</div></td>'+
		'                </tr>'+
		'              </table>'+
		'            </div></td>'+
		'          </tr>'+
		'          <tr>'+
		'            <td><div align="center">'+
		'              <table width="100%" border="0" cellspacing="3" cellpadding="2">'+
		'                <tr>'+
		'                  <td><div align="center"><img src="{photoUrl}" width="305" height="203" border="2"></div></td>'+
		'                </tr>'+
		'              </table>'+
		'            </div></td>'+
		'          </tr>'+
		'          <tr>'+
		'            <td><div align="center" class="tooltip-style4">.:Cabin Description:. </div></td>'+
		'          </tr>'+
		'          <tr>'+
		'            <td><table width="94%" border="2" align="center" cellpadding="2" cellspacing="3" bordercolor="#333333">'+
		'              <tr>'+
		'                <td bgcolor="#666666"><span class="tooltip-style2">{beds}'+
		'				</span></td>'+
		'              </tr>'+
		'            </table></td>'+
		'          </tr>'+
		'          <tr>'+
		'            <td><div align="center">'+
		'              <table width="100%" border="0" align="center" cellpadding="2" cellspacing="2">'+
		'                <tr>'+
		'                  <td><div align="center">{mountainview}</div></td>'+
		'                  <td><div align="center">{hottub}</div></td>'+
		'                  <td><div align="center">{pets}</div></td>'+
		'                  <td><div align="center">{smoking}</div></td>'+
		'                </tr>'+
		'              </table>'+
		'            </div></td>'+
		'          </tr>'+
		'          <tr>'+
		'            <td><div align="center" class="tooltip-style3"><a title="VIEW DETAILS" href="{details_link}" target="_blank">VIEW DETAILS</a> | <a target="_blank" title="PRINT BROCHURE" href="{brochure_link}">PRINT BROCHURE</a> ' +
		'			</div></td>'+
		'          </tr>'+
		'        </table></TD>'+
		'	</TR>'+
		'	<TR>'+
		'		<TD>'+
		'			<IMG SRC="{webPath}media/images/popup/popup_mockup_back_03.png" WIDTH=331 HEIGHT=9 ALT=""></TD>'+
		'	</TR>'+
		'</TABLE>'+
		'<!-- End ImageReady Slices -->' +
		'</div>'
).compile();

/* Register popup template - weather */
MapObject.widget.MapViewer.prototype.popupTemplateWeather = new Ext.Template(
'<div class="info-window">'+
		'<!-- ImageReady Slices (popup_mockup.psd) -->'+
		'<TABLE WIDTH=331 BORDER=0 CELLPADDING=0 CELLSPACING=0>'+
		'	<TR>'+
		'		<TD>'+
		'			<IMG SRC="{webPath}media/images/popup/popup_mockup_back_01.png" WIDTH=331 HEIGHT=9 ALT=""></TD>'+
		'	</TR>'+
		'	<TR>'+
		'		<TD width="331" background="{webPath}media/images/popup/popup_mockup_back_02.png"><table width="100%" border="0" cellspacing="0" cellpadding="0">'+
		'          <tr>'+
		'            <td><div align="center">'+
		'              <table width="317" height="27" border="0" align="center" cellpadding="0" cellspacing="0">'+
		'                <tr>'+
		'                  <td background="{webPath}media/images/popup/title_bar.png">' +
		'					<div align="center" class="tooltip-style1">{title}</div></td>'+
		'                </tr>'+
		'              </table>'+
		'            </div></td>'+
		'          </tr>'+
		''+
		'			<tr>'+
		'				<td><div align="center">'+
		'				<table width="100%" border="0" cellspacing="3" cellpadding="2">'+
		'					<tr>'+
		'                '+
		'					</tr>'+
		'					<tr>'+
		'					<td><div align="center" class="style3 style5">BOOK NOW CLICK HERE! </div></td>'+
		'					</tr>'+
		'				</table>'+
		'				</div></td>'+
		'			</tr>'+
		'			<tr>'+
		'				<td><div align="center" class="style4">.:Cabin Weather:. </div></td>'+
		'			</tr>'+
		'			<tr>'+
		'				<td><table width="94%" border="2" align="center" cellpadding="1" cellspacing="1" bordercolor="#333333">'+
		'				<tr>'+
		'					<td bgcolor="#666666">'+
		'					<div style="width: 300px; height: 250px; background-image: url( http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/fall1_300x250_bg.jpg ); background-repeat: no-repeat; background-color: #E3B589;" >'+
		'						<div style="height: 238px;" >'+
		'<object type="application/x-shockwave-flash" data="http://netweather.accuweather.com/adcbin/netweather_v2/netwx-v29.swf" height="300" width="250" align="top">    '+
		'	<param name="movie" value="http://netweather.accuweather.com/adcbin/netweather_v2/netwx-v29.swf" />'+
		'	<param name="allowScriptAccess" value="never" />'+
		'	<param name="allowNetworking" value="internal" />'+
		'	<param name="quality" value="high" />'+
		'	<param name="scale" value="noscale" />    '+
		'	<param name="salign" value="lt" />    '+
		'	<param name="wmode" value="transparent" />    '+
		'	<param name="bgcolor" value="#ffffff" />    '+
		'	<param name="flashvars" value="partner=netweather&myspace=1&logo=1&tStyle=normal&zipcode=37738&lang=eng&size=212&theme=1&metric=0" />'+
		'</object>'+
		''+
		'						</div>'+
		'					</div></td>'+
		'				</tr>'+
		'				</table></td>'+
		'			</tr>'+
		'			<tr>'+
		'				<td><div align="center">'+
		'				<table width="100%" border="0" align="center" cellpadding="2" cellspacing="2">'+
		'					<tr>'+
		'                  '+
		'					</tr>'+
		'					<tr>'+
		'                 '+
		'					</tr>'+
		'				</table>'+
		'				</div></td>'+
		'			</tr>'+
		''+
		'          <tr>'+
		'            <td><div align="center" class="tooltip-style3"><a title="VIEW DETAILS" href="{details_link}" target="_blank">VIEW DETAILS</a> | <a target="_blank" title="PRINT BROCHURE" href="{brochure_link}">PRINT BROCHURE</a> ' +
		'            </div></td>'+
		'          </tr>'+
		'        </table></TD>'+
		'	</TR>'+
		'	<TR>'+
		'		<TD>'+
		'			<IMG SRC="{webPath}media/images/popup/popup_mockup_back_03.png" WIDTH=331 HEIGHT=9 ALT=""></TD>'+
		'	</TR>'+
		'</TABLE>'+
		'<!-- End ImageReady Slices -->' +
		'</div>'
).compile();

/* Register popup template - book */
MapObject.widget.MapViewer.prototype.popupTemplateCalendar = new Ext.Template(
'<div class="info-window">'+
		'<!-- ImageReady Slices (popup_mockup.psd) -->'+
		'<TABLE WIDTH=331 BORDER=0 CELLPADDING=0 CELLSPACING=0>'+
		'	<TR>'+
		'		<TD>'+
		'			<IMG SRC="{webPath}media/images/popup/popup_mockup_back_01.png" WIDTH=331 HEIGHT=9 ALT=""></TD>'+
		'	</TR>'+
		'	<TR>'+
		'		<TD width="331" background="{webPath}media/images/popup/popup_mockup_back_02.png"><table width="100%" border="0" cellspacing="0" cellpadding="0">'+
		'          <tr>'+
		'            <td><div align="center">'+
		'              <table width="317" height="27" border="0" align="center" cellpadding="0" cellspacing="0">'+
		'                <tr>'+
		'                  <td background="{webPath}media/images/popup/title_bar.png">' +
		'					<div align="center" class="tooltip-style1">{title}</div></td>'+
		'                </tr>'+
		'              </table>'+
		'            </div></td>'+
		'          </tr>'+
		''+

		'		<tr>'+
		'		<td><div align="center">'+
		'			<table width="100%" border="0" cellspacing="3" cellpadding="2">'+
		'			<tr>'+
		'				<td><div align="center"><span class="style4">.:Cabin Schedule:. </span></div></td>'+
		'			</tr>'+
		'			<tr>'+
		'				<td><div align="center"><img src="{webPath}media/images/popup/untitledcalendar.jpg" width="208" height="203"></div></td>'+
		'			</tr>'+
		'			<tr>'+
		'				<td><div align="center" class="style3 style5">BOOK NOW CLICK HERE! </div></td>'+
		'			</tr>'+
		'			</table>'+
		'		</div></td>'+
		'		</tr>'+
		'		<tr>'+
		'			<td><div align="center" class="style4"><img src="{webPath}media/images/popup/adbanner.jpg" width="275" height="78"></div></td>'+
		'		</tr>'+
		'		<tr>'+
		'			<td></td>'+
		'		</tr>'+

		'			<tr>'+
		'				<td><div align="center">'+
		'				<table width="100%" border="0" align="center" cellpadding="2" cellspacing="2">'+
		'					<tr>'+
		'                  '+
		'					</tr>'+
		'					<tr>'+
		'                 '+
		'					</tr>'+
		'				</table>'+
		'				</div></td>'+
		'			</tr>'+
		''+
		'          <tr>'+
		'            <td><div align="center" class="tooltip-style3"><a title="VIEW DETAILS" href="{details_link}" target="_blank">VIEW DETAILS</a> | <a target="_blank" title="PRINT BROCHURE" href="{brochure_link}">PRINT BROCHURE</a> ' +
		'            </div></td>'+
		'          </tr>'+
		'        </table></TD>'+
		'	</TR>'+
		'	<TR>'+
		'		<TD>'+
		'			<IMG SRC="{webPath}media/images/popup/popup_mockup_back_03.png" WIDTH=331 HEIGHT=9 ALT=""></TD>'+
		'	</TR>'+
		'</TABLE>'+
		'<!-- End ImageReady Slices -->' +
		'</div>'
).compile();

/**
* onMarker click event. It selects grid row and fires rowclick event.
* @param {mixed} marker Record id.
* @return none
*/
MapObject.widget.MapViewer.prototype.onMarkerClick = function (marker) {

		//Select a matching record on a grid
		var index = this.ds.indexOfId(marker.id);
		// Pass second argument to keep existing selection
		this.grid.getSelectionModel().selectRow(index, this.ctrlKey);
		
		// This trigures a problem after data set reloading
		//this.grid.fireEvent('rowclick');
		
		// Scroll selected row into view
		if (this.focusGridRow) {
			var view = this.grid.getView();
			view.getRow(index).scrollIntoView();
		}
		// Find active record
		record = this.ds.getById(marker.id);
		// show InfoWindow
		var title = record.get('title');
		var beds = record.get('beds');
		var link = '<br/><a target="_blank" href="' + record.get('detailUrl') + '" title="View Details">View Details</a>' ;
		var linkBrochure = ' - <a target="_blank" href="' + record.get('brochureUrl') + '" title="Print Brochure">Print Brochure</a>' ;
		var updatelink = '';
		/*
		var html = '<div class="info-window"><h2>' + title + '</h2> ' + beds +' <br/>' +  
			'<img src="' + record.get('photoUrl') + '"/>' +  
			link + linkBrochure + updatelink + '</div>';
		*/

		//if single cabin display go direct to JMH page for that cabin /testing this on false is weak but easy for now research)
		if (this.cabin_switch) {
			
		var html = this.popupTemplate.apply(
        	{
        		webPath: this.webPath,
				title: record.get('title'), 
				beds: record.get('beds'), 
				photoUrl: record.get('photoUrl'),
				details_link: record.get('detailUrl'), 
				brochure_link: record.get('brochureUrl'),
				//http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=37.610968,+-122.439709
				//directions_link: 'http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=&daddr=' + encodeURIComponent(record.get('title')) + '@' + encodeURIComponent(record.get('lat')) + ',' + encodeURIComponent(record.get('lng')),

				mountainview: ((record.get('mountainView') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/view.gif" width="70" height="25">' : '&nbsp;'),
				hottub: ((record.get('hotTub') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/tub.gif" width="50" height="36">' : '&nbsp;'),
				pets: ((record.get('pets') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/dog.gif" width="50" height="42">' : '&nbsp;'),
				smoking: ((record.get('smoking') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/cigarettenon.gif" width="39" height="38">' : '&nbsp;'),

				EOF:null
			}                                                                                          
		);

		var htmlWeather = this.popupTemplateWeather.apply(
        	{
        		webPath: this.webPath,
				title: record.get('title'), 
				beds: record.get('beds'), 
				photoUrl: record.get('photoUrl'),
				details_link: record.get('detailUrl'), 
				brochure_link: record.get('brochureUrl'),
				//http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=37.610968,+-122.439709
				//directions_link: 'http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=&daddr=' + encodeURIComponent(record.get('title')) + '@' + encodeURIComponent(record.get('lat')) + ',' + encodeURIComponent(record.get('lng')),

				mountainview: ((record.get('mountainView') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/view.gif" width="70" height="25">' : '&nbsp;'),
				hottub: ((record.get('hotTub') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/tub.gif" width="50" height="36">' : '&nbsp;'),
				pets: ((record.get('pets') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/dog.gif" width="50" height="42">' : '&nbsp;'),
				smoking: ((record.get('smoking') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/cigarettenon.gif" width="39" height="38">' : '&nbsp;'),

				EOF:null
			}                                                                                          
		);
		var htmlCalendar = this.popupTemplateCalendar.apply(
        	{
        		webPath: this.webPath,
				title: record.get('title'), 
				beds: record.get('beds'), 
				photoUrl: record.get('photoUrl'),
				details_link: record.get('detailUrl'), 
				brochure_link: record.get('brochureUrl'),
				//http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=37.610968,+-122.439709
				//directions_link: 'http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=&daddr=' + encodeURIComponent(record.get('title')) + '@' + encodeURIComponent(record.get('lat')) + ',' + encodeURIComponent(record.get('lng')),

				mountainview: ((record.get('mountainView') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/view.gif" width="70" height="25">' : '&nbsp;'),
				hottub: ((record.get('hotTub') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/tub.gif" width="50" height="36">' : '&nbsp;'),
				pets: ((record.get('pets') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/dog.gif" width="50" height="42">' : '&nbsp;'),
				smoking: ((record.get('smoking') == 'Y') ? '<img src="' + this.webPath + 'media/images/popup/cigarettenon.gif" width="39" height="38">' : '&nbsp;'),

				EOF:null
			}                                                                                          
		);
		
		// Hide tooltip
		this.mapViewer.getMapProxy().getTooltip().style.visibility = "hidden";		
		// Open info window 
		//this.mapViewer.getMapProxy().mapObject.openInfoWindowHtml(marker.getLatLng(), html);
		this.mapViewer.getMapProxy().mapObject.openInfoWindowTabsHtml(
			marker.getLatLng(),
			[
				new GInfoWindowTab("General Info", html),
//				new GInfoWindowTab("Book It Now", htmlCalendar),
				new GInfoWindowTab("Weather", htmlWeather)
			]);
		//create the date picker
		//var myDP = new Ext.DatePicker();
		//render the date picker
		//myDP.render('calendar');
		}
		//if cabinswitch false
		else {
			// Hide tooltip
			this.mapViewer.getMapProxy().getTooltip().style.visibility = "hidden";
			winref = window.open(record.get(('detailUrl'),"left=20,top=40,width=400,height=400",resizable="no"));	//detail url is from find active record above
			}; //if cabinswitch = "false"
};

/**
 * tooltipTemplate component designed to fetch and render a tooltip block for the individual datasource record.
 * @namespace MapObject.app.vc
 * @class tooltipTemplate
 * @constructor
 * @param {Ext.data.Store} The instance of data source store object.
 */
MapObject.app.CM.tooltipTemplate = function(ds)
{
	this.init(ds);
};
MapObject.app.CM.tooltipTemplate.prototype = {

	/**
	* Data store
	* @private
	* @type {Ext.data.Store}
	*/
	ds: null,

	/**
	* Tooltip template
	* @private
	* @type {Ext.Template}
	*/
	template: null,

    // Constructor
    init : function(ds){

    	this.ds = ds;// take with Ext.data.Store in {}
    	
    	
    	    	
		this.template = new Ext.Template(
//			'<style type="main/css"> .h2color {text-align:right;}</style>' +			//couldn't get html 4.01 class ref working for h2 below
//			'<style type="main/css"> .h2color {color : "{areacolor}";}</style>' +		// got it working from css but not here		
			'<div class="tooltip">' +
			'<h2>{title}</h2>' +
			'<div class="tooltip-container">' +
			'<h4>{beds}</h4>' +
			'<img width="305" height="203" src="{photoUrl}"/>' +
			'<div class = "h2color">' +
			'<h2 style = "color : {areacolor} ;"> {area} Area</h2></div>' + 		//this might need depricated
			'<h3>click on a marker for details</h3></div></div>'											
		);

//		this.template.compile();

    },

	/**
	* Show a tooltip for a given record id
	* @param {String} record id
	* @return none
	*/
    getHTML: function(id) {

    	var record = this.ds.getById(id);
    	var area ;
    	var acolor ;
    		
    	
    //Set Color of Cabin Area font to match area icon
    	area = record.get('area');
    	switch (area){ 
    	case 'Ski Mountain': acolor = '#CCFFFF'; break;			//Ski Mountain
    	case 'The Spur/Highway 441': acolor = '#ADFF2F'; break;	//Spur
    	case 'Dudley Creek': acolor = '#9933CC'; break;			//Dudley
    	case 'Roaring Fork': acolor = '#FFFFCC'; break;			//Roaring Falls
    	case 'Black Bear Falls': acolor = '#CC0033'; break;		//BBF
    	case 'Arts & Crafts Loop': acolor = '#FF1493'; break;	//Crafts/Arts
    	case 'Birds Creek Road': acolor = '#3366CC'; break;		//Birds Creek
    	case 'East Highway 321': acolor = '#FF8C00'; break;		//East Highway
    	case 'Downtown Gatlinburg': acolor = '#D2691E'; break;	//Downtown
    	case 'The Spur/Highway 441': acolor = '#6495ED'; break;	//GREYSTONE HEIGHT
    	default: acolor = '#FF8C00';
    	}
    	
    	
        return this.template.apply(
        	{
				title: record.get('title'), 
				beds: record.get('beds'), 
				photoUrl: record.get('photoUrl'),
				areacolor: acolor,												
				area: record.get('area')
			}                                                                                          
		);
    },

	/**
	* Hide the tooltip block.
	* @param none
	* @return none
	*/
    hide: function () {
    },

	// No more trailing commas issues
	EOF:null
};//question this RLB


MapObject.app.CM.map = function(opt) {
	this.init(opt);
};

MapObject.app.CM.map.prototype = {
	
	/**
	* City/area name
	* @private
	* @type {string} 
	*/
	area: null,

	/**
	* Area configuration options.
	* @private
	* @type {string} 
	*/
	areaConfig: null,

	/**
	* Instance of Gmap2
	* @private
	* @type {Gmap2} 
	*/
	map: null,

	/**
	* Data store
	* @private
	* @type {Ext.data.Store}
	*/
	ds: null,
	
	/**
	* Grid
	* @private
	* @type {Ext.grid.Grid}
	*/
	grid: null,
	
	/**
	* Record Viewer
	* @private
	* @type {MapObject.app.CM.recordViewer}
	*/
	recordViewer: null,

	/**
	* Record Viewer
	* @private
	* @type {MapObject.app.CM.tooltipTemplate}
	*/
	tooltipTemplate: null,

	/**
	* Icons
	* @private
	* @type {Array}
	*/
	icons: null,

	/**
	* Storage for center marker displayed after geocoding.
	* @private
	* @type {GPoint}
	*/
	centerMarker: null,

	/**
	* Initialize object
	* @param none
	* @return none
	*/
    init : function(opt){

    	// Get config option 
    	this.icons = opt.icons;
    	this.area = opt.area;
    	this.areaConfig = opt.areaConfig;
    	this.allowEdit = opt.allowEdit;
		this.mapCenter = opt.mapCenter;
		this.webPath = opt.webPath; // Installation web path within document root
		// Active marker to be selected after data loading
		this.active_marker_id = opt.active_marker_id;
		this.cabin = opt.cabin ;
		this.event_id = opt.event_id;
		this.cabin_switch = opt.cabin_switch ;
		this.bedrooms = opt.bedrooms ;
		this.sleeps = opt.sleeps ; 
		this.smoking = opt.smoking;
		this.pets = opt.pets ;
		

    	// App init


        //
		// Init map
		//
		/*
		this.map = new GMap2(document.getElementById("map"));
		this.map.addControl(new GSmallMapControl());
		this.map.addControl(new GMapTypeControl());
		// Set map center
		this.map.setCenter(new GLatLng(this.areaConfig.mapCenter.point.lat,this.areaConfig.mapCenter.point.lng), this.areaConfig.mapCenter.zoom);
		*/

		// Set some configuration options
		MapObject.widget.MapViewer.prototype.mapCenter = this.mapCenter	;
		MapObject.widget.MapViewer.prototype.areaConfig = this.areaConfig;
		MapObject.widget.MapViewer.prototype.allowEdit = this.allowEdit;
		MapObject.widget.MapViewer.prototype.webPath = this.webPath;
		MapObject.widget.MapViewer.prototype.setCenter = function() {
			this.mapViewer.getMapProxy().setCenter(parseFloat(this.mapCenter.point.lat), parseFloat(this.mapCenter.point.lng), parseInt(this.mapCenter.zoom));
		};

    	//
    	// Data Store
    	//

    	// Define the Data Store
		this.ds = new Ext.data.Store({
			// load using script tags for cross domain, if the data in on the same domain as
			// this page, an HttpProxy would be better
			//proxy: new Ext.data.ScriptTagProxy({
			// Use XML HTML Request
			proxy: new Ext.data.HttpProxy({
				url: this.webPath + 'api/search.php',
				nocache: true
			}),
			/* Search Parameters */
// dont think this works
//			
//			 baseParams: {searchQuery:"area=1&bedrooms=&sleeps=&search-button=Search"},
//			 baseParams: {cabin:this.cabin},
//			// create reader that reads the markers
			reader: new Ext.data.JsonReader({
				root: 'eventsList',
				/* totalProperty: 'totalCount', */
				id: 'Event_ID'
			}, [
				// Make sure id is present as a part of record
				/* Sample record:
				* {"cdid":"336","cdate":"2007-09-10","calc_time":"07:30 PM","clatitude":"39.286679","clongitude":"-76.591440",
				* "description":"","address":"400 S. Ann St","name":"Theft","cicon":"theft.png"}
				*/
				{name: 'id', mapping: 'Event_ID'},
				{name: 'type_id', mapping: 'Area_ID'},
				{name: 'sid', mapping: 'sid'}, // id-hash
				{name: 'lat', mapping: 'Latitude', type: 'float'},
				{name: 'lng', mapping: 'Longitude', type: 'float'},
				{name: 'title', mapping: 'Title'},
				{name: 'state', mapping: 'State'},
				{name: 'city', mapping: 'City'},
				{name: 'area', mapping: 'AreaName'},
				{name: 'beds', mapping: 'Beds'},
				{name: 'photoUrl', mapping: 'PhotoUrl'},
				{name: 'detailUrl', mapping: 'DetailUrl'},
				{name: 'brochureUrl', mapping: 'BrochureUrl'},
				{name: 'mountainView', mapping: 'MountainView'},
				{name: 'hotTub', mapping: 'HotTub'},
				{name: 'smoking', mapping: 'Smoking'},
				{name: 'pets', mapping: 'Pets'},
				{name: 'icon', mapping: 'icon'}
				//{name: 'price', type: 'float', mapping: 'Property.Price'},
			])
		});


		/* 
		* beforeload Event - Fires before a request is made for a new data object. 
		* If the beforeload handler returns false the load action will be canceled. 
		* 
		* Main responsibility of this hook is to pass search criteria to the server.
		* searchQuery: fieldRep=Select...&address=&zip=&census=&date1=&date2=&owner=Select...&employer=Select...&focus=Select...&ADF_Gap=&construction=Select...
		*/
		function beforeload(options) {
			//Serialize form and send parameters to a server
			options.baseParams.searchQuery = Ext.Ajax.serializeForm('searchForm');
		return true;
		}
		this.ds.on('beforeload', beforeload, this);

		this.ds.on('load', function(ds) {
			// Gat raw JSON data for further custom processing - errors validations
			var rawdata = ds.reader.jsonData;
			if (rawdata.errors.length > 0) {
				Ext.MessageBox.alert("Errors", rawdata.errors.join("<br/>"));
			}

			document.getElementById("recordsCount").innerHTML = "Cabins Found: " + ds.getCount();
			// Show errors
			if (this.dataInitialized && ds.reader.jsonData.errors && ds.reader.jsonData.errors.length > 0) {
				alert(ds.reader.jsonData.errors.join("\n"));
		    }

		    /* Set selected marker */
			setTimeout( function() {
					if((this.activeMarkerID == '0') || (this.activeMarkerID == '')) return;
					var marker = this.mapViewer.getViewer().getMapProxy().getMarker(this.activeMarkerID);
					if (!marker) return;
					this.mapViewer.getViewer().onMarkerClick(marker);
				}.createDelegate(this),
				1000
			);

		    // Set dataInitialized flag to true.
		    this.dataInitialized = true;
		}, this);


    	//
    	// Grid
    	//

		// RowSelectionModel
		var sm = new Ext.grid.RowSelectionModel({singleSelect:true});

		// the DefaultColumnModel expects this blob to define columns. It can be extended to provide
        // custom or reusable ColumnModels
        var colModel = new Ext.grid.ColumnModel([
			{header: "", hideable: false, width: (this.allowEdit ? 80 : 50), sortable: false, dataIndex: 'id', renderer: actionColumnRenderer.createDelegate(this)},
			{header: "Area", width: 120, sortable: true, dataIndex: 'area'},
			{header: "Cabin Name", width: 150, sortable: true, dataIndex: 'title'},
			{header: "City", width: 80, sortable: true, dataIndex: 'city'},
			{header: "State", width: 50, sortable: true, dataIndex: 'state', hidden:true},
			{header: "Beds", width: 330, sortable: false, dataIndex: 'beds'},
			{header: "Mountain View", width: 50, sortable: true, dataIndex: 'mountainView', hidden:true},
			{header: "Hot Tub", width: 50, sortable: true, dataIndex: 'hotTub', hidden:true},
			{header: "Smoking", width: 50, sortable: true, dataIndex: 'smoking', hidden:true},
			{header: "Pets", width: 50, sortable: true, dataIndex: 'pets', hidden:true}
		]);

		// Custom renderer function to render 'view details' and 'update' links
		function actionColumnRenderer(v, p, record){
			var links = [];				
			// View details 
			var imgSrc = (this.icons[record.get('icon')] != undefined) ? this.icons[record.get('icon')].image : (this.webPath + 'media/icons/fam/application_go.png');
			links.push('<a target="_blank" title="View Details" href="' + record.get('detailUrl') + '"><img width="18px" height="18px" src="' + imgSrc + '" alt="View Details"/></a>');
			links.push('<a title="Print Brochure" href="' + record.get('brochureUrl') + '"><img src="' + this.webPath + '/media/icons/fam/layout_content.png" alt="Print Brochure"/></a>');

			if (this.allowEdit) {
				// Update link 
				links.push('<a target="win_update_' + record.get('id') + '" title="Update Details" href="' + this.webPath + 'secure/event-edit.php?event_id=' + encodeURIComponent(record.get('id')) + '"><img src="' + this.webPath + 'media/icons/fam/application_edit.png" alt="Update Details"/></a>');
			}

			return links.join("&nbsp;");
		}

        // create the Grid
        this.grid = new Ext.grid.GridPanel({
        	renderTo: 'grid-container',
            store: this.ds,
            cm: colModel,
	        sm: sm,
			loadMask: false,
			width:783,
			height:400,
            //autoExpandColumn: 'description',
			viewConfig: {
				forceFit:false
			},
			collapsible: true,
	        animCollapse: false,
	        enableColumnHide: true,
			EOF: null
        });


        // Record viewer
        //this.recordViewer = new MapObject.app.CM.recordViewer(this.ds);

        // Record viewer
        this.tooltipTemplate = new MapObject.app.CM.tooltipTemplate(this.ds);

		// Instantiate MapViewer class
		this.mapViewer = new MapObject.widget.MapViewer( {
			'ds': this.ds,
			'grid': this.grid,
			'recordViewer': this.recordViewer,
			'tooltipTemplate': this.tooltipTemplate,
			'gridHelp' : null,
			'autoCenter' : true, 
			// Set center/zoom calculated on a client based on zoom boundaries
			'calculateCenter' : true,
			'focusGridRow' : false,
			'cabinswitch' : this.cabin_switch,
			'mapConfig' : {
				'container' : 'map-container',
				'tooltipEngine' : 'v2',
				'mapControls' : {largeMapControl: true},
				'markersEngine' : 'MarkerManager',
				'icons' : this.icons				
			}
		});


		/* Insert a map legend image */
/*		var legend=document.createElement('div');
		legend.id='map-legend';
		legend.style.position='absolute';
		legend.style.right='1px';
		legend.style.bottom='25px';
		legend.style.backgroundColor='transparent';
		legend.style.zIndex=25500;
		legend.innerHTML='<img src="' + this.webPath + 'media/images/Icon-legend.png" alt="Map Legend" style="border:0; margin: 2px;"/>';
		this.mapViewer.getViewer('Google').mapObject.getContainer().appendChild(legend);*/

		/* deprecated by customer
		var geocoder = new MapObject.proxy.GoogleGeocoder();
		// Instantiate geocoding widget
		var geocodingPanel = new MapObject.widget.GeoCodingPanel(
			'geocodeAddressInput',
			'geocodeButton',
		    geocoder,
		    this.mapViewer.getViewer('Google'),
			{showCenterIcon: true}
		)
		*/

		//
		// Register application events for misc. HTML elements
		//

		// Attach event to the 'search' button
		var showBtn = Ext.get('search-button');

		// Attach event to the 'search' button
		showBtn.on('click', this.evtSearch, this);
		
		// attach event triggered when ds load complete to warn for no records selected
		this.ds.on('load', this.no_records, this);		
 
        // Finally load data. Load of DS on first time in.
        this.dataInitialized = false; // flag to prevent from errors output
 //       this.ds.removeAll();
        this.ds.baseParams.searchQuery = "area="+ this.area + "&event_id=" + this.event_id + "&cabin=" + this.cabin + "&bedrooms=" + this.bedrooms + "&sleeps=" + this.sleeps +  "&smoking=" +	this.smoking + "&pets=" + this.pets;
        this.ds.suspendEvents(); //disable Before Load Function it clears loaded parms to baseparms
        this.ds.load();
        this.ds.resumeEvents();
       
        
    },//init end
 
  //no records message
    no_records: function(e) {
    var ds_record_count ;
	ds_record_count = this.ds.getTotalCount() ;
	if (ds_record_count < 1) {
		alert("No Cabins With Above Search, Try another Search");}
    },    
    
	/**
	* search
	* @param e Event handler
	* @return none
	*/
	//When Submit button on Searhform used Runs from here
    evtSearch: function(e) {
		//Remove all Records from the Store and fires the clear event.
		this.ds.removeAll();
        // Invoke search
        this.ds.load();
 
}
    };//Map Class end


/*
* Map geocoder.
*/
MapObject.app.CM.mapGeocoder = {
	init: function(config) {

		// Instantiate GoogleMap class
		this.mapViewer = new MapObject.proxy.GoogleMap(config.container, (config.mapConfig || {}));

		this.mapViewer.multipleDragableMarkers = false;

		this.mapViewer.on('afterloadmap', function () {
			this.mapViewer.setCenter(config.mapCenter.lat, config.mapCenter.lng, config.mapCenter.zoom);
		}, this);

		// Set lat/lng values on a form
		this.setLatLong = function(lat, lon, accuracy) {
			Ext.get('latitude').dom.value = lat;
			Ext.get('longitude').dom.value = lon;
		};
		this.onGeocode = function(lat, lon, accuracy) {
			this.setLatLong(lat, lon, accuracy);

			this.mapViewer.setCenter(lat, lon, this.geocoder.accuracy[0].levels[accuracy]);

			// Add dragable marker 
			this.mapViewer.addDragableOverlay(lat, lon);
		};
			

		this.mapViewer.onMapClick = this.setLatLong;

		// Load map, e.g. set center
		this.mapViewer.loadMap();

		//Add dragable support
		this.mapViewer.registerMapClick();

		this.geocoder = new MapObject.proxy.GoogleGeocoder();

		this.geocoder.on("aftergeocoding", this.onGeocode, this);

		// Add event listener for geocode button
		Ext.get('GeocodeButton').on('click', function () {
			addr = [
				Ext.get('address').dom.value,
				Ext.get('city').dom.value,
				Ext.get('zip').dom.value
			];
			this.geocoder.geocode(addr.join(" "));
		}, this);

		// Add DragableOverlay if necessary
		if (config.marker && config.marker.lat && config.marker.lng)
		{
			this.mapViewer.addDragableOverlay(config.marker.lat, config.marker.lng);
		}
	}
	
};
