/*
 * SmartForms
 * Copyright(c) 2005-2008, ResLogic Inc. All rights reserved.
 */


Ext.ns('RL');


RL.Global = {
	downloadedVendorLists:{},
	downloadedPricingStores:{},
	Events: new Ext.util.Observable(),
	minWidth:850,
	minHeight:500,
	expectedFrameWidthPadding:40,
	expectedFrameHeightPadding:100,
		
	connectedDestProducts:{},
	connectedDestProdGroups:{},

	user				: null,
	frame				: null,
	viewport			: null,


	getWindowSize: function(){
		var width = 0, height = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
		  //Non-IE
		  width = window.innerWidth;
		  height = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		  //IE 6+ in 'standards compliant mode'
		  width = document.documentElement.clientWidth;
		  height = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		  //IE 4 compatible
		  width = document.body.clientWidth;
		  height = document.body.clientHeight;
		}
		return {width:width,height:height};
	},

	currencyCode: null,
	currencyRecord: null,
	getCurrency: function (){

		var currencyCode=Ext.jx.getStoreValue('GTAW#CADCURR');
		if (!currencyCode) Ext.jx.setStoreValue('GTAW#CADCURR', (currencyCode=Ext.jx.getStoreValue("DEPT#CURRENCY") || Ext.jx.getStoreValue("CONFIG#CURRENCY")));

		if (RL.Global.currencyCode!=currencyCode){
			RL.Global.currencyRecord=Ext.jx.getStore("CURRENCY").data.map['CURRENCY#CTYCODE='+(RL.Global.currencyCode=currencyCode)];
			var htmlFormat=RL.Global.currencyRecord.get('CURRENCY#HTMLFORMAT');
			Ext.jx.math.htmlFormat=htmlFormat || '$ 123,456,789.00';
		}
		return RL.Global.currencyRecord;
	},


	processDeptSettings: function(){

		if (!RL.Defaults) RL.Defaults={};
		if (!RL.Defaults.USE_DATEFIELDPLUS) Ext.reg('datefieldplus', Ext.form.DateField);


		this.user = new RL.Model.User()


		var agent=navigator.userAgent.toLowerCase();
		Ext.isIPhone = (agent.indexOf('iphone')!=-1);

    	Ext.QuickTips.init();
    	Ext.form.Field.prototype.msgTarget = 'side';


		if (Ext.get('SEO_RESLOGIC')) Ext.get('SEO_RESLOGIC').setStyle('display','none');


		var minPlus={
			width: RL.Global.minWidth + RL.Global.expectedFrameWidthPadding,
			height: RL.Global.minHeight + RL.Global.expectedFrameHeightPadding
		};

		var windowSize=RL.Global.getWindowSize();

		if (windowSize.height > minPlus.height) minPlus.height=windowSize.height;
		if (windowSize.width > minPlus.width) minPlus.width=windowSize.width;

		if (Ext.jx.getStoreValue("DEPT#CONOLDLOUT") != 1) {

			var frameConfig = {
				slots : true,

				layout : "border",
				hideBorders:true,
				baseCls: 'x-frameless',

				items : [{
					region : "north",
					autoHeight : true,
					html: Ext.jx.getStoreValue("DEPT#CONTOP"),
					hidden : !Ext.jx.getStoreValue("DEPT#CONTOP")

				},{
					region : "east",
					autoWidth : true,
					html: Ext.jx.getStoreValue("DEPT#CONRIGHT"),
					hidden : !Ext.jx.getStoreValue("DEPT#CONRIGHT")
				},
				{
					xtype : 'RL.Viewport',
					slot : 'viewport',
					region : 'center'
				},
				{
					region : "west",
					baseCls: 'x-frameless',
					hideBorders: true,
					autoWidth : true,
					html: Ext.jx.getStoreValue("DEPT#CONLEFT"),
					hidden : !Ext.jx.getStoreValue("DEPT#CONLEFT")
				},{
					region : "south",
					baseCls: 'x-frameless',
					hideBorders: true,
					autoHeight : true,
					html: Ext.jx.getStoreValue("DEPT#CONBOTTOM"),
					hidden: !Ext.jx.getStoreValue("DEPT#CONBOTTOM")
				}]
			};

			if (Ext.isIPhone || windowSize.width < minPlus.width || windowSize.height < minPlus.height){

				frameConfig.width=minPlus.width;
				frameConfig.height=minPlus.height;
				frameConfig.renderTo=Ext.getBody();
				var frame=new Ext.Panel(frameConfig);

			}else{
				var frame=new Ext.Viewport(frameConfig);
				frame.on('resize',function(){
					frame.doLayout()
				})
			}

		}else{
			
			window.gtawNew = new RL.Quote()

			var irePage=Ext.get('IREPAGE');
			if (!irePage){
				Ext.DomHelper.append(document.body, {
					tag:'div',
					id: 'IREPAGE'
				});
				irePage=Ext.get('IREPAGE');

				irePage.setWidth(minPlus.width );
				irePage.setHeight(minPlus.height);

			}else{
				irePage.setStyle('display','block');
				if ( irePage.getWidth() < RL.Global.minWidth) irePage.setWidth(RL.Global.minWidth);
				if ( irePage.getHeight() < RL.Global.minHeight) irePage.setHeight(RL.Global.minHeight);
			}


			window.gtawNew.width=irePage.getWidth();
			window.gtawNew.height=irePage.getHeight();
			window.gtawNew.render(irePage);
			//Ext.getBody().setStyle({'background-color':'grey'});
			//irePage.setStyle('align:left!important; margin-top:-30px;');
		}


		this.frame 			= frame
		this.viewport		= frame.slots.viewport 


		//Ext.getBody().on('click',function(){
		//	Ext.ux.Sound.enable();
		//	Ext.ux.Sound.play( 'click.wav');
		//});
	},


	showUserAccount : function () {
		if (!RL.Global.user.authenticated) {
			var loginPopup = new RL.Login.Popup({
				returnTrips : true
			})
	
			loginPopup.show(Ext.getBody())
		} else
			this.viewport.showUserAccount()
	},


	showQuoteWizard : function (stepNum) {
		this.viewport.showQuoteWizard(stepNum)
	},
	
	
	startQuoteOver : function () {
		Ext.jx.getStore('BUILD').removeAll()
		Ext.jx.getStore('GTAW').removeAll()
		
		this.viewport.startQuoteOver()
	},
	
	
	showContentQuote : function (quote) {
		this.viewport.showContentQuote(quote)
	},	


	ensureGtawRecord : function() {
		var gtawStore = Ext.jx.getStore('GTAW')

		if (!gtawStore.getAt(0)) {
			var recordType = gtawStore.reader.recordType

			gtawStore.add([ new recordType({}) ])
		}

		//XXX global variable
		gtawRecord = gtawStore.getAt(0)
	},


	defaultDestCode: null,
	//defaultDestCode: 'COBR',

	prettyDate:function(p){

		if (Ext.isDate(p)) p=p.dateFormat("d-M-Y");

		return p;
	},


	getWizard : function (me, dontSearchBelow) {

		if (!me.wizard) me.wizard = me.findParentBy(function (item) {

			if (item instanceof RL.Quote.WizardBase) return true
		})


		if (!me.wizard && !dontSearchBelow) window.gtawNew.findBy(function (item) {  //and if not then search below the top level

			if (item instanceof RL.Quote.WizardBase && !me.wizard) me.wizard = item
		})

		return me.wizard
	},


	getCurrentDestIndex: function (me){
		if (RL.Global.getTripType()!='multi') return 0;
		var p=me.findParentBy(function(p){return typeof p.n_dest != 'undefined' });
		return p ? p.n_dest : 0;
	},


	getSegmentStartValues: function (me, validate){
		return RL.Global.getSegmentStartValuesAll()[RL.Global.getCurrentDestIndex(me)]
	},


	getTripStartCt:function(){
		return gtawNew.slots.wizard.slots.start.slots[RL.Global.getTripType()];
	},


	updateAirportByDest: function (dest){

		var resorts = Ext.jx.getStore("RESORT", "ALL");
		var resortRecord=resorts.data.map['RESORT#SEARCHCODE='+dest];
		var ct=RL.Global.getTripStartCt();
		if (resortRecord) ct.setValues({'#TO_AIRPORT':resortRecord.getValue('RESORT#PREFDCITY')});
		ct.validate();

		var a = ct.findBy(function(item){ return item.name==='#FROM_AIRPORT' });
		if (a.length){
			var fromAirport=a[0];
			if (fromAirport.getValue()==='' && RL.NEARBY_AIRPORTS ){
				var nearbyAirport=RL.Global.getMostNearbyAirport();
				if (nearbyAirport){

					if (fromAirport.store){
						fromAirport.setValue(nearbyAirport);
					}else{
						fromAirport.value=nearbyAirport;
					}
					fromAirport.markInvalid('Your outgoing airport was automatically calculated based on your Internet address.');
				}
			}
		}
	},

	getTripStartValues: function (){
		var valuesRaw=RL.Global.getSegmentStartValuesAll();
		return {

			adults:valuesRaw[0].adults,
			children:valuesRaw[0].children,
			usesAir:valuesRaw[0].usesAir,
			fromAirport:valuesRaw[0].fromAirport,
			toAirport:valuesRaw[0].toAirport,

			dest:valuesRaw[0].dest,
			startDate:valuesRaw[0].startDate,
			endDate:valuesRaw[valuesRaw.length-1].endDate
		};
	},


	getSegmentStartValuesAll: function (validate){

		var arrayReturn=[], valuesRaw=RL.Global.getTripStartCt().getValues();

		if (RL.Global.getTripType()==='multi'){

			if (validate && !valuesRaw['GTAW#ADULT'] ){

			}else{

				valuesRaw.dest_group.each(function(c){

					if (!c['GTAW#RESORT']) return;
					if (validate && (!c['GTAW#DDATE'] || !c['GTAW#RDATE'] )) return;

					arrayReturn.push({
						adults:valuesRaw['GTAW#ADULT'],
						children:valuesRaw['GTAW#CHILD'],
						usesAir:valuesRaw['#AIR_OPTION'],
						fromAirport:valuesRaw['#FROM_AIRPORT'],
						toAirport:valuesRaw['#TO_AIRPORT'],

						dest:c['GTAW#RESORT'],
						startDate:c['GTAW#DDATE'],
						endDate:c['GTAW#RDATE']

					});
				})
			}
		}else{

			var gtawRecord = Ext.jx.getStore('GTAW').getAt(0);

			//place a higher importance on the current reservation's data than the first screen's values
			valuesRaw['GTAW#RESORT']=gtawRecord.data['GTAW#RESORT'] || valuesRaw['GTAW#RESORT'];
			valuesRaw['GTAW#DDATE']=gtawRecord.data['GTAW#DDATE'] || valuesRaw['GTAW#DDATE'];
			valuesRaw['GTAW#RDATE']=gtawRecord.data['GTAW#RDATE'] || valuesRaw['GTAW#RDATE'];
			valuesRaw['GTAW#ADULT']=gtawRecord.data['GTAW#ADULT'] || valuesRaw['GTAW#ADULT'];
			valuesRaw['GTAW#CHILD']=gtawRecord.data['GTAW#CHILD'] || valuesRaw['GTAW#CHILD'];

			if (validate && (!valuesRaw['GTAW#RESORT'] || !valuesRaw['GTAW#DDATE'] || !valuesRaw['GTAW#RDATE'] || !valuesRaw['GTAW#ADULT'] )){

			}else{
				arrayReturn.push({
					adults:valuesRaw['GTAW#ADULT'],
					children:valuesRaw['GTAW#CHILD'],
					usesAir:valuesRaw['#AIR_OPTION'],
					fromAirport:valuesRaw['#FROM_AIRPORT'],
					toAirport:valuesRaw['#TO_AIRPORT'],

					dest:valuesRaw['GTAW#RESORT'],
					startDate:valuesRaw['GTAW#DDATE'],
					endDate:valuesRaw['GTAW#RDATE']
				});
			}
		}
		return arrayReturn;
	},


	getQuoteMode : function () {
		if (!RL.Global.defaultQuoteMode) {

			if (RL.Global.getDefaultDestCode()) Ext.jx.setStoreValue("DEPT#CONMULTDES", 0) //QUOTE_MODE='single'

			var tripTypeNo = Number(Ext.jx.getStoreValue("DEPT#CONMULTDES"))

			if (isNaN(tripTypeNo)) tripTypeNo = 0

			RL.Global.defaultQuoteMode = {
				0:'single',
				2:'multi',
				1:'both'
			}[tripTypeNo]
		}

		return RL.Global.defaultQuoteMode
	},


	getTripType : function () {

		if (!RL.Global.tripType) {
			var defaultQuoteMode = RL.Global.getQuoteMode()

			if (defaultQuoteMode != 'both')
				RL.Global.tripType = defaultQuoteMode
			else
				if (RL.Global.getDefaultDestCode() || !RL.Global.tripType) RL.Global.tripType = 'single'
		}

		return RL.Global.tripType
	},


	getDefaultDestCode: function(){

		if (typeof RL.Global.defaultDest === 'undefined'){
			RL.Global.defaultDest = Ext.isEmpty(Ext.jx.getStoreValue('DEPT#CONDESTLCK')) ?  false : Ext.jx.getStoreValue('DEPT#CONDESTLCK');

			if (!RL.Global.defaultDest){ //alternative way to set the default dest...this is when only one destination is valid
				var resorts = Ext.jx.getStore("RESORT");
				if (resorts.getCount() == 1) {
					var resortRecord = resorts.getAt(0);
					RL.Global.defaultDest = resortRecord.get('RESORT#SEARCHCODE');
				}
			}
		}
		return RL.Global.defaultDest

	},


	getVendorDlEventName: function (destCode, productType){
		return 'downloaded_vendor_list-'+destCode+'-'+productType;
	},


	getVendors : function (resortRecord, callback, scope) {
		
		var destCode		= resortRecord.get('RESORT#SEARCHCODE')
		var vars 			= Ext.jx
		
		if (!vars.vendors) 			vars.vendors 		= {}
		if (!vars.vendors_type) 	vars.vendors_type	= {}
		
		
		//gatherting productTypes
		var productTypes = Ext.jx.getTable('PRODGRP').Funcs.getProductsCodes();

		var productServiceTypes = resortRecord.getProducts()

		Ext.each(productServiceTypes, function (recordProduct) {
			
			productTypes.push(recordProduct.get('SERVICE#CODE'))
		})
		

		//preparing values
		var values = {
			'VENDOR#REGION' : destCode,
			'#VENTYPES' 	: productTypes.join(',')
		}

		var params			= Ext.jx.Ajax.cleanFieldNamesForPost(values)
		var actionParams	= '&' + Ext.jx.Ajax.urlEncode({ screen : 'js::ext_data_store::VENDOR', page_action : params })

		
		//checking whether this search was already done
		if (!RL.Global.pastVendorSearches) RL.Global.pastVendorSearches = {}
		
		if (RL.Global.pastVendorSearches[ actionParams ]) {
			if (callback) callback.call(scope || window, true, resortRecord)
			
			return
		}
		
		RL.Global.pastVendorSearches[ actionParams ] = true

		
		//something related to events )
		var events = []
		
		Ext.each(productTypes, function (productType) {
			events.push(RL.Global.getVendorDlEventName(destCode, productType))
		})
		
		RL.Global.Events.addEvents(events);

		
		var dataRemote 	= Ext.jx.getTable('VENDOR').getData(actionParams, { remote : true })
		var store		= dataRemote.getStore({ remote : true, loadNow : true})

		store.on({
			loadexception : function () {
				
				Ext.Msg.show({
			   		title  :  'Error',
			   		msg: 'There was an error during loading of vendors list. Please try again in a minute',
				   	buttons: Ext.Msg.OK,
				   	icon: Ext.MessageBox.ERROR
				})

				Ext.each(productTypes, function (productType) {
					var eventName = RL.Global.getVendorDlEventName(destCode, productType)
					RL.Global.downloadedVendorLists[eventName] = false
				})
				
				if (callback) callback.call(scope || window, false, resortRecord)
			},
			
			load : function () {
				store.each(function (record) {
					var keyVal 		= record.data['#LINK_TO_VENDOR'] || record.data['#LINK_TO_SERVICE']
					var keyVal_type	= record.data['VENDOR#VENTYPE'] + '-' + destCode
					
					if (!keyVal) return Ext.jx.debug('Missing key locater for record');

					if (!vars.vendors_type[keyVal_type]) vars.vendors_type[keyVal_type] = []
					vars.vendors_type[keyVal_type].push(vars.vendors[keyVal] = record)
				});

				Ext.each(productTypes, function (productType) {
					var eventName = RL.Global.getVendorDlEventName(destCode, productType)
					RL.Global.Events.fireEvent(eventName);
					RL.Global.downloadedVendorLists[eventName] = true
				})
				
				if (callback) callback.call(scope || window, true, resortRecord)
			}
		})
		
		return store
	},


	getMostNearbyAirport: function(){
		return (RL.NEARBY_AIRPORTS && RL.NEARBY_AIRPORTS.length ? RL.NEARBY_AIRPORTS[0].airport : undefined )
	},


	productSupports:function(productType, feature){

		var recordProduct;
		if (typeof productType == 'string'){
			var products=Ext.jx.getStore('SERVICE')
			recordProduct=products.data.map['SERVICE#CODE=' + productType];
		}else{
			recordProduct=productType;
			productType=recordProduct.data['SERVICE#CODE'];

		}

		switch (feature){
			case 'golf':
				return (productType==='GO' && RL.Defaults.DEV_MODE && Ext.jx.getStoreValue("DEPT#CONGOLFPLN"));
		};
		return false;
	},


	getSuperDests:function(){
		var superDests=[];
		Ext.jx.getStore("SUPERDES").each(function(r){
			if (r.getDests().items.length) superDests.push(r);
		},this);
		return superDests;
	},


	showContent : function (parent, type, value, activeTab, config) {
		var items

		switch (type) {
			case 'vendor' :
				if (typeof value == 'string') value = Ext.jx.vendors[value];

				items = Ext.apply({
					xtype : 'vendor_content',
					vendorRecord: value,
					active : activeTab,
					autoHeight : false
				}, config);

				break;

			case 'dest' :
				if (typeof value == 'string') value = Ext.jx.getStore("RESORT").data.map['RESORT#SEARCHCODE=' + value]

				if (value) items = {
					xtype : 'dest_content',
					destRecord : value,
					active : activeTab,
					autoHeight : false
				};
				break;
		}

		if (items) {
			var panelBlind = new Ext.ux.PanelBlind({
				destroyOnDismiss	: true,
				autoHeight			: false,
				layout				: 'fit',
				height				: 400,
				frame				: true
			});

			panelBlind.init(parent);

			panelBlind.show({
				items : items
			})
		}
	},
	
	
	getUrchinCookie : function (name) {
		var value = Ext.util.Cookies.get(name)
		
		return value.replace(/ /g, '+').replace(/\r\n/g, '')
	},
	
	
	extractUrchinValue : function (value, name) {
		var regex = new RegExp(name + '=(.*?)[\\|;]')
		
		var match = regex.exec(value)
		return match ? match[1] : ''
	},
	
	
	getAnalyticData : function () {
		var utmz	= this.getUrchinCookie('__utmz')
		var utma	= this.getUrchinCookie('__utma')
		var utmb	= this.getUrchinCookie('__utmb')
		var utmc	= this.getUrchinCookie('__utmc')
		
		var urchinCookie 	= '__utma=' + utma + ';+__utmz=' + utmz + ';+__utmb=' + utmb + ';+__utmc=' + utmc

		return {
			"GTAW#URLSOURCE"	: window.location.href,
			"GTAW#IREADTRACK"	: '',
			
			"GTAW#UCAMPAIGN"	: this.extractUrchinValue(urchinCookie, 'utmccn'), 
			"GTAW#UCAMPID" 		: this.extractUrchinValue(urchinCookie, 'utmcid'),
			"GTAW#UCONTENT" 	: this.extractUrchinValue(urchinCookie, 'utmcct'),
			"GTAW#UCOOKIE" 		: urchinCookie,
			"GTAW#UMEDIUM" 		: this.extractUrchinValue(urchinCookie, 'utmcmd'),
			"GTAW#USOURCE"		: this.extractUrchinValue(urchinCookie, 'utmcsr'),
			"GTAW#UTERM"		: this.extractUrchinValue(urchinCookie, 'utmctr')
		}
	}

};

Ext.ns('RL');


RL.Quote = Ext.extend(Ext.Container, {

	slots 				: true,

	quoteMode 			: null,
	tripType			: null,


	spinner				: null,
	
	
	//variables from URL
	initialDestCode		: null,
	
	initialStep			: null,
	startDate			: null,
	endDate				: null,
	producttype			: null,
	vendor				: null,
	
	//model object
	quote				: null,


	constructor : function (config) {
		this.quoteMode = config.quoteMode || RL.Global.getQuoteMode()
		this.tripType  = config.tripType || RL.Global.getTripType()

		config = config || {}

		var bannerStyle= (Ext.isIE6 || Ext.isIE7) ? { display:'none' } : undefined
		
		var quote = config.quote = config.quote || new RL.Model.Quote()

		Ext.apply(config, {

			layout : "border",
			baseCls: 'x-frameless',
			hideBorders : true,

			items : [
				{
					region : 'north',

					slot : 'banner',
					baseCls: 'x-frameless',
					hideBorders: true,
					autoHeight:true,
					style: bannerStyle
				},
				{
					region : 'center',

					xtype : 'quote_wizard',
					slot : 'wizard',

					tripType : this.tripType,
					quoteMode : this.quoteMode,
					
					quote : quote
				},
				{
					region : "east",

					xtype : 'rl-quote-summary',
					slot : 'summary',

					tripType : this.tripType,

					quote : quote,

					width : 230

					//split : true,
					//collapsible : true,
					//collapsed : false,
					//collapseMode : 'mini',
				}
			]
		})


		RL.Quote.superclass.constructor.call(this, config)
	},


	initComponent : function(){
		//after this line all slots will be filled
		RL.Quote.superclass.initComponent.apply(this, arguments);

		this.on('afterlayout', this.onAfterLayout, this, { single : true })


		this.on('triptype-changed', this.switchType, this)

		this.on('quote-changed', this.onQuoteChanged, this, { delay : 100 })
//		this.subscribe('quote-loaded', this.onQuoteLoaded, this);

		this.on('quote-finalize', this.onFinalizeQuote, this)
		this.on('quote-startover', this.onStartQuoteOver, this)

		this.on('wizard-leave', this.onWizardLeave, this)
		this.on('wizard-enter', this.onWizardEnter, this)
	},
	
	
	destroy : function () {
//		this.unsubscribe('quote-loaded', this.onQuoteLoaded, this)
		
		RL.Quote.superclass.destroy.apply(this, arguments)
	},
	
	
	configure : function (config) {
		Ext.apply(this, config)
		
		if (config.startDate) 	Ext.jx.setStoreValue('GTAW#DDATE', Date.parseDate(config.startDate, 'm/d/Y'))
		if (config.endDate) 	Ext.jx.setStoreValue('GTAW#RDATE', Date.parseDate(config.endDate, 'm/d/Y'))
		
		this.slots.wizard.configure({
			initialDestCode		: this.initialDestCode,
			
			initialStep			: this.initialStep,
			startDate			: this.startDate,
			endDate				: this.endDate,
			producttype			: this.producttype,
			vendor				: this.vendor
		})
	},
	


//	onQuoteLoaded : function (quote) {
//		this.onQuoteChanged()
//	},


	onWizardLeave : function (wizard) {
		this.slots.summary.collapseDestinationSegment(wizard.n_dest, wizard.destCode)
	},


	onWizardEnter : function (wizard) {
		this.slots.summary.expandDestinationSegment(wizard.n_dest, wizard.destCode)
	},


	onFinalizeQuote : function () {
		var hidePriceReason = this.quote.getQuoteProblems()

		if (hidePriceReason)
			Ext.MessageBox.show({
				icon: Ext.MessageBox.ERROR,
				buttons: Ext.Msg.OK,
				title:'Error',
				msg:'Can not finalize quote because of the following reason(s): <br>' + hidePriceReason
			})
		else 
			this.finalizeQuote()
	},
	
	
	backToQuote : function () {
		RL.Global.showQuoteWizard()
	},


	onStartQuoteOver : function () {

		Ext.MessageBox.confirm('Confirm', 'Are you sure that you want to start over again?', function (btn) {

			if (btn == 'yes') {
				if (this.spinner) this.spinner.close()

				RL.Global.startQuoteOver()
			}
		}, this)
	},


	switchType : function (tripType) {
		this.tripType = tripType

		this.slots.summary.switchType(tripType)
	},


	onAfterLayout : function(){
		Ext.jx.Map.Google.include.defer(100)

		this.onQuoteChanged()
	},


	onQuoteChanged : function () {
		this.quote.updateTSICalcs()
	},


	finalizeQuote : function () {
		if (Ext.jx.getStoreValue('DEPT#CONANON') == 1 || RL.Global.user && RL.Global.user.authenticated)
			this.finalizeQuoteReady()
		else {
			var identity = new RL.Quote.Finalize.Identity()

			identity.on('ready', this.finalizeQuoteReady, this)

			identity.show()
		}
	},


	finalizeQuoteReady : function () {
		
		if (RL.Defaults.DEV_MODE) {
			
			RL.Global.showContentQuote(this.quote)
			
		} else {
			this.spinner = new RL.Quote.Finalize.Spinner()
	
			this.spinner.show()
		}
		
		this.quote.finalize(function () {
			
			if (RL.Defaults.DEV_MODE) 
				//this will remove the old quote content and add new one
				RL.Global.showContentQuote(this.quote)
			else {
				
				window.gtawNew.hide();

				var resno=gtawRecord.get('GTAW#RESNUM');
				var check=gtawRecord.get('#CHECK');

				if (Ext.jx.getStoreValue("DEPT#CONOLDQOUT")==1  && values['PROSPW#EMAIL'] && !Ext.isEmpty(Ext.jx.getStoreValue("CONFIG#IREURL"))){
					window.location=Ext.jx.getStoreValue("CONFIG#IREURL")+"?screen=action_OpenRes("+resno+","+check+")";
				}else{
					window.location=server+'?screen=scnContentQuote&resno='+resno+'&check='+check;
				}
			}
		}, function () {
			if (this.spinner) this.spinner.close()
			
			RL.Global.showQuoteWizard()
			
			Ext.MessageBox.show({
				icon	: Ext.MessageBox.ERROR,
				buttons	: Ext.Msg.OK,
				title	: 'Saving Error',
				msg		: 'There was an unknown error while finalizing your quote. Please try again.'
			})
		}, this)
	}

});


Ext.reg('RL.Quote', RL.Quote)
Ext.ns('RL.Quote');


RL.Quote.WizardBase = Ext.extend(Ext.ux.TabPanelSkin, {

	keepFirstTab : false,
	enableTabScroll : true,
	plain : true,
	border : false,

	tabsBgCls:'quote_steps_bg',
	tabBtnCls:'quote_steps_btn',
	tabsTitleCls:'quote_steps_msg',

	n_dest		: 0,
	destCode	: null,
	
	initialDestCode		: null,
	initialStep			: null,
	startDate			: null,
	endDate				: null,
	producttype			: null,
	vendor				: null,

	prefetchDelay			: 4000,

	
	//model object
	quote				: null,


	constructor : function(config){
		config = config || {};

		Ext.apply(config, {
			
			layoutConfig : {
				deferredRender: true,
				layoutOnCardChange:true
			},



			defaults : {
				//bodyStyle:'padding:5px',
				border: false,
				hideMode:'offsets'
				//,style : 'overflow-y:auto;overflow-x:hidden;'

			}

		}); //eof apply

		//this.on('beforetabchange', this.onBeforeTabChange);

		this.addEvents('quote-changed', 'quote-finalize', 'wizard-leave', 'wizard-enter')
		this.enableBubble('quote-changed', 'quote-finalize', 'wizard-leave', 'wizard-enter')


		RL.Quote.WizardBase.superclass.constructor.call(this, config);
	},


	initComponent : function(){
		RL.Quote.WizardBase.superclass.initComponent.call(this)

		if (this.destCode) this.tabsTitle = this.getResortRecord(this.destCode).get('RESORT#RESORT')

		this.on('beforetabchange', this.onBeforeTabChange, this)
	},



	onRender : function (ct, position) {
		this.elements = 'body,header'; //this is to fix a weird bug...where a tabPanel clears the header from each child tab...in the onBeforeAdd

		RL.Quote.WizardBase.superclass.onRender.call(this, ct, position);
	},


	onDestroy : function(){

		RL.Quote.WizardBase.superclass.onDestroy.call(this);
	},


	onNextStep : function (step) {

		if (step == null) step = this.items.indexOf(this.getActiveTab())

		if (step + 1 >= this.items.getCount()) {

			var topWizard = RL.Global.getWizard(this, true)

			if (topWizard) {
				this.fireEvent('wizard-leave', this)

				topWizard.onNextStep()
			} else
				this.fireEvent('quote-finalize')

		} else {
            this.el.mask('Preparing your screen...', 'x-mask-loading')
			this.activate(step + 1)
    		this.el.unmask.defer(10, this.el)
        }
	},


	onBeforeTabChange : function(self, newTab, currentTab){
		if (!currentTab) return true

		if (this.items.indexOf(currentTab) == 0) {
			var validate = currentTab.validate()

			if (validate === false) Ext.Msg.show({
		   		title  :  'Warning',
		   		msg: 'Please fill all the required fields (marked with red) to continue',
			   	buttons: Ext.Msg.OK,
			   	icon: Ext.MessageBox.WARNING
			})

			return validate
		}
	},


	prefetchPricesInternal: function(){
		Ext.each(this.items.items, function(item){
			if (item && item.priceIt) item.priceIt(true);
		});
	},


	prefetchPrices: function(){
		if (!this.prefetchTask) this.prefetchTask = new Ext.util.DelayedTask(this.prefetchPricesInternal, this);
		this.prefetchTask.delay(this.prefetchDelay);
	},


	getResortRecord : function (destCode) {
		if (destCode) this.destCode = destCode

		var resortStore = Ext.jx.getStore('RESORT')
		this.resortRecord = this.destCode ? resortStore.getAt(resortStore.find('RESORT#SEARCHCODE', this.destCode)) : Ext.jx.getStore('GTAW').getAt(0).getResortRecord()

		return this.resortRecord
	},


	updateQuoteSteps : function (destCode) {
		var resortRecord = this.getResortRecord(destCode)
		if (!resortRecord)  return //the first destination is not selected yet

		this.keepFirstTab ? this.removeRange(1) : this.removeRange()

		var values 		= RL.Global.getSegmentStartValuesAll()
		var isMulti 	= this.isMulti
		var steps 		= []

		//product groups
		var nonEmptyProductGroups = Ext.jx.getTable('PRODGRP').Funcs.getNonEmptyGroups()

		Ext.each(nonEmptyProductGroups, function(recordProdGroup) {

			var form = new RL.PriceSearch.ProductGroup({
				wizard : this,
				title : recordProdGroup.data['PRODGRP#PGDESC'],
				recordProdGroup : recordProdGroup
			})

			steps.push({ form : form, ORDER : recordProdGroup.data['PRODGRP#LINERANGE']})

		}, this)

		//services
		var productServiceTypes = resortRecord.getProducts()

		Ext.each(productServiceTypes, function(recordProduct) {

			if (isMulti && Ext.jx.getStoreValue("DEPT#CONMULTINS")==1 && recordProduct.data['SERVICE#CODE'] =='IN') return
			if (recordProduct.isGDSAir() && (isMulti || !values[0].usesAir)) return

			steps.push({ form : this.getProductTypeStep(recordProduct), ORDER : recordProduct.data['SERVICE#LINERANGE']})

		}, this)


		//sorting tabs
		steps = steps.sort( function (a, b) { return a.ORDER - b.ORDER } )

		Ext.jx.each(steps, function(step) {
			step.form.title = (this.items.length + 1) + '.' + step.form.title

			var formStep = this.add(step.form)
			step.ownerCt = this //for some reason this wasn't getting set
		}, this)

		
		RL.Global.getVendors(resortRecord)
	},


	getProductTypeStep: function (recordProduct, config) {

		if (typeof recordProduct == 'string') {
			var products = Ext.jx.getStore('SERVICE')
			recordProduct = products.data.map['SERVICE#CODE=' + recordProduct]
		}

		var formConstructor = recordProduct.isGDSAir() ? RL.PriceSearch.Air : RL.PriceSearch.Service

		return new formConstructor(Ext.apply({
			wizard : this,
			recordProduct : recordProduct,
			title : recordProduct.data['SERVICE#DESCRIP']

			//,noValidate:true
			//,isOptional:true
		}, config))
	},


	addServiceItem : function (pricingRecord, values) {
		return this.quote.addServiceItem(pricingRecord, values, this.n_dest, this.destCode)
	}

});

Ext.ns('RL.Quote');


RL.Quote.Wizard = Ext.extend(RL.Quote.WizardBase, {

	slots				: true,
	keepFirstTab 		: true,
	withAir 			: true,
	
	activeTab 			: 0,
	
	
	
	//single/multi/both
	quoteMode 				: null,
	tripType 				: null,
	
	
	constructor : function (config) {
		config = config || {}
		
		Ext.apply(config, {

			items: [
				{
					xtype : 'quote_wizard_start',
					slot : 'start',
					
					quoteMode 			: config.quoteMode,
					
					initialDestCode		: config.initialDestCode,
					startDate			: config.startDate,
					endDate				: config.endDate
				}
			]
		});

		RL.Quote.Wizard.superclass.constructor.call(this, config);
	},


	initComponent : function(){
		RL.Quote.Wizard.superclass.initComponent.apply(this, arguments)
		
		this.tabsTitle = 'Trip Quote Wizard'

		this.subscribe('airtype_changed', this.updateAir, this)
		
		this.on('triptype-changed', this.switchType, this)
		this.on('quote-changed', this.onQuoteChanged, this)
		
		this.onQuoteChanged()
	},
	
	
	//intended to be called before rendering
	configure : function (config) {
		Ext.apply(this, config)
		
		if (this.initialStep) {
			this.updateQuoteSteps()
			
			this.activeTab = Number(this.initialStep)
		}
	},
	
	
	onQuoteChanged : function () {
		if (this.tripType == 'single') this.destCode = Ext.jx.getStore('GTAW').getAt(0).get('GTAW#RESORT')
	},

	
	onDestroy : function(){
		this.removeSubscriptionsFor('airtype_changed');
	},


	onBeforeTabChange : function (self, newTab, currentTab) {
		var fromSuper = RL.Quote.Wizard.superclass.onBeforeTabChange.apply(this, arguments)
		
		if (fromSuper === false || this.tripType == 'single') return fromSuper
		
		if (this.tripType == 'multi') {
			
			var delay = 1
			
			if (currentTab instanceof RL.Quote.WizardBase) {
				this.fireEvent.defer(100, this, [ 'wizard-leave', currentTab ])
				
				delay = 500
			}
			
			if (newTab instanceof RL.Quote.WizardBase) this.fireEvent.defer(delay, this, [ 'wizard-enter', newTab ])
		}
	},


	updateQuoteSteps: function() {

		if (RL.Global.getTripType() === 'single') {
			RL.Quote.Wizard.superclass.updateQuoteSteps.call(this);
			return
		}

		this.removeRange(1)

		
		var values = RL.Global.getSegmentStartValuesAll()
		
		if (values.length && values[0].usesAir) {
			var step = this.getProductTypeStep('AB', { useTripDates : true })
			
			step.title = (this.items.items.length + 1) + '.' + step.title
			
			this.add(step)
		}

		
		for (var i = 0; i < values.length; i++) {
			var value = values[i]
			
			var destWizard = new RL.Quote.WizardBase({
				n_dest		: i,
				destCode	: value.dest,
				
				quote		: this.quote,
				
				isMulti		: true
			})

			var resortRecord=destWizard.getResortRecord();
			
			destWizard.title = (this.items.items.length+1)+'.'+resortRecord.get('RESORT#RESORT');
			destWizard.updateQuoteSteps();
			destWizard.activeTab = 0;
			
			this.add(destWizard);
		}

		if (values.length && Ext.jx.getStoreValue("DEPT#CONMULTINS")==1) {
			var step=this.getProductTypeStep('IN',{useTripDates:true});
			step.title=(this.items.items.length+1)+'.'+step.title;
			this.add(step);
		}
	},


	switchType : function(tripType) {
		this.tripType = tripType
		
		this.updateQuoteSteps()
	},


	updateAir : function(withAir) {
		this.withAir = withAir;
		this.updateQuoteSteps();
	}


});

Ext.reg('quote_wizard', RL.Quote.Wizard);

Ext.ns('RL.Quote.Wizard')


RL.Quote.Wizard.Start = Ext.extend(Ext.Panel, {

	slots 		: true,

	bodyStyle : {
		position : 'relative',
		'overflow-y':'auto',
		'overflow-x':'hidden'
	},
	baseCls: 'x-bubble',
	frame: true,


	//single/multi/both
	quoteMode 				: null,
	
	initialDestCode			: null,
	startDate				: null,
	endDate					: null,
	
	ignoreTripTypeChange	: false,


	constructor : function (config) {
		config = config || {}

		var cfg = {}

		cfg.single = {

			items : [
				{
					xtype : 'container',
					autoHeight : true,

					layout : 'column',

					items : [
						{
							xtype : 'single_dest',
							slot : 'single',

							initialDestCode	: config.initialDestCode,
							startDate		: config.startDate,
							endDate			: config.endDate,

							autoHeight : true,

							width : 470
						},
						{
							border : false,
							html : Ext.jx.getStoreValue("DEPT#CONSTART"),
							columnWidth : 1
						}
					]
				},
				{
					xtype : 'container',
					slot : 'resortInfo',

					autoHeight : true
				}
			]
		}

		cfg.multi = {
			layout : 'fit',

			items : [
				{
					xtype : 'multi_dest',
					slot : 'multi'
				}
			]
		}

		cfg.both = {

			layout : 'row-fit',

			items : [
				//trip type chooser
				{
					xtype: 'radiogroup',

					slot  : 'tripTypeBtn',
					
					height : 60,

					style : {
						'margin-left' : '10px'
					},

	                hideLabel: true,
	                columns: 1,

	                defaults : {
	                	name: 'tripType'
	                },


	                items: [
	                    {
	                    	boxLabel : 'Single Destination',

	                    	inputValue: 'single',
	                    	tripType : 'single',

	                    	checked : RL.Global.getTripType() == 'single',

		                    listeners : {
		                    	check : this.onCheckSwitchType,
		                    	scope : this
		                    }
                    	},
	                    {
	                    	boxLabel : 'Multiple Destinations',

	                    	inputValue: 'multi',
	                    	tripType : 'multi',
	                    	
	                    	checked : RL.Global.getTripType() == 'multi',

		                    listeners : {
		                    	check : this.onCheckSwitchType,
		                    	scope : this
		                    }
                    	}
	                ]
                },
                //eof trip type chooser

                //trip type details
            	{
            		xtype : 'container',
        			slot : 'tripType',

        			height : '100%',
        			layout : 'card',

        			activeItem : RL.Global.getTripType() == 'single' ? 0 : 1,

					layoutConfig : {
						deferredRender		: true,
						layoutOnCardChange	: true
					},

        			items : [
	    				{
							xtype : 'container',
							slot : 'single',

							autoHeight : true,

							items : [
								{
									xtype : 'container',
									autoHeight : true,

									layout : 'column',

									items : [
										{
											xtype : 'single_dest',

											width : 470,
											
											destCode	: config.destCode,
											startDate	: config.startDate,
											endDate		: config.endDate
										},
										{
											border : false,
											html : Ext.jx.getStoreValue("DEPT#CONSTART"),
											columnWidth : 1
										}
									]
								},
								{
									xtype : 'container',
									slot : 'resortInfo',

									autoHeight : true
								}
							]
						},
						{
							xtype 	: 'container',
							slot 	: 'multi',

	    					layout : 'columnfit',

	    					items : [
								{
			    					xtype 		: 'multi_dest',

									width : 530,
									autoHeight	: true
								},
								{
									border : false,
									html : Ext.jx.getStoreValue("DEPT#CONSTART"),
									columnWidth : 1
								}
	    					],

							autoHeight	: true  //this line is now required as of ext 3.01
						}
					]
                }
                //eof trip type details
            ]
		}

		var quoteMode = config.quoteMode

		cfg[quoteMode].title = '1.Start'

		Ext.apply(config, cfg[quoteMode])

		this.addEvents('triptype-changed')
		this.enableBubble('triptype-changed')

		RL.Quote.Wizard.Start.superclass.constructor.call(this, config)
	},


	initComponent : function () {
		RL.Quote.Wizard.Start.superclass.initComponent.call(this)

		this.on('destination-changed', this.onDestinationChanged, this)
	},


	onDestinationChanged : function (destCode) {
		this.updateInlineContent(destCode)
	},


	onCheckSwitchType : function(button, check) {

		if (check && !this.ignoreTripTypeChange) {
		   	//if there are any service items added to quote
			var haveItems 	= Ext.jx.getStore('BUILD').getCount()
			var tripType 	= button.tripType

			var switchFunc	= function (btn) {
		   		if (btn == 'yes') {
					this.slots.tripType.getLayout().setActiveItem(this.slots[tripType])
		
					//XXX access to global state
					RL.Global.tripType = tripType
		
					if (haveItems)
						RL.Global.startQuoteOver()
					else
						this.fireEvent('triptype-changed', tripType)
		   		} else {
		   			this.ignoreTripTypeChange = true
		   		
		   			//reverting the trip type radio button state
		   			this.slots.tripTypeBtn.setValue(tripType == 'single' ? 'multi' : 'single')
		   		}
		   	}

			if (haveItems) 
				Ext.Msg.show({
			   		title  		: 'Warning',
			   		msg			: 'Switching between trip types will clear existing quote. Are you sure you want to continue?',
				   	buttons		: Ext.Msg.YESNO,
				   	icon		: Ext.MessageBox.WARNING,
				   	
				   	fn			: switchFunc,
				   	scope		: this
				})
			else
				switchFunc.call(this, 'yes')
		}
		
		this.ignoreTripTypeChange = false
	},



	validate : function () {
		//both mode - validating active card only
		if (this.slots.tripType) return this.slots.tripType.layout.activeItem.validate()

		return RL.Quote.Wizard.Start.superclass.validate.call(this)
	},


	updateInlineContent : function (dest) {
		var destRecord = Ext.jx.getStore("RESORT").data.map['RESORT#SEARCHCODE=' + dest]

		var resortInfo = this.slots.resortInfo

		resortInfo.removeAll()

		if (destRecord) resortInfo.add({
			xtype : 'dest_content',

			style : {
				'margin-top' : '30px'
			},

			destRecord : destRecord,
			noPanPanels : true,

			height : 1300
		})

		if (resortInfo.el) resortInfo.doLayout(false, true)
	}

})

Ext.reg('quote_wizard_start', RL.Quote.Wizard.Start)

Ext.ns('RL.Quote.Wizard.Start');

RL.Quote.Wizard.Start.Single = Ext.extend(Ext.Panel, {

	//establish a slots collector
	slots : true,
	
	border: false,
	
	layout : 'row-fit',

	bodyStyle : {
		'overflow-y':'auto',
		'overflow-x':'hidden'
	},
	
	
	initialDestCode			: null,
	startDate				: null,
	endDate					: null,
	


	constructor : function (config) {

		var destSelect = { xtype : 'container' }

		var defaultDest = RL.Global.getDefaultDestCode() || config.initialDestCode
		

		if (defaultDest)
			Ext.jx.setStoreValue("GTAW#RESORT", defaultDest)
		else
			destSelect = {
				xtype		: "form",
				autoWidth	: true,
				layout		: 'column',
				baseCls		: 'x-frameless',
				labelAlign	: 'top',
				fieldLabel	: "Destination",

				items:[{
					xtype: 'choose_resort_intell',
					slot : 'combo',
					allowBlank: false,
					name: 'GTAW#RESORT',
					listeners: {
						change: this.onChangeField,
						scope: this
					}
				},{
					xtype:'container_spacer',
					width:10
				},{

					xtype:'button',
					slot : 'dest_moreinfo',
					text: 'more info',
					iconCls: 'moreinfo-btn',
					scale: 'small',
					iconAlign: 'left',
					handler: this.onDestMoreInfo,
					moreInfoImg: true,
					scope: this
				}]
			}


		Ext.apply(config, {

			items : [{
				xtype : 'fieldset',
				autoHeight: true,
				width:400,
				border: false,
				style: {
					padding:'10px;'
				},

				defaults: {
					border: false
				},

				items: [destSelect,
				{
					xtype:'air_question',
					fromField:{
						listeners: {
							change: this.onChangeField,
							scope: this
						}
					},
					toField:{
						listeners: {
							change: this.onChangeField,
							scope: this
						}
					}
				//},Ext.jx.getStoreValue("DEPT#CONNODATES")==1 ? {} : {
				//	xtype:'daterange',
				//	startDateFieldName: 'GTAW#DDATE',
				//	endDateFieldName: 'GTAW#RDATE',
				//	startDateField:{
				//		listeners: {
				//			change: this.onChangeField,
				//			scope: this
				//		}
				//	},
				//	endDateField:{
				//		listeners: {
				//			change: this.onChangeField,
				//			scope: this
				//		}
				//	}
				},{
					fieldLabel: 'No. Adults',
					name: 'GTAW#ADULT',
					allowBlank: false,
					xtype: 'perperson_selector',
					listeners:{
						render:function(c){
							c.setValue(Ext.jx.getStoreValue("DEPT#TQNOADL"));
						},

						blur: this.onChangeField,
						//change: this.onChangeField,
						spin: this.onChangeField,
						scope: this

					}
				},Ext.jx.getStoreValue("DEPT#CONNOCHILD")==1 ? {} : {
					fieldLabel: 'No. Children',
					name: 'GTAW#CHILD',
					allowBlank: true,
					xtype: 'perperson_selector',
					childField: true,
					listeners: {
						blur: this.onChangeField,
						//change: this.onChangeField,
						spin: this.onChangeField,
						scope: this
					}

				},Ext.jx.getStoreValue("DEPT#CONHIDECUR")==1 ? {} : {

					xtype:'currency',
					fieldLabel: 'Currency',
					name: 'GTAW#CADCURR',
					allowBlank: true,
					listeners: {
						change: this.onChangeField,
						scope: this
					}


				}]
			},{

				xtype: "buttongroup",
				columns: 2,
				autoWidth:true,
				autoHeight : true,
				
				baseCls: 'x-frameless',
				slot : 'toolbar',
				items: [{

					xtype:'button',
					slot:'newQuoteBtn',
					text: 'start here',
					iconCls: 'new-quote-btn',
					scale: 'large',
					//scale: 'small',
					iconAlign: 'left',
					handler: this.onNewQuote,
					scope : this,
					style:{
						margin: '0 0 0 90px'
					}
				},{	
					xtype:'button',
					iconCls: 'add-to-cart',
					hidden: true
				}]
			}
			
//			,{
//				xtype : 'container',
//				autoEl : 'div',
//				autoWidth:true,
//				//frame: false,
//				//baseCls: 'x-frameless',
//
//				slot : 'resortInfo'
//				//autoHeight : true,
//
//				//items: [{
//				//	//hideBorder:true,
//				//	baseCls: 'x-frameless',
//				//	html: '&nbsp;'
//				//}]
//			}
			]

		});

		//config.frame =(RL.Defaults.QUOTE_MODE!='single');

		this.addEvents('quote-changed', 'destination-changed')
		this.enableBubble('quote-changed', 'destination-changed')


		RL.Quote.Wizard.Start.Single.superclass.constructor.call(this, config);
	},


	onNewQuote : function () {
		var gtawRecord = Ext.jx.getStore('GTAW').getAt(0)

		if (!gtawRecord.data['GTAW#RESORT'])
			Ext.Msg.alert('Note', 'Choose a destination and then click this button.')
		else
			RL.Global.getWizard(this).onNextStep()
	},


	onDestMoreInfo: function (img) {
		if (img.dest)
			RL.Global.showContent(RL.Global.getWizard(this), 'dest', img.dest, 'Pictures')
		else
			Ext.Msg.alert('Note', 'Choose a destination and then click this button for more information.')
	},


	onChangeField: function (fld){
		var wizard=RL.Global.getWizard(fld), gtawRecord=Ext.jx.getStore('GTAW').getAt(0);
		gtawRecord.set(fld.name, fld.getValue());

		if (fld.name==='GTAW#ADULT' || fld.name==='GTAW#CHILD')
			this.fireEvent('quote-changed')
		else
			if (fld.name==='GTAW#CADCURR') {
				RL.Global.getCurrency();
			}else if (fld.name==='GTAW#RESORT') {

				this.fireEvent('quote-changed')

				var moreInfoImg = this.slots.dest_moreinfo;
				//if (Ext.jx.getStoreValue("DEPT#CONINLDEST")!=1 ){
					
					(function () {
						
						this.fireEvent('destination-changed', fld.value)
						
					}).defer(100,this);//this will make the UI seem more responsive
					
					moreInfoImg.hide();
				//}else{
				//	moreInfoImg.dest=fld.value; //this is used by onDestMoreInfo
				//}

				(function(){
					RL.Global.updateAirportByDest(fld.value);
					wizard.updateQuoteSteps(fld.getValue());
				}).defer(100,this);//this will make the UI seem more responsive

			}

		wizard.prefetchPrices.defer(100, wizard);
	},


	afterRender : function () {
        RL.Quote.Wizard.Start.Single.superclass.afterRender.call(this);

		var defaultDest = RL.Global.getDefaultDestCode();

		if (defaultDest) {
			var me=this;
			(function(){
				RL.Global.updateAirportByDest(defaultDest);
				RL.Global.getWizard(me).updateQuoteSteps(defaultDest);

				me.fireEvent('destination-changed', defaultDest)

			}).defer(100);//this will make the UI seem more responsive

		}
	}

});

Ext.reg('single_dest', RL.Quote.Wizard.Start.Single);

Ext.ns('RL.Quote.Wizard.Start');


RL.Quote.Wizard.Start.Multi = Ext.extend(Ext.Panel, {

	slots 			: true,


	constructor : function(config) {

		Ext.apply(config, {

			border 			: false,
			autoHeight		: true,

			bodyStyle : {
				padding : '10px'
			},

			layout 			: 'form',

			items : [
				{
					slot : 'dest_group',
					xtype : 'dest_group'
				},{
					//spacer
					xtype : 'container',
					height : 10
				},{
					xtype:'air_question'
				},{
					//spacer
					xtype : 'container',
					height : 5
				},{
					xtype: 'perperson_selector',

					name: 'GTAW#ADULT',

					fieldLabel: 'No. Adults',

					allowBlank: false,

					value : Ext.jx.getStoreValue("DEPT#TQNOADL"),

					listeners: {
						blur: this.onChangeField,
						spin: this.onChangeField,
						scope: this
					}
				},Ext.jx.getStoreValue("DEPT#CONNOCHILD") == 1 ? {} : {
					fieldLabel: 'No. Children',
					name: 'GTAW#CHILD',
					xtype: 'perperson_selector',

					childField: true,
					listeners: {
						blur: this.onChangeField,
						spin: this.onChangeField,
						scope: this
					}
				},Ext.jx.getStoreValue("DEPT#CONHIDECUR")==1 ? {} : {

					xtype:'currency',
					fieldLabel: 'Currency',
					name: 'GTAW#CADCURR',
					allowBlank: true,
					listeners: {
						change: this.onChangeField,
						scope: this
					}

				},{
					//spacer
					xtype : 'container',
					height : 15
				},{
					xtype: "toolbar",
					slot : 'toolbar',
					height : 45,
					items: [{
						scale : 'large',
						iconCls: 'new-quote-btn',

						text : 'Start here',

						handler: this.onNewQuote,
						scope : this
					}]
				}
			]
		})


		this.addEvents('quote-changed')
		this.enableBubble('quote-changed')


		RL.Quote.Wizard.Start.Multi.superclass.constructor.call(this, config);
	},


	onNewQuote : function(){
		RL.Global.getWizard(this).onNextStep();
	},


	onChangeField: function (field) {
		var gtawRecord = Ext.jx.getStore('GTAW').getAt(0)

		gtawRecord.set(field.name, field.getValue())

		if (field.name==='GTAW#CADCURR') RL.Global.getCurrency();

		this.fireEvent('quote-changed')
	}

});

Ext.reg('multi_dest', RL.Quote.Wizard.Start.Multi);

function above_wizard_notify (options) {
	Ext.ux.Sound.enable();
	Ext.ux.Sound.play( options.sound || Ext.jx.Server.getPrimary()+'/wrm_client/ExtClient/notify.wav');
	new Ext.ux.window.MessageWindow({
		//title: 'Example 1',
		autoDestroy: true,//default = true
		autoHeight: true,
		bodyStyle: {
			'text-align':'center'
		},
		closable: false,

		animateTarget: document,

		plain: true,
		baseCls: 'x-box',//defaults to 'x-window'
		clip: 'bottom',//clips the bottom edge of the window border

		//shadow: false,
		//shiftHeader: true,//use when want the header to be moved to the body in the window's dom

		help:false,

		autoHide: true,//default = true
		pinState : 'unpin',
		//pinState: null,//don't show pin tools
		//handleHelp: function(){
		//	console.info('help requested');
		//},
		pinOnClick:false,

		showFx: {
			delay: 0,
			duration: 2.0, //defaults to 1 second
			//mode: 'standard',//null,'standard','custom',or default ghost
			mode: 'slideIn',
			useProxy: false //default is false to hide window instead
		},

		hideFx: {
			//delay: 5000,
			//duration: 0.25,

			delay: 10000, //other than 0 will create automatic refreshes
			duration: 1.0, //defaults to 1 second
			//mode: 'standard',//null,'standard','custom',or default ghost
			//mode: 'standard',//null,'standard','custom',or default ghost
			mode: 'slideOut',
			useProxy: false //default is false to hide window instead
		},
		html: options.html,
		//iconCls: 'x-icon-error',

		////configure a different origin than the default bottom right corner of the window:
		origin: {
			//get window's Ext.element:
			//el: Ext.get('northRegion'), //element to align to (defaults to document)
			//el:window.gtawNew.slots.wizard.el,
			el:window.gtawNew.slots.banner.el,
			increment: false, //whether to increment position of subsequent messages
			pos: "bl-bl",//position to align to (see {@link Ext.Element#alignTo} for more details defaults to "br-br").
			offX: 10, //amount to offset horizontally (-20 by default)
			offY: 0 //amount to offset vertically (-20 by default)
		},


		////optionally enable sound...see http://efattal.fr/extjs/examples/toastwindow/
		////if you want to enable sound with this
		//listeners: {
		//	'beforerender': function(){
		//		Sound.enable();
		//		Sound.play('notify.wav');
		//		Sound.disable();
		//	}
		//},

		width: options.width || 400 //optional (can also set minWidth which = 200 by default)
	}).show(Ext.getDoc());

}




Ext.ns('RL.Quote.Wizard.Start');



RL.Quote.Wizard.Start.AirQuestion = Ext.extend(Ext.Panel, {

	slots 			: true,
	
	border 			: false,
	autoHeight		: true,
	width			: 300,

	layout 			: 'form',
	bodyStyle 		: {
		padding : '10px'
	},


	constructor : function(config) {
		
		if (Ext.jx.getStoreValue("DEPT#CONUSEAIR") == 0 ){
			RL.Quote.Wizard.Start.AirQuestion.superclass.constructor.call(this, {hidden:true});
			return;
		};


		if (!config.fromField) config.fromField = {};
		
		var areAirportsHidden = Ext.jx.getStoreValue("DEPT#CONUSEAIR") == 1
		
		Ext.applyIf(config.fromField, {
			xtype 		: 'airport',
			slot 		: 'from_airport',
			
			allowBlank 	: areAirportsHidden,
			name		: '#FROM_AIRPORT',
			
			emptyText	: 'Outgoing airport',
			fieldLabel 	: "Leaving from"
		});

		
		if (!config.toField) config.toField = {};
		
		Ext.applyIf(config.toField, {
			xtype 		: "airport",
			slot		: 'to_airport',
			
			allowBlank 	: areAirportsHidden,
			name		: '#TO_AIRPORT',
			
			emptyText	: 'Destination airport',
			fieldLabel 	: 'Going to'
		});


		Ext.apply(config, {

			items : [
				{
					xtype : 'fieldset',
					slot  : 'fieldset',	
					
					title : '<nobr>Would you like to see flights?</nobr>', 
					checkboxToggle : true,
					checkboxName : '#AIR_OPTION',
					
					onCheckClick : this.airTypeChanged.createDelegate(this),
					
					collapsed : areAirportsHidden,
					animCollapse : false,
					
					items : [ 
						config.fromField, 
						config.toField 
					]
		        }
	        ]
		});

		delete config.fromField;
		delete config.toField;

		RL.Quote.Wizard.Start.AirQuestion.superclass.constructor.call(this, config);
	},
	
	
//	initComponent : function () {
//		RL.Quote.Wizard.Start.AirQuestion.superclass.initComponent.call(this)
//	},


	airTypeChanged : function() {
		var slots = this.slots
		
		slots.fieldset.toggleCollapse()
		
		if (slots.fieldset.collapsed) {
			slots.from_airport.allowBlank = true
			slots.to_airport.allowBlank = true
		} else {
			slots.from_airport.allowBlank = false
			slots.to_airport.allowBlank = false
		}
		
		(function () { //this is to keep the UI responsive
			RL.Global.getWizard(this).updateQuoteSteps()
		}).defer(100, this)
	}

});

Ext.reg('air_question', RL.Quote.Wizard.Start.AirQuestion);





//(function(){ //the idea is solid but it causes too many problems bolted in...REAFFIRMED ON 10/10/09
//	var old=Ext.Component.prototype.destroy;
//	Ext.Component.prototype.destroy=function(){
//		try{
//			if (this.ownerCt) {
//				this.hide();
//			}else{
//				if (this.getResizeEl){
//					this.getResizeEl.addClass('x-hidden');
//				}else{
//					old();
//				}
//			}
//			old.defer(5000,this);
//		}catch(e){
//			old();
//		}
//	}
//})();


//Ext.ns('Ext.ux.Toolbar');
//
//
//Ext.ux.Toolbar.Button = Ext.extend(Ext.Toolbar.Button, {
//
//	invalidClass: "x-toolbar-button-invalid",
//	invalidText: "You have made changes. Click the button on the left to continue",
//    msgTarget : 'side',
//    msgFx : 'normal',
//
//	markInvalid: Ext.form.Field.prototype.markInvalid,
//	clearInvalid: Ext.form.Field.prototype.clearInvalid,
//	getMessageHandler: Ext.form.Field.prototype.getMessageHandler,
//	alignErrorIcon: Ext.form.Field.prototype.alignErrorIcon,
//
//    getErrorCt : function(){
//		return this.el;
//    },
//
//
//    initComponent : function(){
//        Ext.Toolbar.Button.superclass.initComponent.call(this);
//        this.addEvents(
//            'invalid',
//            'valid'
//        );
//    }
//
//
//});
//
//Ext.reg('ux_tbbutton',Ext.ux.Toolbar.Button);


Ext.ns('RL.Quote.Wizard.Start.Multi');


RL.Quote.Wizard.Start.Multi.DestRow = Ext.extend(Ext.Container, {
	
	slots 			: true,


	required		: false,
	
	
	initComponent : function () {
		
		Ext.apply(this, {
			
			defaults : {
				border: false
			},
			
			layout : 'column',
			height: 30,
			
			
			items : [{
				xtype : 'choose_resort_intell',
				slot : 'combo',
				
				name: 'GTAW#RESORT',
				
				allowBlank: !this.required, 
				emptyText : 'Destination',
				
				listeners: {
					change : this.onDestChange,
					scope  : this
				}

			},{
				xtype:'container_spacer',
				width : 5,
				html : '&nbsp;'
			},{
						
				xtype:'button',
				slot : 'dest_moreinfo',
				
				disabled : true,
				
				iconCls: 'moreinfo-btn',
				handler: this.onDestMoreInfo,
				moreInfoImg: true,
				scope: this
				
			},{
				xtype:'container_spacer',
				width : 20,
				html : '&nbsp;'
			},Ext.jx.getStoreValue("DEPT#CONNODATES")==1 ? {} : {
				
				xtype:'daterange',
				
				width : 210,
				
				layout:'column',
				
				startDateFieldName: 'GTAW#DDATE',
				startDateField:{
					slot : 'startdate',
					
					disabled : true,
					allowBlank: false,
					emptyText:'Arriving'
				},
				
				endDateFieldName: 'GTAW#RDATE',
				endDateField:{
					slot : 'enddate',
					
					emptyText:'Departing',
					disabled : true,
					allowBlank: false,
					
					listeners: {						
						change: function(fld){
							this.getDestGroup().onChange_childEndDate(this);
						},
						scope: this
					}
				},
				
				spacerField:{
					xtype:'container_spacer',
					width : 5,
					html : '&nbsp;'					
				}
				
			},{
				xtype:'container_spacer',
				width : 5,
				html : '&nbsp;'
			},{
				//slot: this.fieldNames.removeLink,
				width:70,
				//width : Ext.isIE6 ? 200 - 4 : Ext.isIE7 ? 200 - 1 : 200,
				html : '<span style="text-decoration:underline; cursor:pointer;">Remove</span>',
				style : {
					'line-height':'22px'
				},
				cls : 'x-form-item',
				listeners:{
					afterrender:function(){
						this.el.child('span').on('click', function() {
							this.getDestGroup().removeDest(this);
						}, this);
					},
					scope:this
				}
			}]

			
		});
		
		RL.Quote.Wizard.Start.Multi.DestRow.superclass.initComponent.call(this);
	},
	
	

	getDestGroup : function(){
		return this.findParentBy(function(p){ return p.onChange_childDest });
	},
	

	onDestMoreInfo: function(img){
		if (img.dest){
			RL.Global.showContent(RL.Global.getWizard(this), 'dest', img.dest, 'Pictures');
		}else{
			Ext.Msg.alert('Note', 'Choose a destination and then click this button for more information.');
		}
	},

	
	onDestChange : function(fld){
		var moreInfoImg		= this.findBy(function(c){ return c.moreInfoImg })[0];
		moreInfoImg.dest	= fld.value; //this is used by onDestMoreInfo
		
		var slots = this.slots
		
		slots.startdate.enable()
		slots.enddate.enable()
		slots.dest_moreinfo.enable()
		
		this.getDestGroup().onChange_childDest(this);
	},
	
	
	validate : function () {
		if (!this.required) return true
		
		return RL.Quote.Wizard.Start.Multi.DestRow.superclass.validate.call(this)
	}

});

Ext.reg('dest_row', RL.Quote.Wizard.Start.Multi.DestRow);
Ext.ns('RL.Quote.Wizard.Start.Multi');

RL.Quote.Wizard.Start.Multi.DestGroup = Ext.extend(Ext.Container, {
	
	slots : true,
					

	constructor : function(config) {
			
		Ext.apply(config, {
			autoHeight : true,
			
			items : [{
				xtype 			: 'dest_row',
				required		: true
			}]						
		})
		
		RL.Quote.Wizard.Start.Multi.DestGroup.superclass.constructor.call(this, config);
	},

	onChange_childDest: function(destRow){
		var items=this.findByType('dest_row');
		var n=this.items.indexOf(destRow);
		if (n==0) RL.Global.updateAirportByDest(destRow.getValues()['GTAW#RESORT']);

		var l=items.length;
		if (n+1==l) {
			if (n>0){
				var values=destRow.getValues();
				if (!values['GTAW#DDATE']){
					var lastRow=this.items.items[n-1]
					this.onChange_childEndDate(lastRow, true);
				}
			}
			this.addDest();
		}
		RL.Global.getWizard(this).updateQuoteSteps();		
	},
	
	onChange_childEndDate: function(destRow, bypassCheck){
		var items=this.findByType('dest_row');
		var values=destRow.getValues();
		if (values['GTAW#RDATE']){
			var n=this.items.indexOf(destRow);
			var l=items.length;
			if (bypassCheck || n+2<l) this.items.items[n+1].setValues({'GTAW#DDATE':values['GTAW#RDATE']}); //if it is not the last date..set the next start date to equal the last end date
		}
	},
	

	addDest : function(){
		var newRow=new RL.Quote.Wizard.Start.Multi.DestRow({height:0});
		this.add(newRow);
		this.doLayout();

//		(function () {
			newRow.el.setHeight(30, {
				callback : function(){
				},
				scope : this
			});
//		}).defer(100)
		
	},	
	
	removeDest: function(destRow){
		var items=this.findByType('dest_row');
		var n=this.items.indexOf(destRow);
		var l=items.length;
		if (n>0 && l>2) RL.Global.updateAirportByDest(this.items.items[1].getValues()['GTAW#RESORT']); //if you are deleting the first row then set the airport off of the second row
		if (n+1!=l) {
			destRow.el.setHeight(0, {
				callback : function(){
					this.remove(destRow);
					if (n) { //this is to fix date holes when you delete a date in the middle
						var lastRow=this.items.items[n-1]
						this.onChange_childEndDate(lastRow);
					}					
					RL.Global.getWizard(this).updateQuoteSteps();
				},
				scope : this
			});
		}else{
			if (l==1){
				Ext.Msg.alert('Note', 'You must specify at least one destination.');
			}else{
				Ext.Msg.alert('Note', 'There is no reason to delete this destination. The last row is ignored.');
			}
		}
		
	},
	
	
	getName:function(){ //this function gets picked up by container.getValues
		return 'dest_group';
	},

	
	getValue:function(){ //this function gets picked up by container.getValues
		var values=[];
		this.items.items.each(function(c){
			values.push(c.getValues());
		})
		return values;
	}
	

});

Ext.reg('dest_group', RL.Quote.Wizard.Start.Multi.DestGroup);
Ext.ns('RL')


RL.Build = Ext.extend(Ext.Panel, {

	// XXX seems the BUILD record can also be used, as pricing record (_VENDOR_PRICING)
	// edit action will rely on this
	pricingRecord			: null,

	slots					: true,
	
	initialValues			: null,


	constructor : function(config) {
		config = config || {}

		Ext.apply(config, {

			layout : 'row-fit',

			hideBorders:true,
			labelAlign:'top',

			baseCls: 'x-frameless',

			//additional style, required for IE
			style : 'overflow : hidden',

            items : [
            	//Quantity&occupancy
	        	{
				    autoHeight : true,

				    layout:'table',
					layoutConfig: {
						columns: 5
					},

					baseCls:'x-frameless',

					items:[{
						slot:'qty_lbl',
						baseCls:'x-frameless',
						cls:'x-form-item-label',
						html:'No. Rooms'
					},{
						xtype:'container_spacer',
						width:15
					},{
						slot:'occpy_adults_lbl',
						baseCls:'x-frameless',
						cls:'x-form-item-label',
						html:'Adults / Room'
					},{
						xtype:'container_spacer',
						width:15
					},{
						slot:'occpy_children_lbl',
						baseCls:'x-frameless',
						cls:'x-form-item-label',
						html:'Children / Room'
					},{

						slot:'qty',
						xtype : 'spinnerfield',
						fieldLabel: 'No. Units',
						width : 50,
						name: 'BUILD#UNITS',
						minValue: 1,
						allowBlank: false
					},{
						xtype:'container_spacer',
						width:15

					},{

						slot:'occpy_adults',
						xtype: 'perperson_selector',
						fieldLabel: 'Adults / Room',
						name: '#NO_ADULTS',
						minValue: 1,
						allowBlank: false
					},{
						xtype:'container_spacer',
						width:15
					},{

						slot:'occpy_children',
						xtype: 'perperson_selector',
						fieldLabel: 'Children / Room',
						name: '#NO_CHILDREN',
						minValue: 0,
						allowBlank: true

					}]

				},
				//eof Quantity&occupancy

				//dates&times
				{
					autoHeight : true,

				    layout:'table',
					layoutConfig: {
						columns: 7
					},
					baseCls:'x-frameless',
					bodyStyle:{
						padding:'10px 0 10px 0'
					},

					items:[
					//labels
					{
						slot:'startdate_lbl',
						baseCls:'x-frameless',
						cls:'x-form-item-label',
						html:'Start Date'
					},{
						slot:'starttime_lbl_spacer',
						xtype:'container_spacer',
						width:10
					},{
						slot:'starttime_lbl',
						baseCls:'x-frameless',
						cls:'x-form-item-label',
						html:'Start Time'
					},{
						slot:'enddate_lbl_spacer',
						xtype:'container_spacer',
						width:10
					},{
						slot:'enddate_lbl',
						baseCls:'x-frameless',
						cls:'x-form-item-label',
						html:'End Date'
					},{
						slot:'endtime_lbl_spacer',
						xtype:'container_spacer',
						width:10
					},{
						slot:'endtime_lbl',
						baseCls:'x-frameless',
						cls:'x-form-item-label',
						html:'End Time'
					},
					//eof labels


					//fields
					{
						slot:'startdate',
						xtype:'daterange_start',
						fieldLabel: 'Start Date',
						name: 'BUILD#DDATE',
						endDateField: 'BUILD#RDATE'
					},{
						slot:'starttime_spacer',
						xtype:'container_spacer',
						width:10
					},{
						slot:'starttime',
						xtype:'textfield',
						fieldLabel: 'Start Time',
						name: 'BUILD#STARTTIME'
					},{
						slot:'enddate_spacer',
						xtype:'container_spacer',
						width:10
					},{
						slot:'enddate',
						xtype:'daterange_end',
						fieldLabel: 'End Date',
						name: 'BUILD#RDATE',
						startDateField: 'BUILD#DDATE'
					},{
						slot:'endtime_spacer',
						xtype:'container_spacer',
						width:10
					},{
						slot:'endtime',
						xtype:'textfield',
						fieldLabel: 'End Time',
						name: 'BUILD#ENDTIME'
					}
					//eof fields
					]
				},
				//eof dates&times

				{
					slot:'helptxt',
					baseCls:'x-frameless',
					cls:'x-form-item-label'
				},

				//buttons
				{
					xtype: "container",

					height : 40,

					layout : 'column',

					//hack for IE6
					style : Ext.isIE6 ? 'margin-top : -10px' : undefined,

					items : [
						{
							xtype:'button',
							width : 100,

							text: config.addButtonText || 'add',

							iconCls: 'service-add-btn',
							scale: 'large',
							iconAlign: 'left',

							handler : this.onAddService,
							scope : this
						},
						{
							xtype : 'container',
							html : '&nbsp;',
							columnWidth : 1
						},
						{
							xtype:'button',
							width:100,

							text: 'cancel',

							iconCls: 'hide-btn',
							scale: 'large',
							iconAlign: 'left',

							handler : this.onCancel,
							scope : this
						}
					]
				}
				//eof buttons
			]

		})
		//eof apply

		RL.Build.superclass.constructor.call(this, config)
	},


	initComponent : function(){
		RL.Build.superclass.initComponent.call(this)

		this.addEvents('add-service')

		var slots 			= this.slots
    	var productRecord 	= this.pricingRecord.getService()
    	var product 		= productRecord.data


		//quantity
    	if (product['SERVICE#QTYLAB'])
			slots.qty_lbl.html = product['SERVICE#QTYLAB']
		else
			slots.qty_lbl.html = productRecord.isPerPerson() ? 'No. Items' : 'No. Units'


		var webMaxQty = Number(product['SERVICE#WEBMAXQTY'])

		slots.qty.maxValue = webMaxQty > 1 ? webMaxQty : 999

		if (productRecord.isPerPerson() && !this.initialValues) slots.qty.setValue(gtawRecord.getAdultsNum() + gtawRecord.getChildrenNum())
		
		
		//setting initial values
		if (this.initialValues) this.setValues(this.initialValues)
		

		//startdate
		slots.startdate_lbl.html = product['SERVICE#DSTARTLAB']

		slots.startdate.setValue(this.pricingRecord.get('BUILD#DDATE'))

		slots.startdate.minDays = Number(product['SERVICE#SAMEDAY']) == 1 ? 0 : 1


		//enddate
		slots.enddate.setValue(this.pricingRecord.get('BUILD#RDATE'));//it gets sent regardless of whether it is displayed

		if (Number(product['#B_PRICENIGHTLY']) == 1 || Number(product['#B_DONT_AUTOCHANGE_END_DATE']) == 1) {
			if (product['SERVICE#DENDLAB']) slots.enddate_lbl.html = product['SERVICE#DENDLAB']
		} else {
			slots.enddate.allowBlank = true

			slots.enddate_lbl_spacer.hide()
			slots.enddate_lbl.hide()
			slots.enddate_spacer.hide()
			slots.enddate.hide()
		}


		//occpy levels
		if (Number(product['#B_USEOCCUPANCYLEVELS']) == 1) {
			if (Ext.jx.getStoreValue("DEPT#CONNOCHILD") == 1) {
				slots.occpy_children_lbl.hide()
				slots.occpy_children.hide()
				slots.occpy_children.allowBlank = true
			}

		} else {
			slots.occpy_adults_lbl.hide()
			slots.occpy_adults.hide()
			slots.occpy_adults.allowBlank = true

			slots.occpy_children_lbl.hide()
			slots.occpy_children.hide()
			slots.occpy_children.allowBlank = true
		}


		//start time
		if (Number(product['#B_USE_START_TIME']) == 1) {
			if (product['SERVICE#STIMELAB']) slots.starttime_lbl.html = product['SERVICE#STIMELAB']
		} else {
			slots.starttime_lbl_spacer.hide()
			slots.starttime_lbl.hide()
			slots.starttime_spacer.hide()
			slots.starttime.hide()
			slots.starttime.allowBlank = true
		}


		//end time
		if (Number(product['#B_USE_END_TIME']) == 1) {
			if (product['SERVICE#ETIMELAB']) slots.endtime_lbl.html = product['SERVICE#ETIMELAB']
		} else {
			slots.endtime_lbl_spacer.hide()
			slots.endtime_lbl.hide()
			slots.endtime_spacer.hide()
			slots.endtime.hide()
			slots.endtime.allowBlank = true
		}

		if (RL.Defaults.USE_PROD_HELP_TXT) slots.helptxt.html = product['SERVICE#HELP']


		//not using now
		//#B_AUTO_INC_START_DATE_ON_ADDITIONAL

		//not using here
		//#B_DONT_AUTOCHANGE_END_DATE
		//#B_DONT_SHOW_DATES_ON_SEARCH
		//#B_MISC_PRODUCT
		//#S_INITIAL_SORT_COL
		//#B_USE_TRANSFERINFO
		//#B_USEUNITOPENFILTER
		//#B_USE_AIRPORT_FROM
		//#B_USE_AIRPORT_TO
		//#B_USEFILTERS
		//#B_USEGDS
		//#B_USEINVENTORY
		//#B_USEMAPS

		//SERVICE#UNITLAB
		//SERVICE#VENDORLAB
		//SERVICE#CODEDESC

	},


	onAddService : function () {
		if (!this.validate()) return

		this.fireEvent('add-service', this, this.getValues())
	},


	onCancel : function () {
		this.fireEvent('cancel', this)
	}


})
//eof extend

Ext.reg('rl_build', RL.Build)

Ext.ns('RL.Build')


RL.Build.More = Ext.extend(Ext.Panel, {
	
	slots					: true,
	

	constructor : function (config) {
		config = config || {}

		Ext.apply(config, {

			baseCls : 'x-frameless',

			frame : true,
			hideBorders : true,
			
			items : [
				{
					slot : 'content',
					frame : false,
					baseCls : 'x-frameless',
					cls : 'afterAddMsg',
					html : ''
				}
			],
			
			
			bbar : [
				{
					xtype : 'button',
					
					text : 'more',
					
					iconCls : 'service-addanother-btn',
					scale : 'large',
					iconAlign : 'left',
					
					handler : this.onMoreClick,
					scope : this
				},
				'->',
				{
					xtype : 'button',
					
					text : 'skip',
					
					iconCls : 'service-next-btn',
					scale : 'large',
					iconAlign : 'left',
					
					handler : this.onSkipClick,
					scope : this
				}
			]

		})
		//eof apply

		RL.Build.More.superclass.constructor.call(this, config)
	},


	initComponent : function(){
		RL.Build.More.superclass.initComponent.call(this)

		this.addEvents('build-more', 'build-skip')
		this.enableBubble('build-more', 'build-skip')
	},
	
	
	refresh : function (buildRecord, tabName) {
		var content = this.slots.content
		
		if (!content.rendered) return
		
		content.body.update('<div class="added">You added <b>' + buildRecord.data['BUILD#SERVICE'] + '</b>.</div><div class="another">Would you like to add another from <b>' + tabName + '</b>?</div>')
	},
	
	
	onMoreClick : function () {
		this.fireEvent('build-more')
	},
	
	
	onSkipClick : function () {
		this.fireEvent('build-skip')
	}

})
//eof extend

Ext.reg('RL.Build.More', RL.Build.More)

Ext.ns('RL.Build')


RL.Build.Popup = Ext.extend(Ext.Panel, {
	
	pricingRecord			: null,
	searchForm  			: null,
	
	buildPopup				: null,
	
	slots					: true,
	

	initComponent : function(){
		Ext.apply(this, {

			baseCls 	: 'x-box',
			frame 		: true,
			hideBorders : true,
			
			width: 260,
			height : 170,
			
			layout : 'fit',
			
			
			items : [
				{
					xtype : 'panel',
					slot : 'slider',
					
					layout : 'slide',
					
					bodyStyle : {
						background : 'none transparent'
					},
					
					activeItem : 0,
					
					items : [
						{
							xtype 	: 'rl_build',
							slot	: 'build',
							
							pricingRecord : this.pricingRecord,
							searchForm : this.searchForm
						},
						{
							xtype 	: 'RL.Build.More',
							slot	: 'more'
						}
					]
				}
			]

		})
		//eof apply
		
		
		RL.Build.superclass.initComponent.call(this)

		var slots 			= this.slots
		
		slots.build.on('add-service', this.onAddService, this)
		slots.build.on('cancel', this.onMore, this)
		
		slots.more.on('build-more', this.onMore, this)
		slots.more.on('build-skip', this.onSkip, this)
	},


	onAddService : function (buildForm, values) {
    	var buildRecord 	= RL.Global.getWizard(this.searchForm).addServiceItem(this.pricingRecord, values)
		var searchForm 		= this.searchForm
    	
    	if (searchForm.canSuggestMoreItems()) {
    		var more = this.slots.more
    		
    		more.refresh(buildRecord, searchForm.getServiceItemDescription())
    		
    		this.slots.slider.layout.setActiveItem(more)
    	} else
    		this.onSkip()
	},
	
	
	onMore : function () {
		this.buildPopup.hide()
	},
	

	onSkip : function () {
		this.buildPopup.hide()
		
		this.searchForm.wizard.onNextStep()
	}

})
//eof extend

Ext.reg('RL.Build.Popup', RL.Build.Popup)

Ext.ns('RL.Vendor');

RL.Vendor.Calendar = Ext.extend(Ext.Panel, {
	
	baseCls			: 'x-frameless',
	
	invTab			: 'avail',
	frame			: false,
	autoWidth		: true,
	hideBorders		: true,
	layout 			: 'row-fit',
	
	
	pricingRecord	: null,
	vendorRecord	: null,
	searchForm		: null,

	
	constructor : function (config) {

		Ext.apply(config, {

			items:[{
				baseCls:'x-frameless',
				hideBorders:true,
				frame:false,
				calendar_parent:true,
				height:'100%',
				autoWidth:true,
				layout : 'row-fit'

			}]

		});
		RL.Vendor.Calendar.superclass.constructor.call(this, config);
	},


	initComponent : function() {

		if (this.pricingRecord){
			this.firstDt=this.pricingRecord.get('BUILD#DDATE');
			this.lastDt=this.pricingRecord.get('BUILD#RDATE');
			this.ventype=this.pricingRecord.get('BUILD#TYPE') || this.pricingRecord.get('VENDOR#VENTYPE');;
			this.venid=this.pricingRecord.get('BUILD#VENID') || this.pricingRecord.get('VENDOR#VENID');
			this.mgtcoid=this.pricingRecord.get('BUILD#MGTCOID') || this.pricingRecord.get('VENDOR#MGTCOID');
		}else if (this.vendorRecord){
			this.ventype=this.vendorRecord.get('VENDOR#VENTYPE');;
			this.venid=this.vendorRecord.get('VENDOR#VENID');
			this.mgtcoid=this.vendorRecord.get('VENDOR#MGTCOID');
		}
		if (!this.venid){
			alert('did not specify particular vendor on vendor calendar');
		}
		if (!this.firstDt && this.searchForm){
			var values=this.searchForm.getSearchValues();
			this.firstDt=values['#DDATE'];
			this.lastDt=values['#RDATE'];
		}
		if (!this.firstDt ){
			alert('did not specify particular dates on vendor calendar');
		}

		this.createToolbar();
		RL.Vendor.Calendar.superclass.initComponent.call(this);
	},

	
	updateToolbarDts:function(){
		this.topToolbar.el.child('.x-vendor-calendar-toolbar-dates').update('<b>'+this.firstDt.format('d M y') + '</b> to <b>' +this.lastDt.format('d M y')+'</b>');
	},

	
	
    createToolbar : function() {

		this.setDates(this.firstDt, this.lastDt, true);
		var dates='<div class="x-vendor-calendar-toolbar-dates"></div>';

		var invTabs=this.getInvTabs(), buttons=[];
		for (var id in invTabs){
			var tab=invTabs[id];
			buttons.push({
				invTab: id,
				pressed:(this.invTab===id),
				handler:this.onToggleClick,
				allowDepress:false,
				text: tab.desc,
				enableToggle: true,
				scope: this
			}, ' ');
		}

		this.tbar = new Ext.Toolbar({
			toolbarCls:'x-panel-bc',
			style:{
				padding:'5px 0 5px 0'
				//padding:'5px 0 0 0'
			},
			//height:30,
			//toolbarCls:'x-vendor-calendar-toolbar',

			items:[
			{
				xtype:'container_spacer',
				width:20
			},
			buttons,
			{
				xtype:'container_spacer',
				width:20
			},
			{
				scale : 'medium',
				iconCls: 'go-left-btn',
				handler: this.onClickPrevDate,
				scope: this
			},
			dates,
			{
				scale : 'medium',
				iconCls: 'go-right-btn',
				handler: this.onClickNextDate,
				scope: this
			}]
		})
		this.tbar.on('afterlayout', this.afterToolbarLayout, this)
    },
    afterToolbarLayout : function(tb){
		this.updateToolbarDts();
		//tb.el.child("table").set({align:'center', style:{width:'400px'}},1) //this centers the toolbar
	},

	onToggleClick : function(btn){

		if (btn.invTab === this.invTab) return
		this.invTab=btn.invTab;

		var btns=this.topToolbar.findBy(function(){ return this.enableToggle })
		Ext.each(btns, function(b){
			if (btn.id != b.id ) b.toggle(!btn.pressed);
		})

		this.onStoreReady.defer(100, this, []);

	},

	onClickPrevDate : function(btn){

		var lastDt=this.firstDt.add(Date.DAY,-1);
		var firstDt=Date.parseDate(lastDt.format('m')+'/01/'+lastDt.format('Y'),'m/d/Y');
		if (lastDt.subtractDt(firstDt)<14){
			dt=this.firstDt.add(Date.DAY,-1);
			firstDt=Date.parseDate(dt.format('m')+'/01/'+dt.format('Y'),'m/d/Y');
		}
		this.getStoreRaw(firstDt, lastDt);

	},

	onClickNextDate : function(btn){

		var firstDt=this.lastDt.add(Date.DAY,1);
		var lastDt=Date.parseDate(firstDt.format('m')+'/'+firstDt.getDaysInMonth()+'/'+firstDt.format('Y'),'m/d/Y');
		if (lastDt.subtractDt(firstDt)<14){
			var dt=lastDt.add(Date.DAY,1);
			lastDt=Date.parseDate(dt.format('m')+'/'+dt.getDaysInMonth()+'/'+dt.format('Y'),'m/d/Y');
		}
		this.getStoreRaw(firstDt, lastDt);

	},



    onRender : function(ct, position){
        RL.Vendor.Calendar.superclass.onRender.apply(this, arguments);
		this.getStoreRaw.defer(100, this, []);
    },


	setDates: function(firstDt, lastDt, performChecks){
		this.firstDt=Ext.isDate(firstDt) ? firstDt :Date.parseDate(firstDt,'m/d/Y');
		this.lastDt=Ext.isDate(lastDt) ? lastDt :Date.parseDate(lastDt,'m/d/Y');

		if (performChecks){

			if (this.lastDt.subtractDt(this.firstDt)<14){
				this.firstDt=this.firstDt.add(Date.DAY,-7);
				this.lastDt=this.lastDt.add(Date.DAY,7);
			}

		}

		if (this.el) this.updateToolbarDts();

	},
	checkLoading:function(nowLoading){ //this logic is slightly different from the pricing one...it always repaints the mask window since the mask window does not paint well on a sliding in panel

		var wasLoading;
		if (typeof nowLoading != 'undefined'){
			wasLoading=this.loading;
			this.loading=nowLoading;
		}

		var calendar_parent=this.findBy(function(item){ return item.calendar_parent })[0];
		if (calendar_parent.el) calendar_parent.el.unmask();

		if (this.loading){
			if (calendar_parent.el) calendar_parent.el.mask('Now populating the calendar...', 'x-mask-loading');
			this.checkLoading.defer(300, this, []);
		}
	},

	getStoreRaw: function(firstDt, lastDt, venid, mgtcoid, ventype){

		if (firstDt){
			this.setDates(firstDt,lastDt);
		}
		if (venid) {
			this.venid=venid;
			this.mgtcoid=mgtcoid;
			this.ventype=ventype;
		}

		//if (this.dataTemp){
		//	var dataRemote=Ext.jx.getTable('_VENDOR_INVENTORY').setData('TEST', this.dataTemp);
		//	this.storeRaw=dataRemote.getStore();
		//	this.onStoreReady();
		//	return;
		//}
		this.checkLoading(true);

		var server = Ext.jx.Server.get(), conn = new Ext.data.Connection();

		var params=Ext.jx.Ajax.cleanFieldNamesForPost({
			'VENDOR.VENID':this.venid,
			'VENDOR.MGTCOID':this.mgtcoid || '~~NULL~~',
			'VENDOR.VENTYPE':this.ventype,
			'.DDATE':this.firstDt,
			'.RDATE':this.lastDt
		});
		var actionParams='&'+Ext.jx.Ajax.urlEncode({screen:'js::ext_data_store::_VENDOR_INVENTORY', page_action:params});

		conn.request({
			timeout:90,
			url: server+'?'+actionParams+'&pl='+Ext.jx.getStoreValue('DEPT#DEPTNO'),
			method: 'GET',
			success: function(responseObject) {
				Ext.jx.Server.release(server);
				this.checkLoading(false);
				if (!responseObject.responseObject){
					eval('responseObject.responseObject='+responseObject.responseText);
				}
				var dataRemote=Ext.jx.getTable('_VENDOR_PRICING').setData(actionParams, responseObject.responseObject);
				this.storeRaw=dataRemote.getStore();
				this.onStoreReady();

			},
			failure: function() {
				Ext.jx.Server.release(server);
				this.checkLoading(false);

				calendar_parent.add({
					html:'There was a problem loading the data'
				});

				if (calendar_parent.el){
					calendar_parent.doLayout();
					calendar_parent.el.unmask();
				}
			},
			scope : this
		});
	},

	onStoreReady:function(){

		var commonFields=['_VENDOR_INVENTORY#UNITSAY', '_VENDOR_INVENTORY#PRICECODE', '#LINK_TO_SERVICE', '_VENDOR_INVENTORY#PRICECODE', '_VENDOR_INVENTORY#MGTCOID', '_VENDOR_INVENTORY#VENID'];
		var specificFields=[
			'_VENDOR_INVENTORY#INV_DATE', '_VENDOR_INVENTORY#AUDIT', '_VENDOR_INVENTORY#AUDITDATE', '_VENDOR_INVENTORY#AVAIL', '_VENDOR_INVENTORY#RELDATE', '_VENDOR_INVENTORY#STATUS',
			'_VENDOR_INVENTORY#TOTINV', '_VENDOR_INVENTORY#USED', '_VENDOR_INVENTORY#BLACKOUT', '_VENDOR_INVENTORY#UNITSAY', '_VENDOR_INVENTORY#SELL_PRICE', '_VENDOR_INVENTORY#MINNGTS'
		];

		var newStoreFields=[], newStoreData=[], rowsHash={};
		Ext.each(commonFields, function(fld){
			newStoreFields.push(Ext.apply({},this.storeRaw.fields.map[fld]));
		},this);

		var days=this.lastDt.subtractDt(this.firstDt);
		for (var i=0; i<=days; i++){
			var dateNow=this.firstDt.add('d', i);
			var fldDt='#'+dateNow.format('Y-m-d');
			newStoreFields.push({name:fldDt});

		}

		this.storeRaw.each(function(rec){

			var dtRaw=rec.data['_VENDOR_INVENTORY#INV_DATE'];
			var dt=Date.parseDate(dtRaw,'m/d/Y');

			var rowKey=rec.data['_VENDOR_INVENTORY#VENID']+'&'+rec.data['_VENDOR_INVENTORY#MGTCOID']+'&'+rec.data['_VENDOR_INVENTORY#PRICECODE'];
			var row = rowsHash[rowKey];
			if (!row){
				newStoreData.push(row=rowsHash[rowKey]={rowkey:rowKey});
				Ext.each(commonFields, function(fld){
					row[fld]=rec.data[fld]
				});
			}
			var dtValues={};
			Ext.each(specificFields, function(fld){
				dtValues[fld]=rec.data[fld]
			});

			row['#'+dt.format('Y-m-d')]=dtValues;
		});

		this.store=new Ext.data.JsonStore({
			fields: newStoreFields,
			data: newStoreData
		});

		this.updateGrid();
		return;
	},


	getGridCols: function(invTab){

		if (invTab) this.invTab=invTab;

		var gridCols=[
		//new Ext.grid.RowNumberer(),
		{
			header: "Unit Type",
			width: 120,
			sortable: true,
			dataIndex:'_VENDOR_INVENTORY#UNITSAY',
			//align:'left'
			//,css:'font-weight:bold'
			renderer: function(v, p, r, rowIndex, i, ds){
				return '<div class="unit_type_col">'+v+'</div>';
			}
		}];

		var days=this.lastDt.subtractDt(this.firstDt);
		for (var i=0; i<=days; i++){
			var dateNow=this.firstDt.add('d', i);
			var fldDt='#'+dateNow.format('Y-m-d');
			gridCols.push(Ext.apply({
				//wrong //width: 40, //the width is specified on the customer renderer which is set in getInvTabs
				//header: dateNow.format('d M Y'),
				//header: dateNow.format('j'),
				header: dateNow.format('M j'),
				resizable: false,
				sortable: false,
				menuDisabled: true,
				dataIndex: fldDt
			},this.getInvTabs()[this.invTab]));
		}
		return gridCols;
	},

	getInvTabs:function(){

		if (this.invTabs) return this.invTabs;

		return this.invTabs={
			avail:{
				desc:'Availability Calendar',
				width: 38,
				
				renderer : function(v, metadata, r, rowIndex, i, ds) {
					if (v['_VENDOR_INVENTORY#BLACKOUT'] == '1' || v['_VENDOR_INVENTORY#AVAIL'] == '0') {
						metadata.css = 'inv_calendar_blackout_date'
						return 'n/a'
					}
					
					metadata.css = 'inv_calendar_available_date'
					
					return v['_VENDOR_INVENTORY#AVAIL']
				}
			},
			minNights:{
				desc:'Min Nights Calendar',
				width: 38,
				renderer: function(v, p, r, rowIndex, i, ds){
					return v['_VENDOR_INVENTORY#MINNGTS'];
				}
			}
		}

	},

	updateGrid: function(){

		var calendar_parent=this.findBy(function(item){ return item.calendar_parent })[0];

		calendar_parent.removeRange();

		var grid = new Ext.grid.GridPanel({
			store: this.store,
			columns: this.getGridCols(),
			cls:'inven_cal_grid',
			selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
			//selModel: new Ext.grid.CellSelectionModel(),
			stripeRows: true,
			autoWidth:true,
			frame: true,
			height:'100%'
		});

		calendar_parent.add(grid);
		if (calendar_parent.el) calendar_parent.doLayout();

	}

});
//eof extend

Ext.reg('vendor_calendar', RL.Vendor.Calendar);

Ext.ns('RL.Vendor');


RL.Vendor.Carousel = Ext.extend(Ext.Panel, {
	
	layout: 'carousel',
	baseCls:'x-frameless',
	autoWidth:true,
	height: 200,
	
	layoutConfig: {
		pagedScroll: true,
		loopCount:1,
		scrollButtonPosition:'split',
		marginScrollButtons: 1
	},
	
	vendorRecord : null,
	
	constructor : function (config) {
		var vendorRecord = config.vendorRecord;
		config.items = [];
		var imageBase = Ext.jx.getStoreValue({ tableName : "CONFIG", fieldName : "CONFIG#IMAGEPATH" });
				
		for (var i = 1; i <= 10; i++) {
			var imageName = vendorRecord.data['VENDOR#IMAGE' + i];
			if (!imageName) continue;
			
			config.items.push({
			    style : { margin: '1px 1px 1px 1px'},
                html : {tag: 'img', width : 250, height : 200, src : imageBase + '/fs_' + imageName, style : { width : 250, height : 200 } }
			});
		}
		
		RL.Vendor.Carousel.superclass.constructor.call(this, config);
	}
	
});

Ext.reg('vendor_carousel', RL.Vendor.Carousel);
Ext.ns('RL.Vendor');


RL.Vendor.Content = Ext.extend(Ext.ux.TabPanelSkin, {

	slots 				: true,
	
	tabsBgCls			: 'prodtype_ldg_header',
	tabBtnCls			: 'prodtype_round_button',
	tabsTitleCls		: 'quote_steps_msg',

	active 				: null, //name of initially active tab
	enableTabScroll		: true,
	plain				: true,
	border				: false,
	activeTab			: 0,

	layoutConfig : {
		deferredRender		: true,
		layoutOnCardChange	: true
	},

	vendorRecord 		: null,
	pricingRecord 		: null,
	searchForm			: null,


	constructor : function (config) {

		var vendorRecord 	= config.vendorRecord;
		var searchForm 		= config.searchForm;
		var pricingRecord 	= config.pricingRecord;

		if (!config.items) config.items = []

		if (!vendorRecord.hasPictures){
			Ext.jx.debug('problem with hasPictures');
		} else {

			if (vendorRecord.hasPictures()) config.items.push({
				title : 'Pictures',
				name : 'Pictures',
				layout : 'row-fit',
				sort:-5,

				items : [
					{
						html: vendorRecord.getDesc(),
						autoWidth : true,
						autoHeight : true
					},
					{
						xtype : 'vendor_carousel',
						vendorRecord : vendorRecord,
						height : '100%'
					}
				]
			});


			if (vendorRecord.hasMap()) config.items.push({
				xtype	: 'vendor_map',
				title	: 'Map',
				name	: 'Map',
				sort:-4,
				vendorRecord : vendorRecord
			});


			if (vendorRecord.hasStreetView()) config.items.push({
				xtype	: 'RL.Vendor.StreetView',
				slot	: 'panorama',
				
				title	: 'Street View',
				name	: 'StreetView',
				sort	: -4.5,
				vendorRecord : vendorRecord
			});


			if (vendorRecord.hasCalendar()) config.items.push({
				xtype : 'vendor_calendar',
				title : 'Avail',
				name : 'Calendar',
				gridHeight : this.height - 112,
				sort:-3,
				vendorRecord : vendorRecord,
				pricingRecord : pricingRecord,
				searchForm : searchForm
			})



			var contentMethod=Ext.jx.getStoreValue("CONFIG#CONVENCON");

			if (contentMethod ==1){

				if (vendorRecord.data["VENDOR#SHORT"]) config.items.push({

						title:'About',
						name:'About',
						sort:-2,

						html: vendorRecord.data["VENDOR#SHORT"],

						bodyStyle : 'overflow-y : auto'
				});

			}


			var content=contentMethod ==2 ? ((vendorRecord.data["VENDOR#SHORT"] || '')+(vendorRecord.data["VENDOR#LONG"] || '')) : vendorRecord.data["VENDOR#LONG"];

			if (content) config.items.push({

				title:'More Info',
				name:'More Info',
				sort:-1,
				html: content,

				bodyStyle : 'overflow-y : auto'

			});


			for (var i=1; i<=7; i++){
				if (!vendorRecord.data['VENDOR#CAT'+i+'NAME'] || !vendorRecord.data['VENDOR#CAT'+i+'INFO']){
					continue;
				}

				config.items.push({
					title:vendorRecord.data['VENDOR#CAT'+i+'NAME'],
					name:'VENDOR#CAT'+i+'NAME',
					sort:vendorRecord.data['VENDOR#CAT'+i+'ORDER'],
					hideBorders:true,

					bodyStyle : 'overflow-y : auto',

					items:[{
						xtype: !config.noPanPanels ? 'panpanel' : 'panel',
						html: vendorRecord.data['VENDOR#CAT'+i+'INFO']
					}]
				});
			}


			if (RL.Defaults.DEV_MODE) config.items.push({
				xtype : 'RL.Vendor.Inventory',
				name : 'Inventory',
				vendorRecord : vendorRecord,
				pricingRecord : pricingRecord,
				searchForm : searchForm
			})

		}


		config.items.sort(function(a,b){
			return (a.sort || 0) - (b.sort || 0)
		})

		Ext.each(config.items, function(item, index) {
			if (config.active == item.name) config.activeTab = index;
		});

		this.tabsTitle = vendorRecord.data['VENDOR#VENDOR']

		RL.Vendor.Content.superclass.constructor.call(this, config);
	},


	initComponent : function () {
		RL.Vendor.Content.superclass.initComponent.call(this)

		//allowing at least 2 seconds to load the images on active tab (usually pictures)
		//then render the other tabs
		this.on('afterlayout', this.onAfterLayout, this, { defer : 2000, single : true })
	},
	
	
	afterShow : function () {
		var panorama = this.slots.panorama
		
		if (panorama) panorama.afterShow(this.layout.activeItem == panorama)
	},
	
	
	beforeDismiss : function () {
		var panorama = this.slots.panorama
		
		if (panorama) panorama.beforeDismiss()
	},


	onAfterLayout : function () {
		var layout = this.layout

		if (!layout.deferredRender) return

		layout.deferredRender = false

		this.doLayout()
	}



});
//eof extend

Ext.reg('vendor_content', RL.Vendor.Content);

Ext.ns('RL.Vendor');


RL.Vendor.Map = Ext.extend(Ext.ux.GoogleMapPanel, {

	//vendor record
	vendorRecord : null,

	constructor : function (config) {

		var vendorRecord = config.vendorRecord;

		Ext.apply(config, {
			title:'Map',

			mapType:'terrain',
			renderedSafe:true,

			controls:['zoom','menumaptype','scale'],
			zoom:14,

			border: false,

			markers: [{
				address: vendorRecord.getAddress(),
				icon:'building',
				title:vendorRecord.get('VENDOR#VENDOR'),
				html:vendorRecord.template('longdescription'),
				maxWidth:300
			}]
		});
		//eof apply

		RL.Vendor.Map.superclass.constructor.call(this, config);
	}

});
//eof extend

Ext.reg('vendor_map', RL.Vendor.Map);


//Ext.ns('RL.Vendor');
//
//
//RL.Vendor.Map = Ext.extend(Ext.Panel, {
//
//	//vendor record
//	vendorRecord 			: null,
//
//	
//	constructor : function (config) {
//
//		var vendorRecord = config.vendorRecord;
//
//		Ext.apply(config, {
//			title		: 'Map',
//			
//			//when rendered into hidden DOM element this prevents the map from actual rendering
//			layout 		: 'fit',
//			
//			hideBorders : true,
//			
//			items : [
//				{
//					xtype 		: 'gmappanel',
//					minGeoAccuracy	: 1,
//					zoomLevel 	: 14,
//					
////					gmapType	: 'G_PHYSICAL_MAP',
//		
//					mapControls	: [ 'GSmallZoomControl', 'GMenuMapTypeControl', 'GScaleControl'],
//					
//					setCenter	: {
//						geoCodeAddr : vendorRecord.getAddress()
//					}
//				}
//			]
//
//			
////			,
////
////			markers: [{
////				address: vendorRecord.getAddress(),
////				icon:'building',
////				title:vendorRecord.get('VENDOR#VENDOR'),
////				html:vendorRecord.template('longdescription'),
////				maxWidth:300
////			}]
//		});
//		//eof apply
//
//		RL.Vendor.Map.superclass.constructor.call(this, config);
//	}
//
//});
////eof extend
//
//Ext.reg('vendor_map', RL.Vendor.Map);

Ext.ns('RL.Destination');


RL.Destination.Carousel = Ext.extend(Ext.Panel, {
	
	layout: 'carousel',
	baseCls:'x-frameless',
	autoWidth:true, 
	height: 200,
	
	layoutConfig: {
		pagedScroll: true,
		loopCount:1,
		scrollButtonPosition:'split',
		marginScrollButtons: 1
	},
	
	destRecord : null, 
	
	constructor : function (config) {
		var destRecord = config.destRecord;
		config.items = [];
		var imageBase = Ext.jx.getStoreValue({ tableName : "CONFIG", fieldName : "CONFIG#IMAGEPATH" });
				
		for (var i = 1; i <= 10; i++) {
			var imageName = destRecord.data['RESORT#IMAGE' + i];
			if (!imageName) continue;
			
			config.items.push({
			    style : { margin: '1px 1px 1px 1px'},
                html : {tag: 'img', width : 250, height : 200, src : imageBase + '/fs_' + imageName, style : { width : 250, height : 200 } }
			});
		}
		
		RL.Destination.Carousel.superclass.constructor.call(this, config);
	}
	
});

Ext.reg('dest_carousel', RL.Destination.Carousel);
Ext.ns('RL.Destination');


RL.Destination.Content = Ext.extend(Ext.ux.TabPanelSkin, {

	tabsBgCls:'prodtype_ldg_header',
	tabBtnCls:'prodtype_round_button',
	tabsTitleCls:'quote_steps_msg',

	active : null, //name of initially active tab
	enableTabScroll: true,
	plain:true,
	border:false,
	activeTab: 0,

	layoutConfig : {
		deferredRender: true,
		layoutOnCardChange:true
	},

	destRecord : null,
	
	autoHeight : true,


	constructor : function (config) {
		if (!config.items) config.items = [];

		var destRecord = config.destRecord;
		
		var isAutoHeight = config.autoHeight != null ? config.autoHeight : this.autoHeight

		if (!destRecord.hasPictures) {
			Ext.jx.debug('problem with hasPictures');
		} else {

			if (destRecord.hasPictures()) config.items.push({
				title:'Pictures',
				name:'Pictures',
				sort:-3,
				
				autoHeight : true,

				items:[
					{
						html: destRecord.getDesc(),
						autoWidth : true,
						autoHeight : true
					},
					{
						xtype : 'dest_carousel',
						destRecord : destRecord
					}
				]
			});

			var contentMethod=Ext.jx.getStoreValue("CONFIG#CONDESTCON");

			if (contentMethod == 1)
				if (destRecord.data["RESORT#MULTIPLE"]) config.items.push({

					title : 'About',
					name : 'About',
					sort : -2,

					html : destRecord.data["RESORT#MULTIPLE"],
					
					autoHeight : isAutoHeight,
				
					bodyStyle : 'overflow-y : auto'
				})

				
			var content = contentMethod == 2 ? ((destRecord.data["RESORT#MULTIPLE"] || '') + (destRecord.data["RESORT#SINGLE"] || '')) : destRecord.data["RESORT#SINGLE"];
			
			if (content) config.items.push({
				title : 'More Info',
				name : 'More Info',
				sort : -1,
				
				html : content,
				
				autoHeight : isAutoHeight,
				bodyStyle : 'overflow-y : auto'
			})


			for (var i = 1; i <= 7; i++) {
				if (!destRecord.data['RESORT#CAT'+i+'NAME'] || !destRecord.data['RESORT#CAT'+i+'INFO']) continue

				config.items.push({
					title : destRecord.data['RESORT#CAT'+i+'NAME'],
					name  : 'RESORT#CAT'+i+'NAME',
					
					sort : destRecord.data['RESORT#CAT'+i+'ORDER'],
					
					hideBorders:true,
				
					autoHeight : isAutoHeight,
					bodyStyle : 'overflow-y : auto',
					
					items:[{
						xtype: !config.noPanPanels ? 'panpanel' : 'panel',
						html: destRecord.data['RESORT#CAT'+i+'INFO']
					}]
				});
			}

			if (Ext.jx.getStoreValue("CONFIG#IREURL")) config.items.push({
				xtype : 'RL.Destination.HotDeals',
				
				title : 'Hot Deals',
				name  : 'Specials',
				
				autoHeight : isAutoHeight,
				
				destRecord : destRecord
			})



			//if (destRecord.hasMap()) config.items.push({
			//	xtype:'dest_map',
			//	title:'Map',
			//	name:'Map',
			//
			//	destRecord : destRecord
			//});

		}

		config.items.sort(function(a,b){
			return (a.sort || 0) - (b.sort || 0)
		})

		this.tabsTitle=destRecord.data['RESORT#RESORT'];

		Ext.each(config.items, function(item, index) {
			if (config.active == item.name) config.activeTab = index;
		});

		RL.Destination.Content.superclass.constructor.call(this, config);
	},
	
	
	initComponent : function () {
		RL.Destination.Content.superclass.initComponent.call(this)
		
		//allowing at least 2 seconds to load the images on active tab (usually pictures)
		//then render the other tabs
		this.on('afterlayout', this.onAfterLayout, this, { defer : 2000, single : true })
	},
	
	
	onAfterLayout : function () {
		var layout = this.layout
		
		if (!layout.deferredRender) return
		
		layout.deferredRender = false
		
		this.doLayout()
	}
	

});
//eof extend

Ext.reg('dest_content', RL.Destination.Content);

Ext.ns('RL.Destination');


RL.Destination.Map = Ext.extend(Ext.ux.GoogleMapPanel, {

	//dest record
	destRecord : null,
	
	constructor : function (config) {
		
		var destRecord = config.destRecord;
		
		Ext.apply(config, {
			title:'map',
			
			mapType:'terrain',
			renderedSafe:true,
			
			controls:['zoom','menumaptype','scale'],
			zoom:14,
			
			border: false,
			
			markers: [{
				address: destRecord.getAddress(),
				icon:'building',
				title:destRecord.get('RESORT#RESORT'),
				html:destRecord.template('longdescription'),
				maxWidth:300
			}]
		});
		//eof apply
		
		RL.Destination.Map.superclass.constructor.call(this, config);
	}
	
}); 
//eof extend

Ext.reg('dest_map', RL.Destination.Map);
Ext.ns('RL');


RL.PriceSearch = Ext.extend(Ext.Panel, {

	style : {
		padding:'0px !important',
		margin:'0px !important'
	},

	//style : 'overflow-y:auto;overflow-x:hidden;',

	height : 562,
	layout : "border",
	baseCls: 'x-frameless',
	hideBorders: true,


	waitLoop			: 200,
	allowPrefetch		: true,
	slots 				: true,
	lastSearchParams 	: null,

	recordProduct		: null,
	wizard				: null,


	constructor : function(config) {

		config = config || {};

		var centerCfg = config.centerCfg || {};
		delete config.centerCfg;

		var blankHtml=config.recordProduct ? config.recordProduct.data['SERVICE#CONBLANK'] : config.recordProdGroup.data['PRODGRP#CONBLANK'];

		Ext.applyIf(centerCfg, {
//			PriceSearchCenter:true,
			region : "center",
			slot : 'tabCenter',

			layout : "fit", //this is needed to keep the search results grid at 100%

			baseCls : 'x-frameless',
			hideBorders: true,
			html: blankHtml
		});


		var searchCfg = config.searchCfg || {};
		delete config.searchCfg;

		var helpHtml=config.recordProduct ? config.recordProduct.data['SERVICE#CONHELP'] : config.recordProdGroup.data['PRODGRP#CONHELP'];

		var westCfg={
			region : "west",
			slot : 'tabWest',
			baseCls: 'x-bubble', //buttons below don't work with baseCls: 'x-bubble'
			frame: true,
			bodyStyle : {
				'overflow-y':'auto',
				'overflow-x':'hidden'
			},
			width:200,
			items:[
				Ext.applyIf(searchCfg, {
					//style : 'overflow-y:auto;overflow-x:hidden;',
					PriceSearchLeft : true,
					slot : 'options',
					baseCls: 'x-frameless',
					//baseCls: 'x-bubble',
					//frame: true,
					//hideBorders: true, //this was removing the borders of a child frameset

					html: helpHtml,
					bodyStyle : {
						'padding-left':'10px'
					}

				})
			]
		};

		var westButtons=[{
			xtype:'button',
			slot:'newQuoteBtn',
			text: 'search',
			iconCls: 'search-btn',
			scale: 'medium',
			//scale: 'small',
			iconAlign: 'left',
			handler : this.onSearch,
			scope : this
		},{
			xtype:'button',
			text: 'skip',
			iconCls: 'skip-btn',
			scale: 'medium',
			//scale: 'small',
			iconAlign: 'left',
			handler : this.onSkipClick,
			scope : this,
			hidden:config.recordProduct && !config.recordProduct.allowSkip()

		}];

		var buttonDisplay=searchCfg.buttonDisplay;

		if (!buttonDisplay || buttonDisplay=='buttons_attached'){

			westCfg.items[0].items.push({
				xtype: "buttongroup",
				columns: 2,
				autoWidth:true,
				baseCls: 'x-frameless',
				items:westButtons
			});

		}else if (buttonDisplay=='toolbar_attached'){

			westCfg.items[0].bbar=westButtons;

		}else if (buttonDisplay=='toolbar_below'  || (westCfg.baseCls=='x-bubble' && buttonDisplay=='buttons_below')){

			westCfg.bbar=westButtons;

		}else if (buttonDisplay=='buttons_below'){  //buttons below don't work with baseCls: 'x-bubble'

            westCfg.buttonAlign='center';
			westCfg.buttons=westButtons;
		}

		Ext.apply(config, {

			items : [
				westCfg,
				centerCfg
			]
		});//eof apply

		RL.PriceSearch.superclass.constructor.call(this, config);
	},//eof constructor


	initComponent : function(){
		RL.PriceSearch.superclass.initComponent.call(this);

		this.on('activate', this.onActivate, this);
	},


	onActivate : function() {
		this.updateFields();
		this.priceIt();
 	},


	getSearchValues:function(){

		var wizardValues 	= this.useTripDates ? RL.Global.getTripStartValues() : RL.Global.getSegmentStartValues(this)
		var values			= this.getValues()


		if (!values['VENDOR#REGION']) values['VENDOR#REGION']=wizardValues.dest;

		if (this.recordProduct){
			values['VENDOR#VENTYPE']=this.recordProduct.data['SERVICE#CODE'];

			if (this.recordProduct.get('#B_DONT_SHOW_DATES_ON_SEARCH')!=1){
				if (!values['#DDATE'] && wizardValues.startDate){
					var startPlus=Number(this.recordProduct.get('SERVICE#DDATEPLUS'));
					if (isNaN(startPlus)) startPlus=0;
					values['#DDATE']=wizardValues.startDate.add('d', startPlus);
				}
				if (!values['#RDATE'] && wizardValues.endDate){

					var endMinus=Number(this.recordProduct.get('SERVICE#RDATEMINUS'));
					if (isNaN(endMinus)) endMinus=0;
					values['#RDATE']=wizardValues.endDate.add('d', -1 * endMinus);
				}
			}

			if ( this.recordProduct.isGDSAir() ){
				if (!values['#FROM_AIRPORT'] && wizardValues.fromAirport) values['#FROM_AIRPORT']=wizardValues.fromAirport;
				if (!values['#TO_AIRPORT'] && wizardValues.toAirport) values['#TO_AIRPORT']=wizardValues.toAirport;
				if (!values['#NUM_SEATS'] && (wizardValues.adults || wizardValues.children) ) values['#NUM_SEATS']=wizardValues.adults + wizardValues.children;
			}


		}else if (this.recordProdGroup){

			values['#VENTYPES']='';
			this.recordProdGroup.getProducts().each(function(recordProduct){
				if (values['#VENTYPES']!=''){
					values['#VENTYPES']+=',';
				}
				values['#VENTYPES']+=recordProduct.data['SERVICE#CODE'];
			});

			if (!values['#DDATE']) values['#DDATE']=wizardValues.startDate;
			if (!values['#RDATE']) values['#RDATE']=wizardValues.endDate;

		}

		return values;
	},

	updateFields:function(){
		this.setValuesIf( this.getSearchValues() );
		//this.setValues( this.getSearchValues() );
	},

	onChangeField: function (field){
		//this.slots.searchBtn.markInvalid(); //toolbar button invalid only works on ff
	},


	onSkipClick : function(){
		RL.Global.getWizard(this).onNextStep();
	},


	onSearch : function(){
		this.priceIt();
	},


	checkLoading : function (nowLoading) {

		if (typeof nowLoading != 'undefined') this.loading = nowLoading

		var tabCenter = this.slots.tabCenter
		if (tabCenter.el && !this.loading) tabCenter.el.unmask()

		if (this.loading) {
			if (tabCenter.el && !Ext.Element.data(tabCenter.el.dom, 'mask')) tabCenter.el.mask('Now loading results...', 'x-mask-pricing')
			this.checkLoading.defer(this.waitLoop, this, [])
		}
	},


	onStoreSuccess : function (store) {
		this.checkLoading(false)

		var tabCenter = this.slots.tabCenter

		tabCenter.removeRange()
		tabCenter.add(this.getStoreSuccess.call(this, store))

		if (tabCenter.el) {
			tabCenter.doLayout()
			tabCenter.body.unmask()
		}
	},


	onStoreError : function (error, canRetry) {
		this.checkLoading(false)

		var btns = [
			{
				buttonText : '<b>change search</b>'
			}
		]

		var me = this

		if (!this.recordProduct || this.recordProduct.allowSkip()) btns.push({
			buttonText : '<b>skip</b>',

			fn : function () {
				me.onSkipClick()
			}
		})


		Ext.customAlert({
			title	: 'Pricing Error',
			msg		: error,
			icon	: Ext.MessageBox.ERROR,
			btns	: btns
		});


		var tabCenter = this.slots.tabCenter

		tabCenter.removeRange()
		tabCenter.add(this.getStoreError(error))

		if (tabCenter.el) {
			tabCenter.doLayout()
			tabCenter.body.unmask()
		}
	},


	getStoreError : function(error) {
		return {
			html:['<div class="prodtype_transp_footer">',
					'<div class="prodtype_transp_outer3">',
						'<div class="prodtype_transp_leftcol3b">',error,'</div>',
					'</div>',
				'</div>'
			].join('')
		}
	},


	getStoreSuccess : function (store){
		return new RL.PriceResult.Service({
			searchForm : this,
			store : store
		});
	},


	priceIt : function( prefetchOnly ){
		this.storePriceIt( prefetchOnly );
	},


	storePriceIt : function ( prefetchOnly ){
		if (prefetchOnly && !this.allowPrefetch) return;

		var record = this.recordProdGroup || this.recordProduct;
		var gtawRecord = Ext.jx.getStore('GTAW').getAt(0);

		if (!Ext.jx.vendors) Ext.jx.vendors={};

		var values=this.getSearchValues();

		if (this.recordProduct){
			if (this.recordProduct.get('#B_DONT_SHOW_DATES_ON_SEARCH') != 1 && !values['#DDATE']) return;
			if (this.recordProduct.isGDSAir() && (!values['#FROM_AIRPORT'] || !values['#TO_AIRPORT'] || !values['#NUM_SEATS'])) return;
		}else if (this.recordProdGroup){
			if (this.recordProdGroup.get('#B_DONT_SHOW_DATES_ON_SEARCH') != 1 && !values['#DDATE']) return;
		}else{
			if (!values['#DDATE']) return;
		}


		if (!prefetchOnly) gtawRecord.checkDatesSearch(record, values['#DDATE'], values['#RDATE'], values['VENDOR#REGION'] );


		var params = Ext.jx.Ajax.cleanFieldNamesForPost(values);
		
		var user = RL.Global.user
		
		if (user && user.authenticated) Ext.apply(params, {
			consumer_email 		: user.username,
			consumer_password 	: user.password
		})
		
		var actionParams = '&' + Ext.jx.Ajax.urlEncode({ 
			screen 		: 'js::ext_data_store::_VENDOR_PRICING', 
			page_action : params
		})

		
		if (this.lastSearchParams == actionParams) return; //this keeps double grid refresh from happening


		if (RL.Global.downloadedPricingStores[actionParams]){
			
			var store=RL.Global.downloadedPricingStores[actionParams];
			if (!store.getCount()) {
				this.onStoreError('Could not find any items that match your criteria.', false);
			}else{
				this.onStoreSuccess(store);
			}
			return;
		}




		this.checkLoading(true);

		var server = Ext.jx.Server.get();
		new Ext.data.Connection().request({
			timeout:90,
			url: server+'?'+actionParams+'&pl='+Ext.jx.getStoreValue('DEPT#DEPTNO')+'&currency='+Ext.jx.getStoreValue('GTAW#CADCURR'),
			method: 'GET',
			success: function(responseObject) {
				
				if (this.lastSearchParams == actionParams) return; //this keeps double grid refresh from happening

				Ext.jx.Server.release(server);
				if (!responseObject.responseObject){
					eval('responseObject.responseObject='+responseObject.responseText);
				}
				var dataRemote=Ext.jx.getTable('_VENDOR_PRICING').setData(actionParams, responseObject.responseObject);
				var store=dataRemote.getStore(undefined, undefined, ExtX.Data.Store.Paged);

				RL.Global.downloadedPricingStores[actionParams]=store;

				var priceField=store.fields.map['#SELL_PRICE'];
				if (priceField) priceField.sortType=Ext.data.SortTypes.asInt; //dirty hack: it would be much better to do a convert


				if (!prefetchOnly){

					if (!store.getCount()) {
						this.onStoreError('Could not find any items that match your criteria.', false);
					}else{
						this.lastSearchParams = actionParams;
						
						this.onStoreSuccess(store);
					}
				} else
					//not sure whether this is needed, but I experienced a bug, which seems was related to
					//call to 'checkLoading' on already removed component
					this.onStoreSuccess(store);
			},

			failure: function() {
				Ext.jx.Server.release(server);
				delete this.lastSearchParams;
				this.onStoreError('There was an unknown problem which caused the servers to time out.', true);
			},
			scope : this
		});
	},


	canSuggestMoreItems : function () {
		if (this.recordProdGroup)
			return !this.recordProdGroup.get('PRODGRP#EXCLUSIVE') 
		else 
			if (this.recordProduct)
				if (this.recordProduct.isPerPerson() && !this.recordProduct.isGDSAir())
					return true
				else
					return false
	},
	
	
	
	getServiceItemDescription : function () {
		if (this.recordProdGroup)
			return this.recordProdGroup.get('PRODGRP#PGDESC')
		else 
			if (this.recordProduct) return this.recordProduct.get('SERVICE#DESCRIP')
	}

});

Ext.ns('RL.PriceSearch');


RL.PriceSearch.Service = Ext.extend(RL.PriceSearch, {


	//SERVICE#* record?
	recordProduct 		: null,


	constructor : function(config){
		config = config || {};

		Ext.apply(config, {

		    //search options
		    searchCfg : {
		        //layout:"template",
		        layout:"form",
				labelAlign:'top',

				style:{padding:'0px !important', margin:'0px !important', border:'0px'},
				//isOptional:true,

				autoHeight:true,
//			    height:350,

		        items:[{
					xtype : 'search_top_toolbar',
					form : this
				},{

					xtype:'daterange',
					startDateFieldName: '#DDATE',
					endDateFieldName: '#RDATE',
					labelAlign:'top',
					startDateField:{
						listeners: {
							change: this.onChangeField,
							scope: this
						}
					},
					endDateField:{
						listeners: {
							change: this.onChangeField,
							scope: this
						}
					}
				}]

		    }

		}); //eof apply

		if (RL.Defaults.DEV_MODE)
			if (config.recordProduct.get('SERVICE#CONFILTERS')==1){
				//config.buttonDisplay='toolbar_below';
				config.buttonDisplay='buttons_below';

				config.searchCfg.items.push({
					//layout:'triggerform',
					//labelAlign:'top',
					slot:'vendor_filters',
					xtype:'vendorfilters'
				});
			}


		RL.PriceSearch.Service.superclass.constructor.call(this, config);
	},//eof constructor


	initComponent : function(){
		RL.PriceSearch.Service.superclass.initComponent.call(this);

		var recordProduct = this.recordProduct;

		//setting up search options fields
		var searchOp = this.slots.options;

		Ext.jx.Misc.updateItemLabel(searchOp, '#VENDOR_SEARCH', recordProduct, 'SERVICE#VENDORLAB');
		Ext.jx.Misc.updateItemLabel(searchOp, '#DDATE', recordProduct, 'SERVICE#DSTARTLAB');
		Ext.jx.Misc.updateItemLabel(searchOp, '#RDATE', recordProduct, 'SERVICE#DENDLAB');

	},


	priceIt : function ( prefetchOnly ) {

		if (RL.Global.productSupports(this.recordProduct,'golf')) {

			var values=this.getSearchValues();
			if (!values['#DDATE'] || !values['#RDATE']) return; //missing dates

			if (!this.golfPlanner) {
				this.golfPlanner=new RL.PriceResult.GolfPlanner({searchForm : this, ownerCt: this});

				var tabCenter = this.slots.tabCenter;

				tabCenter.add(this.golfPlanner);
				if (tabCenter.el) tabCenter.doLayout()
			} else
				this.golfPlanner.printGolfPlanner();

		} else
			this.storePriceIt( prefetchOnly )
	}



});

Ext.ns('RL.PriceSearch');


RL.PriceSearch.Air = Ext.extend(RL.PriceSearch, {

	allowPrefetch: false,
	
	constructor : function(config){
		config = config || {};
		
		Ext.apply(config, {
			//noValidate:true,
		    //search options
		    searchCfg : {
				
				//buttonDisplay:'toolbar_below',
				buttonDisplay:'buttons_below',
				
		        //layout:"template",
		        layout:"form",
				labelAlign:'top',
				
				autoHeight:true,
//			    height:350,
			    
		        items:[{
					xtype : 'search_top_toolbar',
					form : this
				},{
					xtype : "airport",
					allowBlank : false,										
					name:"#FROM_AIRPORT",
					emptyText:'Outgoing airport',
					fieldLabel : "Leaving from",
					width:180					
			    },{

					xtype : "airport",
					allowBlank : false,										
					name:"#TO_AIRPORT",
					emptyText:'Destination airport',
					fieldLabel : "Going to",
					width:180					
				},{

					xtype: 'perperson_selector',
					fieldLabel:"No. Seats",
					dataControlField:'#NUM_SEATS',
					name:"#NUM_SEATS",
					allowBlank:false

				},{	
					
					xtype:"form",
					layout:'column',
					baseCls:'x-frameless',
					labelAlign:'top',
					fieldLabel:"Outbound flight",
					
					items:[{
						xtype:'daterange_start'
			//        },{
			//            xtype:"combo",
			//	        fieldLabel:"Time",
			//			dataControlField:'#FLIGHT_START_TIME',
			//			emptyText:'Any',
			//			width: 85,
			//			triggerAction:'all',
			//            name:"#FLIGHT_START_TIME",
			//            store:[[0,'Anytime'],[1,'Afternoon']],
			//            listeners:{
			//            	render:function (comp) {
			//            		Ext.jx.Misc.WebKitLateTriggerRender.defer(1, comp);
			//				}
			//			}
							
						
					}]
				},{
					xtype:"form",
					layout:'column',
					baseCls:'x-frameless',
					labelAlign:'top',
					fieldLabel:"Return flight",
					items:[{						
						xtype:'daterange_end'

			//       	},{
			//            xtype:"combo",
			//	        fieldLabel:"Time",
			//			dataControlField:'#FLIGHT_END_TIME',
			//			emptyText:'Any',
			//			triggerAction:'all',
			//			width: 85,
			//            name:"#FLIGHT_END_TIME",
			//            store:[[0,'Anytime'],[1,'Afternoon']],
			//            listeners:{
			//            	render:function (comp) {
			//            		Ext.jx.Misc.WebKitLateTriggerRender.defer(1, comp);
			//				}
			//			}

						
						
						
					}]
				//},{
				//
				//    fieldLabel:"&nbsp;",
				//    labelSeparator:"&nbsp;",					
				//	xtype:"fieldset",
				//	title: 'Options',
				//	collapsible: true,
				//	collapsed:false,
				//	labelAlign:'top',
				//	width: 140,
				//	
				//	//hideBorder:false,
				//	border:true,
				//
				//	items:[{
				//	
				//		xtype:"combo",
				//		fieldLabel:"Service Class",
				//		dataControlField:'#SERVICE_CLASS',
				//		emptyText:'Optional',
				//		triggerAction:'all',
				//		name:"#SERVICE_CLASS",
				//		width: 100,
				//		store:[['F','First Class'],['C','Business']],
				//		listeners:{
				//			render:function (comp) {
				//				Ext.jx.Misc.WebKitLateTriggerRender.defer(1, comp);
				//			}
				//		}
				//
				//
				//	},{
				//		xtype:"combo",
				//		fieldLabel:"Airline Filter",
				//		dataControlField:'#AIRLINE_FILTER',
				//		emptyText:'Optional',
				//		triggerAction:'all',
				//		name:"#AIRLINE_FILTER",
				//		width: 100,
				//		store:[['UA','United'],['NW','Northwest']],
				//		listeners:{
				//			render:function (comp) {
				//				Ext.jx.Misc.WebKitLateTriggerRender.defer(1, comp);
				//			}
				//		}
				//	}]
				//	
				}]
		    	
		    }
		    //eof search options
			
		}); //eof apply
		
		RL.PriceSearch.Air.superclass.constructor.call(this, config);
	},//eof constructor
	
	
	initComponent : function(){
		RL.PriceSearch.Air.superclass.initComponent.call(this);
		
		var recordProduct = this.recordProduct;

		//setting up search options fields labels
		var searchOp = this.slots.options;
		
		Ext.jx.Misc.updateItemLabel(searchOp, '#DDATE', recordProduct, 'SERVICE#DSTARTLAB');
		Ext.jx.Misc.updateItemLabel(searchOp, '#RDATE', recordProduct, 'SERVICE#DENDLAB');
		Ext.jx.Misc.updateItemLabel(searchOp, '#NUM_SEATS', recordProduct, 'SERVICE#QTYLAB');
		Ext.jx.Misc.updateItemLabel(searchOp, '#FROM_AIRPORT', recordProduct, 'SERVICE#AIRDEPLAB');
		Ext.jx.Misc.updateItemLabel(searchOp, '#TO_AIRPORT', recordProduct, 'SERVICE#AIRRETLAB');
		Ext.jx.Misc.updateItemLabel(searchOp, '#FLIGHT_START_TIME', recordProduct, 'SERVICE#STIMELAB');
		Ext.jx.Misc.updateItemLabel(searchOp, '#FLIGHT_END_TIME', recordProduct, 'SERVICE#ETIMELAB');

		this.slots.tabWest.setWidth(240);		

	},
	
	
		
	getStoreSuccess : function (store) {
		return new RL.PriceResult.Air({
			searchForm : this,
			store : store
		});
	}
	
	
});
Ext.ns('RL.PriceSearch');


RL.PriceSearch.ProductGroup = Ext.extend(RL.PriceSearch, {
	
	constructor : function(config) {
		config = config || {};
		
		Ext.apply(config, {
			
		    //searchCfg
		    searchCfg : {
		        //layout:"template",
				//isOptional:true,
		        layout:"form",
				labelAlign:'top',				
			    autoHeight:true,
				style:{padding:'0px !important', margin:'0px !important', border:'0px'},
			    //height:150,
		        items:[{					
					xtype : 'search_top_toolbar',
					form : this
				},{
					
					xtype:'daterange',
					startDateFieldName: '#DDATE',
					endDateFieldName: '#RDATE',
					labelAlign:'top',
					startDateField:{
						listeners: {
							change: this.onChangeField,
							scope: this
						}
					},
					endDateField:{
						listeners: {
							change: this.onChangeField,
							scope: this
						}
					}
		        }]
					    	
		    }
		    //eof searchCfg
			
		});//eof apply
		
		RL.PriceSearch.ProductGroup.superclass.constructor.call(this, config);
		
	},//eof constructor
			
	getStoreSuccess: function(store) {
		
//		store.sort('BUILD#TYPE');
//		store.groupBy('BUILD#TYPE');
//		//store.sort('VENDOR#VENDOR');
//		store.groupBy('VENDOR#VENDOR');

		return new RL.PriceResult.ProductGroup({
			searchForm : this,
			store : store
		})		
		
	}
		
	
});

Ext.ns('RL.PriceResult');


RL.PriceResult.Service = Ext.extend(Ext.Panel, {

	slots : true,
	baseCls: 'x-bubble',
	frame: true,

	layout : 'row-fit',
	//layout : 'vbox',
	autoWidth:true,

	unitLabel: 'Item',
	vendorLabel: 'Vendor',

	//searchForm to which this result is attached
	searchForm 		: null,

	showPrices		: null,


	constructor : function (config) {
		config = config || {};

		var searchForm = config.searchForm;

		if (searchForm.recordProduct) {

			var recordProduct = searchForm.recordProduct;
			if (recordProduct.get('SERVICE#UNITLAB')) 	config.unitLabel = recordProduct.get('SERVICE#UNITLAB');
			if (recordProduct.get('SERVICE#VENDORLAB')) config.vendorLabel = recordProduct.get('SERVICE#VENDORLAB');

			var rowActions = this.rowActions = new RL.PriceResult.PricingRowActions({
				searchForm : searchForm,
				resultForm : this
			});

			Ext.namespace('Ext.jx.temp');
			Ext.jx.temp.rowActions = rowActions;

			var actionCol;
			var configAddToolBar;

			if ( RL.Defaults.USE_DDOWN_QTY_ADD_LOGIC_WHEN_CAN && recordProduct.isPerPerson()) {
				actionCol = Ext.jx.Misc.getSimpleQtyActionCol()

				configAddToolBar = new RL.PriceResult.CombinedToolBar({
					form 		: searchForm,
					gtawRecord 	: searchForm.gtawRecord,
					priceResult : this,

					slot		: 'toolbar'
				})
			} else {
				actionCol = Ext.apply({ width:50, header:'Add Item', id:1 }, rowActions.get('add-to-cart'));

				configAddToolBar = {
					xtype 		: 'results_top_toolbar',
					slot		: 'toolbar',

					form 		: searchForm,
					height		: 20
				}
			}

			var colDef=[
				//{header: "Location", width: 120, dataIndex: 'LOCATION#NAME', sortable: true},
				actionCol,
				{ header: config.vendorLabel, width: 120, dataIndex: 'VENDOR#VENDOR', sortable: true, id : 2, hidden : true },
				//{ header: 'VENDOR#PREFERRED', width: 120, dataIndex: 'VENDOR#PREFERRED', sortable: true, id : 100},
				//{ header: 'VENDOR#SEARCHCODE', width: 120, dataIndex: 'VENDOR#SEARCHCODE', sortable: true, id : 100},
				{ header: 'Location', width: 120, dataIndex: 'LOCATION#NAME', sortable: true, id : 101, hidden : true },
				{ header: 'Discount', width: 120, dataIndex: '#DISCOUNT', sortable: true, id : 102, hidden : true }
			];

			colDef.push({
				header: config.unitLabel,
				width: 180,
				dataIndex: '#UNIT_DESC',
				sortable: true,
				renderer: this.unitTypeRenderer,
				scope: this,
				id:3
			});


			var conPriceOv = recordProduct.get('SERVICE#CONPRICEOV')
			var conPrices  = Ext.jx.getStoreValue("DEPT#CONPRICES")

			this.showPrices = conPriceOv == 1 || (conPriceOv != 2 && (conPrices == 3 || conPrices == 2)) //the product type website show toggle must be on


			if (this.showPrices) colDef.push({
				header		: "Price in <b>"+Ext.jx.getStoreValue('GTAW#CADCURR')+"</b>",
				width		: 115,
				dataIndex	: '#SELL_PRICE',
				sortable	: true,
				renderer	: this.priceRenderer,
				scope		: this,
				id			: 4
			})

			var cm = new Ext.grid.ColumnModel(colDef);

			Ext.apply(config, {

				layout : 'row-fit',

				items : [
					configAddToolBar,

					{
						xtype  	: 'grid',
						slot    : 'grid',

						autoWidth : true,
						height : '100%',

						hideHeaders: true,
						plugins : [ rowActions ],

						store : config.store,

						view : new Ext.ux.MultiGroupingView({
							enableNoGroups		: false, // REQUIRED!
//							hideGroupedColumn	: true,
							displayEmptyFields	: true,
							forceFit			: true,
							groupTextTpl		: '{text} : {gvalue} ({[values.rs.length]} {[values.rs.length == 1 ? "Record" : "Records"]})'
						}),

						cm: cm
					},

					{
						xtype : 'container',
						slot : 'pagingContainer',

						height : 24,

						layout : 'column',
						hideBorders : true,

						items : [
							{
								columnWidth : 0.5,
								html : '&nbsp;'
							},
							{
								xtype : 'ExtX.Toolbar.Paging',
								slot : 'paging',

								width : Ext.isChrome ? 210 : 200,

								pageSize : 20,

								store : config.store,

								paramNames : {
	                                start : 'from'
	                            }
							},
							{
								columnWidth : 0.5,
								html : '&nbsp;'
							}
						]
					}
				]
			})
			//eof apply
		}

		RL.PriceResult.Service.superclass.constructor.call(this, config);
	},
	//eof constructor


	initComponent : function(){
		RL.PriceResult.Service.superclass.initComponent.call(this);

		this.addEvents('bodyresize-buffered')
		this.on('bodyresize-buffered', this.onBodyResizeBuffered, this, { buffer : 200 });


		//store preparations
		var store = this.store;

		store.pageSize = 20

		var multiProto = Ext.ux.MultiGroupingStore.prototype

		
		for (var prop in multiProto) if (!store.hasOwnProperty(prop) && multiProto.hasOwnProperty(prop)) store[prop] = multiProto[prop]


		store.groupFieldClasses = {
			'VENDOR#VENDOR' : 'x-grid-group-hd-vendor',
			'#RANDOM_VENDOR' : 'x-grid-group-hd-vendor',
			'LOCATION#NAME' : 'x-grid-group-hd-headerless'
		}

		store.groupFieldTemplates = {
			'LOCATION#NAME' : '{[' +
				'function () {' +
					'var record = values.rs[0];' +
					'return record.get("LOCATION#NAME") || "No location";' +
				'}()' +
			']}'
		};

		store.groupFieldTemplates['VENDOR#VENDOR']=store.groupFieldTemplates['#RANDOM_VENDOR']='{['+
			'function (){'+
				'var record=values.rs[0];'+
				'var recordVendor=record.getVendor();'+
				'return recordVendor ? recordVendor.getShortDesc() : record.get("VENDOR#VENDOR");'+
			'}()'+
		']}';


		//toolbar preparations
		var toolbar = this.slots.toolbar

		if (toolbar) {

			var sortingOptions = this.prepareSortingOptions()

			toolbar.add(
				'->',
				{
					xtype 	: 'toolbar',
					items:[{
						xtype 	: 'tbtext',
						text: 'Sort by'
					},
					{
						xtype 	: 'combo',
						slot 	: 'sortCombo',	//will be added to our slots since toolbar have no slot collectors enabled

						mode 	: 'local',
						triggerAction : 'all',
						editable : false,

						valueField	 : 'id',
						displayField : 'description',

						store : sortingOptions.store,

						value : sortingOptions.initialSort
					}]
				},
				{
					xtype : 'RL.PriceResult.Service.Filter',
					slot  : 'filter',
					parentResults : this,
					store : this.store
				}
			)

			var sortCombo 	= this.slots.sortCombo
			var paging 		= this.slots.paging
			var filter 		= this.slots.filter

			sortCombo.on('select', this.onSortChange, this)
			
			if (this.getConnectedMgtCo()) sortingOptions.initialSort=1

			this.onSortChange(sortCombo, sortCombo.store.getById(sortingOptions.initialSort))

			paging.on('show-page', this.onPageChanged, this)
			filter.on('filter-change', this.onFilterChanged, this)
		}
	},
	//eof initComponent


	onFilterChanged : function () {
		var paging 				= this.slots.paging
		var pagingContainer 	= this.slots.pagingContainer

		if (this.store.getTotalCount() > paging.pageSize * 1.5)
			pagingContainer.show()
		else
			pagingContainer.hide()

		this.doLayout()
	},


	prepareSortingOptions : function () {
		var recordProduct = this.searchForm.recordProduct

		//high-level sorting
		var initialSort, highLevelSort 	= recordProduct.get('SERVICE#CNSSORT') || 'vendor'
		if (highLevelSort == 'item') initialSort = 2
		if (highLevelSort == 'location') initialSort = 4

		var preVendorSort, postVendorSort, preferredOffed=(!this.isMoreThanOneGroupOn('VENDOR#PREFERRED'));
		var vendorSort 		= recordProduct.get('SERVICE#CNSSORTVEN') || 'VENDOR#PREFERRED'
		if (vendorSort == 'VENDOR#PREFERRED'){
			if (preferredOffed){
				vendorSort = 'name'
				if (!initialSort) initialSort=1
			}else{
				postVendorSort='VENDOR#VENDOR'
			}
		}
		if (vendorSort == 'name') {
			vendorSort = 'VENDOR#VENDOR'
			if (!initialSort) initialSort=1
		}
		if (vendorSort == 'random') vendorSort = '#RANDOM_VENDOR'
		if (vendorSort == 'tier_random') {
			preVendorSort = 'VENDOR#PREFERRED'
			vendorSort = '#RANDOM_VENDOR'
		}
		if (vendorSort == 'discount') {
			if (!initialSort) initialSort=7
			preVendorSort = '#DISCOUNT'
			vendorSort = 'VENDOR#VENDOR'
		}
		if (!initialSort) initialSort=3

		//items sorting
		var unitSort		= recordProduct.get('SERVICE#CNSSORTUNT') || '#UNIT_DESC'
		if (unitSort == 'price') unitSort = '#SELL_PRICE'
		if (unitSort == 'discount') unitSort = '#DISCOUNT'

		var store = new Ext.data.ArrayStore({
			fields : [ 'id', 'description', 'sortBy', 'sortDir', 'groupBy', 'paging' ],
			idIndex : 0,

			data : [
				[ 1, this.vendorLabel, [ 'VENDOR#VENDOR', unitSort ] , 'ASC', [ 'VENDOR#VENDOR' ], true ],
				[ 2, this.unitLabel, [ '#UNIT_DESC' ] , 'ASC', [ 'VENDOR#VENDOR' ], true ],
				[ 3, 'Featured', [ preVendorSort, vendorSort, postVendorSort, unitSort ] , 'ASC', [ 'VENDOR#VENDOR' ], true ],
				[ 4, 'Location', [ 'LOCATION#NAME', preVendorSort, vendorSort, postVendorSort, unitSort ], 'ASC', [ 'LOCATION#NAME', 'VENDOR#VENDOR' ], true ],
				[ 5, 'Price (high to low)', [ '#SELL_PRICE' ], 'DESC', [ 'VENDOR#VENDOR' ], true ],
				[ 6, 'Price (low to high)', [ '#SELL_PRICE' ], 'ASC', [ 'VENDOR#VENDOR' ], true ],
				[ 7, 'Discounts', [ '#DISCOUNT', preVendorSort, vendorSort, postVendorSort ], 'DESC', [ 'VENDOR#VENDOR' ], true ]
			]
		})

		if (preferredOffed) {
			store.removeAt(store.indexOfId(3))

			if (initialSort == 3) initialSort = 1
		}


		if (!this.isMoreThanOneGroupOn('VENDOR#VENDOR')) {
			store.removeAt(store.indexOfId(1))
			store.removeAt(store.indexOfId(3))
			store.removeAt(store.indexOfId(4))
			if (initialSort == 1 || initialSort == 3 || initialSort == 4) initialSort = 2
		}

		if (!this.isMoreThanOneGroupOn('LOCATION#NAME')) {
			store.removeAt(store.indexOfId(4))
			if (initialSort == 4) initialSort = 3
		}

		if (!this.isMoreThanOneGroupOn('#DISCOUNT')) store.removeAt(store.indexOfId(7))

		if (!this.showPrices) {
			store.removeAt(store.indexOfId(5))
			store.removeAt(store.indexOfId(6))
		}

		return {
			store : store,
			initialSort : initialSort
		}
	},


	isMoreThanOneGroupOn : function (fieldName) {
		var store = this.store

		var encounteredValues = {}
		var encounteredCounter = 0

		store.each(function (record) {
			var fieldValue = String(record.get(fieldName))

			if (!encounteredValues.hasOwnProperty(fieldValue)) {
				encounteredValues[fieldValue] = true
				encounteredCounter++

				if (encounteredCounter > 1) return false
			}
		}, this)

		return encounteredCounter > 1
	},



	onPageChanged : function (paging, from, to) {
		this.store.setDataPage(from, to)
	},


	onSortChange : function (combo, record, index) {
		var store 				= this.store
		var paging 				= this.slots.paging
		var pagingContainer 	= this.slots.pagingContainer
		var filter 				= this.slots.filter

		store.suspendEvents()

		filter.reset()

		store.setDataPage(0, store.getTotalCount() - 1)
		store.clearGrouping()

		store.sort(record.get('sortBy'), record.get('sortDir'))

		Ext.each(record.get('groupBy'), function (field) {
			store.groupBy(field)

			if (this.isMoreThanOneGroupOn(field)) this.addFilterForField(field)

		}, this)

		this.slots.toolbar.doLayout()

		store.refreshDataSet()

		if ( store.getTotalCount() > paging.pageSize * 1.5) {
			store.setDataPage(0, paging.pageSize - 1)
			pagingContainer.show();
		} else {
			pagingContainer.hide();
		}


		store.resumeEvents()

		store.fireEvent('datachanged', store)

		paging.onLoad(store, [], {})
	},


	addFilterForField : function (field) {
		var filter 			= this.slots.filter
		var colModel 		= this.slots.grid.getColumnModel()
		var columnIndex		= colModel.findColumnIndex(field)

		var options = {}

		if (columnIndex != -1) options.description = colModel.getColumnHeader(columnIndex)


		if (field == 'BUILD#TYPE')
			Ext.apply(options, {
				computeDisplayValue : function (pricingRecord) {
					return pricingRecord.getService().get("SERVICE#DESCRIP")
				}
			})
			
		if (field == 'VENDOR#VENDOR'){
			field="#LINK_TO_VENDOR"
			Ext.apply(options, {
				computeDisplayValue : function (pricingRecord) {
					return pricingRecord.data["VENDOR#VENDOR"]
				}
			})
		}

		filter.addFilter(field, options)
	},


	unitTypeRenderer: function (v,n,r,i,c,s) {
		return r.data['#DISCOUNT'] == '' ? v : v + ' <div class="unitTypeDiscount">' + r.data['#DISCOUNT'] + '</div>'
	},


	priceRenderer: function(v,n,r,i,c,s){

		if (!this.priceRules){
			this.priceRules={
				"DEPT#CONPRICES":  Number(Ext.jx.getStoreValue("DEPT#CONPRICES")),
				"DEPT#CONPRANGEL": Number(Ext.jx.getStoreValue("DEPT#CONPRANGEL")),
				"DEPT#CONPRANGEH": Number(Ext.jx.getStoreValue("DEPT#CONPRANGEH")),
				"DEPT#CONPRANGER": Number(Ext.jx.getStoreValue("DEPT#CONPRANGER"))
			};

			var recordProduct=this.searchForm.recordProduct ?  this.searchForm.recordProduct : r.getService();
			this.priceRules['#B_PRICENIGHTLY']= recordProduct.data['#B_PRICENIGHTLY']==1 || recordProduct.isGDSLodging();
		}

		if (this.priceRules['#B_PRICENIGHTLY'] && r.data['BUILD#NGTS'] && r.data['BUILD#NGTS']!=0) v=v/r.data['BUILD#NGTS'];

		var rounder;
		if (this.priceRules['DEPT#CONPRANGER']!=1){
			var roundDigits=this.priceRules['DEPT#CONPRANGER']==2 ? -1 : 0;
			rounder=Math.pow(10,roundDigits);
		}
		if (this.priceRules['DEPT#CONPRICES']==2){
			var low=(1-this.priceRules['DEPT#CONPRANGEL'])*v;
			if (rounder) low=Math.round(low * rounder)/rounder;
			low=Ext.jx.math.formatCurrency(low);

			var high=(1+this.priceRules['DEPT#CONPRANGEH'])*v;
			if (rounder) high=Math.round(high * rounder)/rounder;
			high=Ext.jx.math.formatCurrency(high);

			v=(low==high ? '~ '+low : String(low)+' to '+String(high));
		}else if (this.priceRules['DEPT#CONPRICES']==3){
			if (rounder) v=Math.round(v * rounder)/rounder;
			v=Ext.jx.math.formatCurrency(v);
		}

		if (this.priceRules['#B_PRICENIGHTLY'] && r.data['BUILD#NGTS'] && r.data['BUILD#NGTS']!=0) v=String(v)+' night';
		return v;

	},


    onBodyResize : function (w, h) {
        this.fireEvent('bodyresize-buffered', this, w, h)
    },


    onBodyResizeBuffered : function (self, w, h) {
    	this.fireEvent('bodyresize', self, w, h)
    },
    
	getConnectedMgtCo : function(){
		var wizard=RL.Global.getWizard(this.searchForm), o, mgtco;
		if ((o=RL.Global.connectedDestProducts[wizard.destCode]) && this.searchForm.recordProduct) 
			mgtco=o[ this.searchForm.recordProduct.data['SERVICE#CODE'] ]

		if (!mgtco && (o=RL.Global.connectedDestProdGroups[wizard.destCode]) && this.searchForm.recordProdGroup)
			mgtco=o[ this.searchForm.recordProdGroup.data['PRODGRP#PGID'] ]
		
		return mgtco;
    }

});

//XXX unused code?

//Ext.ns('RL.PriceResult');
//
//
//RL.PriceResult.SimpleQtyAddToolBar = Ext.extend(Ext.Panel, {
//	
//	//form to which this toolbar is attached
//	form : null,
//	
//	resultComp : null,
//	
//
//	constructor : function(config){
//		config = config || {};
//		
//		var form = config.form;
//		
//		Ext.apply(config, {
//			
//			layout : 'template',
//			
//			tpl : ['<div class="prodtype_transp_footer">',
//					'<div class="prodtype_transp_outer3">',
//						'<div class="prodtype_transp_leftcol3b">Choose quantity and select Add button</div>',
//						'<div class="prodtype_transp_rightcol3">{skipBtn:field}</div>',
//						'<div class="prodtype_transp_middlecol3">',
//							'<div class="prodtype_transp_inner3">{addBigBtn:field}</div>',
//						'</div>',
//					'</div>',
//				'</div>'
//			],
//		
//			height : 50,
//			
//			items : [
//				{
//					//xtype:'simple_button',
//					xtype:'button',
//					name:'skipBtn',					
//					iconCls:'skip-btn',					
//					handler: function() {
//						RL.Global.getWizard(this).onNextStep();
//					},
//					scope : this
//				},
//				{
//					xtype:'button',
//					//xtype:'simple_button',
//					name:'addBigBtn',
//					
//					iconCls:'add-multiple-btn',
//					
//					handler : function() {
//						var view = this.resultComp.slots.grid.view;
//						var gtawRecord = Ext.jx.getStore('GTAW').getAt(0);
//						var totalQty = 0;
//
//						if (view.ds){
//							Ext.jx.debug('missing view.ds');
//							return undefined;
//						}
//		
//						for (var i = 0, len = view.ds.data.items.length; i < len; i++) {
//							var rowEl = view.getRow(i), r = view.ds.data.items[i], dropDowns=Ext.fly(rowEl).query('.quantityDropdown'), qty, dropDown;
//							if (dropDowns.length && (dropDown=dropDowns[0]) && (qty=Number(dropDown.options[dropDown.selectedIndex].value))){
//								totalQty+=qty;
//								var buildRecord = RL.Global.getWizard(this.searchForm).addServiceItem( r, {'BUILD#UNITS':qty} );
//								dropDown.selectedIndex=0; 
//							}
//						}
//						
//						if (totalQty) {
//							//this.form.fireEvent('next_step');
//						}else{
//							Ext.MessageBox.alert('Alert', 'Select the number of items you want using the drop down buttons before pressing this button');
//						}
//					},
//					scope : this
//				}
//			]
//			
//		});//eof apply
//		
//		RL.PriceResult.SimpleQtyAddToolBar.superclass.constructor.call(this, config);
//		
//	}//eof constructor
//	
//});//eof extend
//	
//	
//Ext.reg('simple_qty_add_toolbar', RL.PriceResult.SimpleQtyAddToolBar);
Ext.ns('RL.PriceResult');

RL.PriceResult.GolfPlanner = Ext.extend(Ext.Panel, {
	baseCls: 'x-bubble',
	frame: true,
	layout:"border",
	hideBorders:true,
	
	constructor : function(config){
		config = config || {};
		
		Ext.apply(config, {
			
			//layout:'fit',
			//items:[{
			items:[{
				region:'north',
				xtype : 'results_top_toolbar',
				//height: 60,
				//form : searchForm ,
				msg:'Golf Planner'
			},{
				
				region:'center',
				golf_planner_parent:true,
				bodyStyle : {
					'overflow-y':'auto',
					'overflow-x':'hidden'
				}
				
				//bodyStyle : 'overflow-y:auto;overflow-x:hidden;'

			},{

				region:'south',
				autoHeight : true,

				xtype: "toolbar",			
				items:[{
					iconCls:'skip-btn',
					handler : this.onSkipClick,
					scope : this					        
				}]
				
			}]
			
			//}]
			//autoScroll:true,
			//autoWidth:true,
			//style:{padding:'0px !important', margin:'0px !important', border:'0px'}
			//,
			//isOptional:true,
			
			//autoHeight:true
		    	
		    
			
			
		}); //eof apply
		
		RL.PriceResult.GolfPlanner.superclass.constructor.call(this, config);
	},//eof constructor
	
    onRender: function(){
		
		this.printGolfPlanner();		
        RL.PriceResult.GolfPlanner.superclass.onRender.apply(this,arguments);		
		
    },	
	
	onSkipClick : function(){
		RL.Global.getWizard(this).onNextStep();
	},
	
	printGolfPlanner : function() {
		var golf_planner_parent=this.findBy(function(item){ return item.golf_planner_parent })[0];

		var values=this.searchForm.getSearchValues();
		
		var ddate=values['#DDATE'] ? values['#DDATE'].dateFormat("m/d/y") : undefined;
		var rdate=values['#RDATE'] ? values['#RDATE'].dateFormat("m/d/y") : undefined;
		
		if (this.ddate_printed != ddate || this.rdate_printed != rdate){
			this.ddate_printed = ddate;
			this.rdate_printed = rdate;

			golf_planner_parent.removeRange();
	
			if (!ddate || !rdate) return;

			if (golf_planner_parent.el) golf_planner_parent.el.mask('Preparing your screen...', 'x-mask-loading');
			
			var items=[];	
			var days=values['#RDATE'].subtractDt(values['#DDATE']);
			for (var i=0; i<=days; i++){
				
				var dateNow=values['#DDATE'].add('d', i);
				items.push({
					xtype:'golf_day',
					dateDay: dateNow,
					recordProduct:this.searchForm.recordProduct,
					searchForm:this.searchForm,
					style:{
						'margin-bottom':'3px'
					}
				});	
			}
			
			golf_planner_parent.add(items);			

			if (golf_planner_parent.el) golf_planner_parent.el.unmask();
			
		}
		
	}
	//
	//
	//vendorsDownloaded : function(calledDirect) {
	//	
	//	var vars=Ext.jx, vendorStore=Ext.jx.getStore('VENDOR'), formResort = this.findParentBy(function(item){ return !!item.resortRecord }),
	//		destCode=formResort.resortRecord.get('RESORT#SEARCHCODE'),
	//		productType=this.recordProduct.get('SERVICE#CODE'),
	//		eventName=RL.Global.getVendorDlEventName(destCode,productType);
	//	
	//	if (!calledDirect){
	//		RL.Global.Events.un(eventName, this.vendorsDownloaded);
	//		this.el.unmask.defer(300, this.el);						
	//	}
	//	
	//	this.printGolfPlanner();
	//	
	//},
	//
	
//	onActivate : function() {
//		RL.PriceSearch.Service.superclass.onActivate.call(this);
//
//		var vars=Ext.jx, vendorStore=Ext.jx.getStore('VENDOR'), formResort = this.findParentBy(function(item){ return !!item.resortRecord });
//		if (!formResort || !formResort.resortRecord) return; //can not go back to parent
//		var destCode=formResort.resortRecord.get('RESORT#SEARCHCODE'), productType=this.recordProduct.get('SERVICE#CODE'), eventName=RL.Global.getVendorDlEventName(destCode,productType);
//		
//		if (!RL.Global.downloadedVendorLists[eventName]){
//			this.el.mask('Preparing your screen...', 'x-mask-loading');
//			RL.Global.Events.on(eventName, this.vendorsDownloaded, this);
//		}else{
//			this.vendorsDownloaded(true);
//		}
// 	}, 

	
	
});
Ext.reg('golfplanner', RL.PriceResult.GolfPlanner);



RL.PriceResult.GolfPlanner_Day = Ext.extend(Ext.Panel, {

	autoHeight: true,

	constructor : function(config){
		config = config || {};
		
		var htmlDay='<b>'+config.dateDay.dateFormat("l, F j, Y")+'</b>';				
		
		var cats=config.recordProduct.getTimesCats();

		var newItems=[];
		var htmlDay='<b>'+config.dateDay.dateFormat("l, F j, Y")+'</b>';

		newItems.push({
				//xtype:'container',
				frame:true,
				html:htmlDay
		});
		
		for (var catName in cats){
			var cat=cats[catName];
			var store = new Ext.data.ArrayStore({
				fields:Ext.jx.getStore("TIMES","ALL").fields.items
			});
			store.add(cat);
			newItems.push({
				xtype:'golf_day_time',
				recordProduct: config.recordProduct,
				searchForm: config.searchForm,
				catName:catName,
				timeStore: store
			});
			
		};
		config.items=newItems;
		RL.PriceResult.GolfPlanner_Day.superclass.constructor.call(this, config);
		
	}


});

Ext.reg('golf_day', RL.PriceResult.GolfPlanner_Day);


RL.PriceResult.GolfPlanner_DayTime = Ext.extend(Ext.Panel, {
	layout:'column',
	autoHeight: true,

	onVendorSelect: function(combo){
		var moreInfoImg=this.findBy(function(c){ return c.moreInfoImg },this)[0];
		if (combo.getValue()){		
			moreInfoImg.addClass('more-info');
		}else{
			moreInfoImg.removeClass('more-info');			
		}
	},

	onVendorMoreInfo: function(img){
		var vendorSelect=this.findBy(function(c){ return c.xtype==='vendor_selector' },this)[0];
		var vendorCode=vendorSelect.getValue();
		if (!vendorCode) return;
		var vendorRecord=Ext.jx.vendors[vendorCode];
		var golf_planner_parent=this.findParentBy(function(p){ return p.golf_planner_parent });
		RL.Global.showContent(golf_planner_parent, 'vendor', vendorRecord, 'Pictures', {vendorRecord: vendorRecord, searchForm: this.searchForm});
	},
	
	constructor : function(config){
		config = config || {};
		
		var searchForm = config.searchForm;
		this.recordProduct = searchForm.recordProduct;
		
		Ext.apply(config, {
				
			items:[{
				frame:true,
				width:40,
				html:config.catName
			},{
				xtype:'container_spacer',
				width:10
			},{
				//name:'people',
				emptyText:'Golfers',
				width:70,
				xtype:'perperson_selector'
			},{
				xtype:'container_spacer',
				width:10
			},{						
				xtype:'combo',
				width:100,
				mode:'local',				
				emptyText:'Tee Time',
				typeAhead: true,
				triggerAction: 'all',				
				displayField: 'TIMES#LABEL',
				valueField: 'TIMES#LABEL',				
				store:config.timeStore
			},{
				xtype:'container_spacer',
				width:10
			},{						
				width:250,
				emptyText:'Golf Course',
				xtype:'vendor_selector',
				listeners:{
					valid: this.onVendorSelect,
					scope: this
				}
			},{
				xtype:'container_spacer',
				width:10
			},{						
				xtype:'image',
				moreInfoImg: true,
				listeners:{
					click: this.onVendorMoreInfo,
					scope: this
				}
			}]
		});
		delete config.timeStore;
		
		RL.PriceResult.GolfPlanner_DayTime.superclass.constructor.call(this, config);
	}
	
});


Ext.reg('golf_day_time', RL.PriceResult.GolfPlanner_DayTime);

Ext.ns('RL.PriceResult');


RL.PriceResult.Air = Ext.extend(Ext.Panel, {

	slots : true,

	autoEl : 'div',


	//searchForm to which this result is attached
	searchForm : null,
	layout:'row-fit',
	baseCls: 'x-bubble',
	frame: true,


	constructor : function(config){
		config = config || {};

		config.recordProduct = config.searchForm.recordProduct;

		var rowActions = new Ext.ux.RowActions({
			actions:[{
				iconCls : 'add-to-cart-orange',
				autoWidth : false,
				width : 45,
				style : {
					width:'45px'
				},
				tooltip : 'Add the item to your quote',
				listeners : {
					action : function(rowActions, dataview, pricingRecord, action, row, col, iconCls) {
	                	var gtawRecord=Ext.jx.getStore('GTAW').getAt(0);
	                	var buildRecord=RL.Global.getWizard(this.searchForm).addServiceItem( pricingRecord );
						RL.Global.getWizard(this.searchForm).onNextStep();
		    		},
					scope:this
		    	}
			}]
		});


		Ext.apply(config, {


	    	items:[
	    		{
					xtype : 'results_top_toolbar',
					height: 60,
					form : config.searchForm
		    	},
	    		{
				    xtype:'dataview',
				    slot : 'view',

				    store: config.store,
				    plugins : [ rowActions ],

					style:{
						overflow:'auto'
					},
					itemSelector:'.gdsAirRecord',
					tpl : new Ext.XTemplate(Ext.jx.getTable("_VENDOR_PRICING").templates.gdsair)
				}
			]

		}); //eof apply

		RL.PriceResult.Air.superclass.constructor.call(this, config);
	},//eof constructor


	initComponent : function(){
		RL.PriceResult.Air.superclass.initComponent.call(this);

	}

});

Ext.ns('RL');

RL.SearchTopToolbar = Ext.extend(Ext.Toolbar, {
	
	slot : 'search_toolbar',
	//height: 60,
	
	//form to which this toolbar is attached
	form : null,
	
	constructor : function(config){
		config = config || {};
		
		var form = config.form;
		
		Ext.apply(config, {
			toolbarCls: 'x-frameless',
			hideBorders: true,
			
			height : 30,
			
		    items : [
		    	'<div style="margin: 0 10px 0 5px"><b>Search Filters</b></div>'
	//    		{
	//				iconCls:'newSearch-btn',
	//				style:'margin-left:100px;margin-right:50px;',
	//				handler: function() {
	//					this.form.fireEvent('new_search');
	//				},
	//				scope : this
	//    		},
//    			{
//			    	xtype:'image',
//					cls:'skip-btn',
//					baseStyle:{
//						margin: '0 0 0 10px'
//					},
//					listeners:{
//						click: function(){
//							RL.Global.getWizard(this).onNextStep();
//						},
//						scope: this
//					}
//				}
			]
			
		}); //eof apply
		
		RL.SearchTopToolbar.superclass.constructor.call(this, config);
	}//eof constructor
	
});


Ext.reg('search_top_toolbar', RL.SearchTopToolbar);



RL.ResultsTopToolbar = Ext.extend(Ext.Toolbar, {

	msg : 'Search Results',	
	slot : 'results_toolbar',
	
	constructor : function(config){
		config = config || {};
		
		var form = config.form;
		
		Ext.apply(config, {
			toolbarCls: 'x-frameless',
			hideBorders: true,
			
			height : 30,
			
		    items : [
		    	'<div style="margin: 0 10px 0 5px"><b>'+(config.msg||this.msg)+'</b></div>',
	//    		{
	//				iconCls:'newSearch-btn',
	//				style:'margin-left:100px;margin-right:50px;',
	//				handler: function() {
	//					this.form.fireEvent('new_search');
	//				},
	//				scope : this
	//    		},
    			{
			    	xtype:'image',
					cls:'skip-btn',
					baseStyle:{
						margin: '0 0 0 10px'
					},
					listeners:{
						click: function(){
							RL.Global.getWizard(this).onNextStep();
						},
						scope: this
					}
				}
			]
			
		}); //eof apply
		
		RL.ResultsTopToolbar.superclass.constructor.call(this, config);
	}//eof constructor
	
});


Ext.reg('results_top_toolbar', RL.ResultsTopToolbar);


Ext.ns('RL.PriceResult');


RL.PriceResult.ProductGroup = Ext.extend(RL.PriceResult.Service, {

	productTypes : null,



	constructor : function(config) {
		config = config || {};

		var formProdGroup = this, searchForm = config.searchForm, recordProdGroup = searchForm.recordProdGroup, store = config.store;

		var rowActions = this.rowActions = new RL.PriceResult.PricingRowActions({
			searchForm : searchForm,
			resultForm : this
		});


		Ext.namespace('Ext.jx.temp');
		Ext.jx.temp.rowActions = rowActions;


		var actionCol;
		var configAddToolBar = {
			xtype : 'results_top_toolbar',
			form : searchForm,

			slot : 'toolbar'
		};

		if ( RL.Defaults.USE_DDOWN_QTY_ADD_LOGIC_WHEN_CAN ) {
			actionCol = Ext.jx.Misc.getSimpleQtyActionCol()
		} else {
			actionCol = Ext.apply({width:50, header:'Add Item', id:1}, rowActions.get('add-to-cart'));
		}

		var colDef=[
			//{header: "Location", width: 120, dataIndex: 'LOCATION#NAME', sortable: true},
			Ext.apply(actionCol,{id:0}),
			{ header: "Product Type", width: 120, dataIndex: 'BUILD#TYPE', sortable: true, id : 1, hidden : true },
			{ header: "Vendor", width: 120, dataIndex: 'VENDOR#VENDOR', sortable: true, id : 2, hidden : true },
			{ header: "Service", width: 120, dataIndex: 'SERVICE#DESCRIP', renderer : this.serviceDescriptionRenderer, sortable: true, id : 100 },
			{ header: '#DISCOUNT', width: 120, dataIndex: '#DISCOUNT', sortable: true, id : 102, hidden : true }

		];

		colDef.push({
			header: "Type",
			width: 180,
			dataIndex: '#UNIT_DESC',
			sortable: true,
			renderer: this.unitTypeRenderer,
			scope: this,
			id:3
		});


		var conPriceOv = recordProdGroup.get('SERVICE#CONPRICEOV')
		var conPrices  = Ext.jx.getStoreValue("DEPT#CONPRICES")

		this.showPrices = conPriceOv == 1 || (conPriceOv != 2 && (conPrices == 3 || conPrices == 2)) //the product type website show toggle must be on

		if (this.showPrices) colDef.push({
			header: "Price in <b>"+Ext.jx.getStoreValue('GTAW#CADCURR')+")</b>",
			width: 115,
			dataIndex: '#SELL_PRICE',
			renderer: this.priceRenderer,
			scope: this,
			sortable: true,
			id:4
		}); //todo Ext.jx.getStoreValue("DEPT#CONPRICES") ==2 which is the price range


		var cm = new Ext.grid.ColumnModel(colDef);

		//UI definition
		Ext.apply(config, {

			layout : 'row-fit',

	    	items : [
		    	configAddToolBar,

//				!jumps ? { baseCls: 'x-frameless' } : {
//					layout		: 'toolbar',
//					autoHeight	: true,
//					//height : 30,
//					items		: jumps,
//					frame		: true
//				},
				{
					xtype:'grid',
					slot : 'grid',

					height:'100%',
					hideHeaders: true,

					plugins : [ rowActions ],
					store : store,

					view: new Ext.ux.MultiGroupingView({
						//showGroupName: false,
						enableNoGroups:false, // REQUIRED!
//						hideGroupedColumn: true,
						forceFit:true,
						groupTextTpl: '{text} : {gvalue} ({[values.rs.length]} {[values.rs.length == 1 ? "Record" : "Records"]})'
					}),
					cm: cm
				},

				{
					xtype : 'container',
					slot : 'pagingContainer',
					
					height : 24,

					layout : 'column',
					hideBorders : true,

					items : [
						{
							columnWidth : 0.5,
							html : '&nbsp;'
						},
						{
							xtype : 'ExtX.Toolbar.Paging',
							slot : 'paging',

							width : 230,

							pageSize : 20,

							store : config.store,

							paramNames : {
                                start : 'from'
                            }
						},
						{
							columnWidth : 0.5,
							html : '&nbsp;'
						}
					]
				}

			]


		});//eof apply

		RL.PriceResult.ProductGroup.superclass.constructor.call(this, config); //do not perform construction of the parent

	},//eof constructor


	initComponent : function(){
		RL.PriceResult.ProductGroup.superclass.initComponent.call(this);

		//store preparations
		var store = this.store;

		store.groupFieldClasses = {
			'BUILD#TYPE' : 'x-grid-group-hd-headerless',
			'VENDOR#VENDOR' : 'x-grid-group-hd-vendor',
			'#RANDOM_VENDOR' : 'x-grid-group-hd-vendor',
			'LOCATION#NAME' : 'x-grid-group-hd-headerless'
		}

		store.groupFieldTemplates={
			'BUILD#TYPE':'{['+
				'function (){'+
					'var record=values.rs[0];'+
					'var recordProduct=record.getService();'+
					'return recordProduct.get("SERVICE#DESCRIP");'+
				'}()'+
			']}',
			'VENDOR#VENDOR':'{['+
				'function (){'+
					'var record=values.rs[0];'+
					'var recordVendor=record.getVendor();'+
					'return (!recordVendor ? record.get("VENDOR#VENDOR") :  recordVendor.getShortDesc() );'+
				'}()'+
			']}'
		};
	},


	prepareSortingOptions : function () {
//		var recordProduct = this.searchForm.recordProduct
//
//		//high-level sorting
//		var initialSort, highLevelSort 	= recordProduct.get('SERVICE#CNSSORT') || 'vendor'
//		if (highLevelSort == 'item') initialSort = 2
//		if (highLevelSort == 'location') initialSort = 4
//
//		var preVendorSort, postVendorSort, preferredOffed=(!this.isMoreThanOneGroupOn('VENDOR#PREFERRED'));
//		var vendorSort 		= recordProduct.get('SERVICE#CNSSORTVEN') || 'VENDOR#PREFERRED'
//		if (vendorSort == 'VENDOR#PREFERRED'){
//			if (preferredOffed){
//				vendorSort = 'name'
//				if (!initialSort) initialSort=1
//			}else{
//				postVendorSort='VENDOR#VENDOR'
//			}
//		}
//		if (vendorSort == 'name') {
//			vendorSort = 'VENDOR#VENDOR'
//			if (!initialSort) initialSort=1
//		}
//		if (vendorSort == 'random') vendorSort = '#RANDOM_VENDOR'
//		if (vendorSort == 'tier_random') {
//			preVendorSort = 'VENDOR#PREFERRED'
//			vendorSort = '#RANDOM_VENDOR'
//		}
//		if (!initialSort) initialSort=3
//
//		//items sorting
//		var unitSort		= recordProduct.get('SERVICE#CNSSORTUNT') || '#UNIT_DESC'
//		if (unitSort == 'price') unitSort = '#SELL_PRICE'
//		if (unitSort == 'discount') unitSort = '#DISCOUNT'

		var initialSort = 0

		var store = new Ext.data.ArrayStore({
			fields : [ 'id', 'description', 'sortBy', 'sortDir', 'groupBy', 'paging' ],
			idIndex : 0,

			data : [
				[ 0, 'Service', [ 'BUILD#TYPE' ] , 'ASC', [ 'BUILD#TYPE', 'VENDOR#VENDOR' ], true ],
				[ 1, this.vendorLabel, [ 'VENDOR#VENDOR' ] , 'ASC', [ 'VENDOR#VENDOR' ], true ],
				[ 2, this.unitLabel, [ '#UNIT_DESC' ] , 'ASC', [ 'VENDOR#VENDOR' ], true ],
//				[ 3, 'Featured', [ preVendorSort, vendorSort, postVendorSort, unitSort ] , 'ASC', [ 'VENDOR#VENDOR' ], true ],

				//XXX no such field for product groups?
				//[ 4, 'Location', [ 'LOCATION#NAME' ], 'ASC', [ 'LOCATION#NAME', 'VENDOR#VENDOR' ], false ],

				[ 5, 'Price (high to low)', [ '#SELL_PRICE' ], 'DESC', [ 'VENDOR#VENDOR' ], true ],
				[ 6, 'Price (low to high)', [ '#SELL_PRICE' ], 'ASC', [ 'VENDOR#VENDOR' ], true ]

				//XXX no such field for product groups?
				//[ 7, 'Discounts', [ '#DISCOUNT' ], 'DESC', [ 'VENDOR#VENDOR' ], true ]
			]
		})

//		if (preferredOffed) {
//			store.removeAt(store.indexOfId(3))
//
//			if (initialSort == 3) initialSort = 1
//		}
//
//
//		if (!this.isMoreThanOneGroupOn('VENDOR#VENDOR')) {
//			store.removeAt(store.indexOfId(1))
//			store.removeAt(store.indexOfId(3))
//			store.removeAt(store.indexOfId(4))
//			if (initialSort == 1 || initialSort == 3 || initialSort == 4) initialSort = 2
//		}
//
//		if (!this.isMoreThanOneGroupOn('LOCATION#NAME')) {
//			store.removeAt(store.indexOfId(4))
//			if (initialSort == 4) initialSort = 3
//		}
//
//		if (!this.isMoreThanOneGroupOn('#DISCOUNT')) store.removeAt(store.indexOfId(7))
//
		if (!this.showPrices) {
			store.removeAt(store.indexOfId(5))
			store.removeAt(store.indexOfId(6))
		}

		return {
			store : store,
			initialSort : initialSort
		}
	},


	onSortChange : function (combo, record, index) {
		var grid = this.slots.grid
		var colModel = grid.getColumnModel()
		var serviceDescIndex = colModel.getIndexById(100)

		colModel.setHidden(serviceDescIndex, record.id == 0)

		RL.PriceResult.ProductGroup.superclass.onSortChange.apply(this, arguments)
	},


	serviceDescriptionRenderer : function (value, metaData, record, rowIndex, colIndex, store) {
		return record.getService().get("SERVICE#DESCRIP")
	}


});

Ext.ns('RL.PriceResult');


RL.PriceResult.PricingRowActions = Ext.extend(Ext.ux.RowActions, {

	searchForm 		: null,
	resultForm		: null,


	constructor : function (config) {
		config = config || {};

		Ext.apply(config, {
			actions : [
				{
					iconCls : 'add-to-cart',
					autoWidth : false,
					width : 45,
					style : {
						width : '45px'
					},
					text: 'add',
					tooltip : 'Add the item to your quote',
					listeners : {
						action : this.showAddServicePopup.createDelegate(this)
					}
				},
				{
					iconCls : 'more-info',
					cls : 'prodtype_round_button',
					text : 'More Info',
					autoWidth : false,
					noBlankImg : true,
					tooltip : 'Find out more information about this vendor',
					listeners : {
						
						action : function(rowActions, grid, record, action, row, col, iconCls){
							var vendorRecord = record.getVendor()
							if (vendorRecord) RL.Global.showContent(rowActions.searchForm, 'vendor', vendorRecord, 'More Info', {pricingRecord : record, vendorRecord: vendorRecord});
						}
					}
				},

				{
					iconCls : 'more-info-pictures',
					cls : 'prodtype_round_button',
					text : 'Pictures',
					autoWidth : false,
					noBlankImg : true,
					tooltip : 'Find out more information about this vendor',
					listeners : {
						action : function(rowActions, grid, record, action, row, col, iconCls){
							var vendorRecord = record.getVendor()
							if (vendorRecord) RL.Global.showContent(rowActions.searchForm, 'vendor', vendorRecord, 'Pictures', {pricingRecord : record, vendorRecord: vendorRecord});
						}
					}
				},

				{
					iconCls : 'more-info-calendar',
					cls : 'prodtype_round_button',
					text : 'Avail',
					autoWidth : false,
					noBlankImg : true,
					tooltip : 'Check inventory data available',
					listeners : {
						action: function(rowActions, grid, record, action, row, col, iconCls){
							var vendorRecord = record.getVendor()
							if (vendorRecord) RL.Global.showContent(rowActions.searchForm, 'vendor', vendorRecord, 'Calendar', {pricingRecord : record, vendorRecord: vendorRecord});
						}
					}
				},

				{
					text 			: 'Inventory',

					iconCls 		: 'more-info-inventory',
					cls 			: 'prodtype_round_button',

					autoWidth 		: false,
					noBlankImg 		: true,
					tooltip 		: 'Check inventory data available',

					listeners : {
						action : function (rowActions, grid, record, action, row, col, iconCls) {
							var vendorRecord = record.getVendor()

							if (vendorRecord) RL.Global.showContent(rowActions.searchForm, 'vendor', vendorRecord, 'Inventory', { pricingRecord : record, vendorRecord : vendorRecord })
						}
					}
				},

				{
					iconCls : 'more-info-content',
					text : 'Content'
				},

				{
					iconCls : 'more-info-map',
					cls : 'prodtype_round_button',
					name : 'more-info-map',
					text : 'Map',
					autoWidth : false,
					noBlankImg : true,
					tooltip : 'Find out more information about this vendor',
					listeners : {
						action : function(rowActions, grid, record, action, row, col, iconCls){
							var vendorRecord = record.getVendor()
							
							if (vendorRecord) RL.Global.showContent(rowActions.searchForm, 'vendor', vendorRecord, 'Map', {pricingRecord : record, vendorRecord: vendorRecord});
						}
					}
				},
				
				{
					iconCls : 'more-info-streetview',
					cls : 'prodtype_round_button',
					name : 'more-info-streetview',
					text : 'Street View',
					autoWidth : false,
					noBlankImg : true,
					tooltip : 'Find out more information about this vendor',
					listeners : {
						action : function(rowActions, grid, record, action, row, col, iconCls){
							var vendorRecord = record.getVendor()
							
							if (vendorRecord) RL.Global.showContent(rowActions.searchForm, 'vendor', vendorRecord, 'StreetView', {pricingRecord : record, vendorRecord: vendorRecord});
						}
					}
				}
			]

		}); //eof apply

		Ext.ux.RowActions.call(this, config);
	},
	
	
	showAddServicePopup : function (rowActions, grid, record, action, row, col, iconCls) {
	
		if (RL.Global.lastGridRowBlind) return //it allows 5px treshold, so potentially can open several popups
		
		var popup = new Ext.ux.GridRowBlind({
			destroyOnDismiss		: true,
			autoEventsHide			: [ 'click' ],
			
			marginLeft				: 0,
			marginRight				: 100
		})
		
		popup.init(grid)

		popup.show(row, new RL.Build.Popup({
			pricingRecord 	: record,
			searchForm 		: this.searchForm,
			
			buildPopup 		: popup
		}))
		
		popup.on('destroy', function () {
			RL.Global.lastGridRowBlind = null
		})

		RL.Global.lastGridRowBlind = popup //there can only be one since any click away destroys it in the autoDestroy mode
	}
	
	



}); //eof extend

Ext.ns('RL.PriceSearch');


RL.PriceSearch.VendorFilter = Ext.extend(Ext.ux.form.SuperBoxSelect, {
	
	clsTrigger: 'x-tool-toggle',
	
	constructor : function(config){
		config = config || {};
		
		Ext.apply(config, {

			//labelTriggerBtn:'test',
			labelTriggerBtn:'<div class="x-tool '+this.clsTrigger+'" style="width:15px;float:right; background-position:0 -75px;">&#160;</div>',
			

			
			
			
			renderFieldBtns:false,
			renderInputBtn: false,
			stackItems:true,
			allowBlank:true,
			//fieldLabel: 'States',
			//emptyText: 'Select some US States',
			resizable: true,
			name: 'states',
			anchor:'100%',
			//width:150,
			mode: 'local'
			
			//displayField: 'state',
			//displayFieldTpl: '{state} ({abbr})',
			//valueField: 'abbr',
			//value: 'CA,NY'
			
		}); //eof apply
		
		RL.PriceSearch.VendorFilter.superclass.constructor.call(this, config);
	},//eof constructor
	
	
	initComponent : function(){
		
//		Ext.namespace('Ext.exampledata');
//		
//		Ext.exampledata.states = [
//			['AL', 'Alabama', 'The Heart of Dixie','ALClass'],
//			['AK', 'Alaska', 'The Land of the Midnight Sun','AKClass'],
//			['AZ', 'Arizona', 'The Grand Canyon State','AZClass'],
//			['AR', 'Arkansas', 'The Natural State','ARClass'],
//			['CA', 'California', 'The Golden State','someClass'],
//			['CO', 'Colorado', 'The Mountain State','someClass'],
//			['CT', 'Connecticut', 'The Constitution State','someClass'],
//			['DE', 'Delaware', 'The First State','someClass'],
//			['DC', 'District of Columbia', "The Nation's Capital",'someClass'],
//			['FL', 'Florida', 'The Sunshine State','someClass'],
//			['GA', 'Georgia', 'The Peach State','someClass'],
//			['HI', 'Hawaii', 'The Aloha State','someClass'],
//			['ID', 'Idaho', 'Famous Potatoes','someClass'],
//			['IL', 'Illinois', 'The Prairie State','someClass'],
//			['IN', 'Indiana', 'The Hospitality State','someClass'],
//			['IA', 'Iowa', 'The Corn State','someClass'],
//			['KS', 'Kansas', 'The Sunflower State','someClass'],
//			['KY', 'Kentucky', 'The Bluegrass State','someClass'],
//			['LA', 'Louisiana', 'The Bayou State','someClass'],
//			['ME', 'Maine', 'The Pine Tree State','someClass'],
//			['MD', 'Maryland', 'Chesapeake State','someClass'],
//			['MA', 'Massachusetts', 'The Spirit of America','someClass'],
//			['MI', 'Michigan', 'Great Lakes State','someClass'],
//			['MN', 'Minnesota', 'North Star State','someClass'],
//			['MS', 'Mississippi', 'Magnolia State','someClass'],
//			['MO', 'Missouri', 'Show Me State','someClass'],
//			['MT', 'Montana', 'Big Sky Country','someClass'],
//			['NE', 'Nebraska', 'Beef State','someClass'],
//			['NV', 'Nevada', 'Silver State','someClass'],
//			['NH', 'New Hampshire', 'Granite State','someClass'],
//			['NJ', 'New Jersey', 'Garden State','someClass'],
//			['NM', 'New Mexico', 'Land of Enchantment','someClass'],
//			['NY', 'New York', 'Empire State','someClass'],
//			['NC', 'North Carolina', 'First in Freedom','someClass'],
//			['ND', 'North Dakota', 'Peace Garden State','someClass'],
//			['OH', 'Ohio', 'The Heart of it All','someClass'],
//			['OK', 'Oklahoma', 'Oklahoma is OK','someClass'],
//			['OR', 'Oregon', 'Pacific Wonderland','someClass'],
//			['PA', 'Pennsylvania', 'Keystone State','someClass'],
//			['RI', 'Rhode Island', 'Ocean State','someClass'],
//			['SC', 'South Carolina', 'Nothing Could be Finer','someClass'],
//			['SD', 'South Dakota', 'Great Faces, Great Places','someClass'],
//			['TN', 'Tennessee', 'Volunteer State','someClass'],
//			['TX', 'Texas', 'Lone Star State','someClass'],
//			['UT', 'Utah', 'Salt Lake State','someClass'],
//			['VT', 'Vermont', 'Green Mountain State','someClass'],
//			['VA', 'Virginia', 'Mother of States','someClass'],
//			['WA', 'Washington', 'Green Tree State','someClass'],
//			['WV', 'West Virginia', 'Mountain State','someClass'],
//			['WI', 'Wisconsin', "America's Dairyland",'someClass'],
//			['WY', 'Wyoming', 'Like No Place on Earth','someClass']
//		];
//
//        var states = new Ext.data.SimpleStore({
//            fields: ['abbr', 'state', 'nick', 'cls'],
//            data: Ext.exampledata.states,
//            sortInfo: {field: 'state', direction: 'ASC'}
//        });
//		this.store=states;

		RL.PriceSearch.VendorFilter.superclass.initComponent.call(this);

	},

    onRender:function(ct, position) {
		

		//categoryField: "SFILTER#CATEGORY",
		//displayField: "SFILTER#QUALNAME",
		//valueField:"SFILTER#QUALCODE",

		
        RL.PriceSearch.VendorFilter.superclass.onRender.call(this, ct, position);
		
		this.triggerBtn=Ext.fly(this.container.dom.parentNode).child('div.'+this.clsTrigger);
		if (!this.triggerBtn) return Ext.jx.debug('missing trigger btn');
		
    	this.triggerBtn.on('click',function(e){
    		e.stopEvent();
    		if(this.disabled){
    			return;
    		}
    		if(this.isExpanded()){
    			this.multiSelectMode = false;
    		}else if(this.pinList){
    			this.multiSelectMode = true;
    		}
    		this.onTriggerClick();
    	},this);

	},
    onDestroy : function() {

		RL.PriceSearch.VendorFilter.superclass.onDestroy.call(this);
		
		if (this.triggerBtn){
			this.triggerBtn.removeAllListeners();
		}
	}	
	
});

Ext.reg('vendorfilter', RL.PriceSearch.VendorFilter);

Ext.ns('RL.PriceSearch');


RL.PriceSearch.VendorFilters = Ext.extend(Ext.form.FieldSet, {

	productTypeField: 'SFILTER#VENTYPE',	
	categoryField: 'SFILTER#CATEGORY',
	displayField: 'SFILTER#QUALNAME',
	valueField: 'SFILTER#QUALCODE',
	valueField2: 'SFILTER#TYPE',
	
	constructor : function(config) {
		
		Ext.apply(config, {
			
			dataIndex: '#VENDOR_FILTERS',
			layout:'triggerform',			
			title: 'Filters',
			labelAlign:'top',
			width:175,
			collapsible: true,
			collapsed:false,
			items:[{
				xtype: 'vendor_selector',
				name:"#VENDOR_SEARCH",
				width:153,
				
				listeners: {
					change: this.onChangeField,
					scope: this
				}
				
			}]
		});
		
		RL.PriceSearch.VendorFilters.superclass.constructor.call(this, config);
	},

	initComponent : function(){
		RL.PriceSearch.VendorFilters.superclass.initComponent.apply(this, arguments);
		this.initComponentDeferred.defer(1, this); //it is deferred so that ownerCt has time to get populated
	},
	
	initComponentDeferred : function(){ //it is deferred so that ownerCt has time to get populated

		var formProduct = this.findParentBy(function(item){ return !!item.recordProduct });
		var recordProduct = formProduct.recordProduct;
		var formProductType=recordProduct.get('SERVICE#CODE');
		
		if (recordProduct.get('SERVICE#CONFILTERS')!=1){ //the product type website show toggle must be on
			this.on('beforerender', function(){
				return false;
			});
			return;
		}

		this.categories = {};
		this.categoryNames = [];

		if (RL.Global.productSupports(recordProduct,'golf')){ //otherwise it will get hidden
			
		}else{
		
			this.store=Ext.jx.getStore("SFILTER");
			
			for (var i = 0, it = this.store.data.items, l = it.length; i < l; i++) {
				var row=it[i].data, cat = row[this.categoryField];
				var rowProductType=row[this.productTypeField];
				if (formProductType !== rowProductType && rowProductType) continue;
				
				if (!this.categories[cat]) {
					this.categoryNames.push(cat);
					this.categories[cat] = [];
				}
				
				this.categories[cat].push([
					[row[this.valueField2] || ' ',row[this.valueField]].join(''),
					row[this.displayField]
				]);
			}
	
			var newItems=[];
			for (var i = 0, l = this.categoryNames.length; i < l; i++) {
				var cat=this.categoryNames[i], newRows=this.categories[cat];
				
				this.add({
					xtype:'vendorfilter',
					
					fieldLabel: cat,
					valueField: 'id',
					displayField: 'display',
					emptyText: cat,
					
					store: new Ext.data.ArrayStore({
						fields: ['id','display'],
						data: newRows
					}),
					
					listeners: {
						change: this.onChangeField,
						scope: this
					}
					
				});			
			}
		}
		
		if (!this.categoryNames.length) {			
			//formProduct.slots.tabWest.setWidth(100); //this is not necessary now because the skip button is there
			this.addClass('x-hidden');
		}else{
			//formProduct.slots.tabWest.setWidth(150);			
		}
		
		
	},
	
	getValue:function() {
		//var values=this.getValues();
		var values=[]; 
		for (var i = 0, it = this.items, l = it.length; i < l; i++) {
			var item=it.items[i];
			values=values.concat(item.getValue().split(','));			
		}
		return values.join('');
	},
	onChangeField:function(){

		var formProduct = this.findParentBy(function(item){ return !!item.recordProduct });		
		if (formProduct.onChangeField) formProduct.onChangeField();

		
	},
	
	
    onRender:function(ct, position) {
        RL.PriceSearch.VendorFilters.superclass.onRender.call(this, ct, position);
 
	},		
	
	onDestroy : function(){
		//this.dataControl.un('changevalue', this.onChangeValue, this);
		//this.record.un('update', this.onRecordUpdate, this);
		
		RL.PriceSearch.VendorFilters.superclass.onDestroy.call(this);
	}
	//,
	
	

});

Ext.reg('vendorfilters', RL.PriceSearch.VendorFilters);

Ext.ns('RL.form');


RL.form.ChooseResortComboBox = Ext.extend(Ext.form.ComboBoxQuickChange, {
	
	name: 'GTAW#RESORT',
	
	fieldLabel: 'Destination',
	width: 200,
	listWidth: 600,
	
	displayField: 'RESORT#RESORT',
	valueField: 'RESORT#SEARCHCODE',
	
	onViewClick: function(doFocus) {
		var index = this.view.getSelectedIndexes()[0];
		var r = Ext.jx.Template.findSearchItem("resortDropdown", index);
		if (r) {
			this.onSelect(r, index);
		}
		if (doFocus !== false) {
			this.el.focus();
		}
	},
	
	findRecord: function(prop, value) {
		var record;
		var store = Ext.jx.getStore("RESORT", "ALL");
		if (store.getCount() > 0) {
			store.each(function(r) {
				if (r.data[prop] == value) {
					record = r;
					return false;
				}
			});
		}
		return record;
	},
	
	typeAhead: true,
	mode: 'local',
	triggerAction: 'all',
	
	emptyText: 'Choose a destination',
	allowBlank: false,
	
	selectOnFocus: true,
	
	listeners: {
		render: function() {},
		
		beforerender: function() { //	this.store.sort('RESORT#RESORT');
			var defaultDest = RL.Global.getDefaultDestCode();
			if (defaultDest) {
				this.setValue(defaultDest); 
				Ext.jx.setStoreValue("GTAW#RESORT",defaultDest);								
				this.hideItem();
				return;
			}
			this.store = Ext.jx.getStore("SUPERDES");
			this.tpl = new Ext.XTemplate(Ext.jx.getTable("SUPERDES").templates.dests);
			this.itemSelector = 'div.search-item';
		}
	}
});

Ext.reg('choose_resort_combo', RL.form.ChooseResortComboBox);
Ext.ns('RL.form.ChooseResortComboBox');


RL.form.ChooseResortComboBox.Detail = Ext.extend(Ext.Panel, {
	
	slots : true,
	
	constructor : function(config) {
		config = config || {};
		
		Ext.apply(config, {
			autoEl : 'div',
			
			layout : 'columnfit',
			
			items : [
				{
					xtype : 'container',
					autoEl : 'div',
					
					slot : 'grouped_to_master',
					width : 30,
					
					cls : 'rs-super-dest-to-master'
				},
				{
					xtype : 'dataview',
					slot : 'grouped_detail_view',
					
					columnWidth : 1,
					
					store : new Ext.data.Store(),
					tpl : new Ext.XTemplate([
						'{[ Ext.jx.Template.clearSearchItems("subDestsDetail") ]}',
						'<tpl for=".">',
							'<div class="rs-sub-dest-title">',
								'{[xindex == 1 ? values._record.getSuperDestRecord().getName() : ""]}',
							'</div>',
							'<div class="rs-sub-dest-wrp">',
								'{[',
									'Ext.jx.Template.setSearchItem("subDestsDetail",values._record)+',
									'"<div class=\'search-item\' recordId=\'"+values._record.get("#LINK_TO_RESORT")+"\'>"+',
										'values._record.template("shortcleandesc")+',
									'"</div>"',
								']}',
							'</div>',
						'</tpl>'
					]),
					itemSelector : 'div.rs-sub-dest-wrp',
					
					singleSelect: true,
        			overClass: 'rs-super-dest-hover',
					
					//style : 'overflow-y:auto;overflow-x:hidden;'
					style : {
						'overflow-y':'auto',
						'overflow-x':'hidden'
					}
					
				}
			]
		}); //eof apply
		
		this.addEvents('resort_choosed', 'back');
		
		RL.form.ChooseResortComboBox.Detail.superclass.constructor.call(this, config);
	},
	
	
	initComponent : function() {
		RL.form.ChooseResortComboBox.Detail.superclass.initComponent.call(this);
		
		this.slots.grouped_to_master.on('render', function(comp){
			var el = comp.el;
			
			el.on('click', function(){
				this.fireEvent('back', this);
			}, this);
			
			el.on('mouseover', function(){
				el.addClass('rs-super-dest-hover');
			});
			
			el.on('mouseout', function(){
				el.removeClass('rs-super-dest-hover');
			});
		}, this); 
		
		this.slots.grouped_to_master.on('render', function(comp) {
			Ext.QuickTips.register({
				target: comp.el,
				title: 'Back to groups',
				text: 'Back to groups',
				width: 100,
//				dismissDelay: 20,
				trackMouse : true
			});		
		}, this);
		
		
		this.slots.grouped_detail_view.on('click', this.onDetailListClick, this);
		
		
	},
	
	
	setSuperDest : function(superDestRecord){
		var slots = this.slots;		
		var detail = slots.grouped_detail_view;
		
		var resortsStore = new Ext.data.Store();
		
		superDestRecord.getDests().each(function(item){
			resortsStore.add(item.copy());
		});
		
		detail.setStore(resortsStore);
		if (detail.rendered) detail.refresh();
	},
	
	
	onDetailListClick : function(view, index, node){
		var resortRecord = Ext.jx.Template.findSearchItem("subDestsDetail", index);
		if (!resortRecord) throw "Resort record not found";
		
		this.fireEvent('resort_choosed', this, resortRecord);
	}
	
});

Ext.reg('choose_resort_detail', RL.form.ChooseResortComboBox.Detail);
Ext.ns('RL.form.ChooseResortComboBox');


RL.form.ChooseResortComboBox.SimpleView = Ext.extend(Ext.Panel, {
	
	slots : true,
	
	constructor : function(config) {
		config = config || {};
		
		Ext.apply(config, {
			title : 'List',
			
			layout : 'fit',
			
			items : [
				{
					xtype : 'dataview',
					slot : 'list',
					
					store : Ext.jx.getStore("SUPERDES", "ALL"),
					tpl : new Ext.XTemplate(Ext.jx.getTable("SUPERDES").templates.dests),
					itemSelector : 'div.search-item',
					
					singleSelect: true,
        			overClass: 'rs-search-item-hover',
					
					style : {
						'overflow-y':'auto',
						'overflow-x':'hidden'
					}
				}
			]
		});
		
		this.addEvents('resort_choosed');

		RL.form.ChooseResortComboBox.SimpleView.superclass.constructor.call(this, config);
	},
	
	
	initComponent : function() {
		RL.form.ChooseResortComboBox.SimpleView.superclass.initComponent.call(this);
		
		this.slots.list.on('click', this.onSimpleListViewClick, this);
	},
	
	
	onSimpleListViewClick: function(view, index, node) {
		var resortRecord = Ext.jx.Template.findSearchItem("resortDropdown", index);
		if (!resortRecord) throw "Resort record not found";
		
		this.fireEvent('resort_choosed', this, resortRecord);
	}
	
});

Ext.reg('choose_resort_simple', RL.form.ChooseResortComboBox.SimpleView);
Ext.ns('RL.form.ChooseResortComboBox');


RL.form.ChooseResortComboBox.GroupedView = Ext.extend(Ext.Panel, {

	slots : true,


	constructor : function(config) {
		config = config || {};

		Ext.apply(config, {
			title : 'Regions',

			layout : 'slide',
			activeItem : 0,

			items : [
				//master card )
				{
					xtype : 'dataview',
					slot : 'grouped_master',

					store : Ext.jx.getStore("SUPERDES", "ALL"),
					tpl : new Ext.XTemplate([
						'{[ Ext.jx.Template.clearSearchItems("superDestsMaster") ]}',
						'<tpl for=".">',
							'{[ values._record.getDests().items.length ? Ext.jx.Template.setSearchItem("superDestsMaster", values._record) : ""]}',
							'{[ !values._record.getDests().items.length ? "" : ',
								'"<div class=rs-super-dest-wrp>',
									'<div class=\'rs-super-dest-to-detail\'>',
									'</div>',
									'<div class=\'rs-super-dest\'>"+',
										'values._record.getImageHtml(1,"TN_")+',
										'values._record.getName("bold")+',
									'"</div>',
									'<div class=\'x-clear\'></div>',
								'</div>"',
							 ']}',
						'</tpl>'
					]),
					itemSelector : 'div.rs-super-dest-wrp',

					singleSelect: true,
        			overClass: 'rs-super-dest-hover',

					style : {
						'overflow-y':'auto',
						'overflow-x':'hidden'
					}
				},
				//eof master card )

				//detail card
				{
					xtype : 'choose_resort_detail',
					slot : 'grouped_detail',

					listeners : {
						back : this.onGroupedBack,
						resort_choosed : this.onResortChoosed,
						scope : this
					}
				}
				//eof detail card
			]
		});

		this.addEvents('resort_choosed');

		RL.form.ChooseResortComboBox.GroupedView.superclass.constructor.call(this, config);
	},


	initComponent : function() {
		RL.form.ChooseResortComboBox.GroupedView.superclass.initComponent.call(this);

		this.slots.grouped_master.on('click', this.onMasterListClick, this);
	},


	onResortChoosed : function(comp, record){
		this.fireEvent('resort_choosed', this, record);
	},


	onGroupedBack : function(){
		this.layout.setActiveItem(this.slots.grouped_master);
	},


	onMasterListClick : function(view, index, node){
		var superDestRecord = Ext.jx.Template.findSearchItem("superDestsMaster", index);
		if (!superDestRecord) throw "Super destination record not found";

		var slots = this.slots;
		slots.grouped_detail.setSuperDest(superDestRecord);

		this.layout.setActiveItem(slots.grouped_detail);
	}

});

Ext.reg('choose_resort_groupedview', RL.form.ChooseResortComboBox.GroupedView);

Ext.ns('RL.form.ChooseResortComboBox');


RL.form.ChooseResortComboBox.MapView = Ext.extend(Ext.Panel, {
	
	slots : true,
	
	//html chunk with map <img> and <map> tags (should not contain 'name' attribute)
	mapHtml : null,
	//style : 'overflow:auto;',
	
	//regex to extract the superdest code from 'href' attribute of <area> tags in map (should be 1st matched group)
	//backslashes should be doubled
	supDesRegexStr : '-superdest-(\\w\\w)-.htm',
	
	constructor : function(config) {
		config = config || {};
		
		Ext.apply(config, {
			title : 'Map View',
			slot : 'mapview',
			
			layout : 'slide',
			activeItem : 0,
			//style : 'overflow-y:auto;overflow-x:hidden;',
			
			items : [
				//master card )
				{
					slot : 'map',
					
					//to provide 'afterlayout' event
					layout : 'auto',
					
					border : false,
					style : {
						'text-align':'center',
						'overflow-y':'auto',
						'overflow-x':'hidden'
					},
					//style : 'overflow-y:auto;overflow-x:hidden;',
					//autoHeight:true,
					html : config.mapHtml
//					html : '<img width="329" height="455" border="0" src="../resources/images/map.gif"/>\
//						<map>\
//				  			<area href="http://www.skithewest.com/-superdest-ZC-.htm" coords="8,2,13,18,23,18,28,29,29,54,36,67,24,81,25,89,19,95,20,102,24,102,28,115,33,116,27,123,28,130,35,138,42,141,41,149,56,161,106,176,139,181,156,56,101,44,29,7,13,2" shape="poly"/>\
//					  		<area href="http://www.skithewest.com/-superdest-ID-.htm" coords="93,173,87,203,87,212,81,225,82,229,79,237,77,253,124,263,127,230,122,231,113,229,107,218,102,216,106,212,101,202,98,189,102,177" shape="poly"/>\
//						  	<area href="http://www.skithewest.com/-superdest-WY-.htm" coords="129,229,124,273,183,276,184,232" shape="poly"/>\
//						  	<area href="http://www.skithewest.com/-superdest-LT-.htm" coords="19,239,51,249,45,282,83,338,84,347,78,360,79,364,77,367,56,365,54,352,28,334,30,326,21,308,24,305,20,294,27,287,21,290,15,279,13,265,13,256" shape="poly"/>\
//						  	<area href="http://www.skithewest.com/-superdest-LT-.htm" coords="53,249,100,259,89,326,84,323,84,335,47,282" shape="poly"/>\
//						  	<area href="http://www.skithewest.com/-superdest-UT-.htm" coords="100,259,92,316,137,322,139,276,123,275,124,264" shape="poly"/>\
//						  	<area href="http://www.skithewest.com/-superdest-CO-.htm" coords="140,275,138,320,198,325,198,280" shape="poly"/>\
//						  	<area href="http://www.skithewest.com/-superdest-NM-.htm" coords="137,323,130,389,136,389,138,382,154,385,155,381,188,382,190,327" shape="poly"/>\
//						  	<area href="http://www.skithewest.com/-superdest-MT-.htm" coords="107,177,144,183,186,184,184,231,136,227,127,230,113,230,109,220,105,217,107,213,102,198,99,190,103,176" shape="poly"/>\
//						</map>'
				},
				//eof master card )
				
				//detail card
				{
					xtype : 'choose_resort_detail',
					slot : 'mapview_detail',
					
					listeners : {
						back : this.onMapViewBack,
						resort_choosed : this.onResortChoosed,
						scope : this
					}
				}
				//eof detail card
			]
			
		});
		
		this.addEvents('resort_choosed');
		
		RL.form.ChooseResortComboBox.MapView.superclass.constructor.call(this, config);
	},
	
	
	initComponent : function() {
		RL.form.ChooseResortComboBox.MapView.superclass.initComponent.call(this);
		
		this.slots.map.on('afterlayout', this.setupMap, this, { single : true });
	},
	
	
	onResortChoosed : function(comp, record){
		this.fireEvent('resort_choosed', this, record);
	},
	
	
	onMapViewBack : function(){
		this.layout.setActiveItem(this.slots.map);
	},
	
	
	setupMap : function(panel) {
		//panel.setHeight(200);
		var el = panel.el;
        //panel.body.setHeight(200); 
        panel.body.setOverflow('auto'); 
		
		var image = el.child('img');
		var map = el.child('map');
		
		map.set({ name : map.id });
		//useMap is case-sensitive for IE
		image.set({ useMap : '#' + map.id });
				
		el.select('area', true).each(function(areaEl){
			areaEl.on('click', function(e){
				e.preventDefault();
				
				var slots = this.slots;
				
				var superDests = Ext.jx.getStore("SUPERDES");
				
				var supDesRegex = new RegExp(this.supDesRegexStr, 'gi');

				var code=supDesRegex.exec(areaEl.dom.href)[1];
				
				slots.mapview_detail.setSuperDest(superDests.query('SUPERDES#CODE', code).itemAt(0));
				
				this.layout.setActiveItem(slots.mapview_detail);
			}, this);
		}, this);
	}
	
	
});

Ext.reg('choose_resort_mapview', RL.form.ChooseResortComboBox.MapView);
Ext.ns('RL.form.ChooseResortComboBox');


RL.form.ChooseResortComboBox.Intelligent = Ext.extend(Ext.form.ComboBox.Container, {

	displayField: 'RESORT#RESORT',
	valueField: 'RESORT#SEARCHCODE',

	fieldLabel: 'Destination',
	width: 150,
	listWidth: 500,

	emptyText: 'Choose a destination',
	//allowBlank: false,

	selectOnFocus: true,
	typeAhead : true,
	typeAheadDelay : 350,
	mode : 'local',

	//tabsHeight : 500,
	tabsEnabled : [ 'grouped' ], //possibilities [ 'simple', 'grouped', 'map' ],

	//html chunk with map <img> and <map> tags (should not contain 'name' attribute)
	mapHtml : null,

	supDesRegex : null,

	constructor : function(config) {
		config = config || {};

		Ext.apply(this, config);

		if (RL.Global.getSuperDests().length < 2) this.tabsEnabled=['simple'];

		if (Ext.jx.getStoreValue("DEPT#CONDESMAPH")){
			if (!Ext.jx.getStoreValue("DEPT#CONDESMAPR")) Ext.jx.setStoreValue("DEPT#CONDESMAPR", "-superdest-(\\w\\w)-.htm");
			this.tabsEnabled.push ('map');
		}

		//if (RL.Defaults.CHOOSE_RESORT_TABS) this.tabsEnabled = RL.Defaults.CHOOSE_RESORT_TABS;

		var tabs = {};
		Ext.each(this.tabsEnabled, function(viewMode) { tabs[viewMode] = true })

		var tabComponents = []
		
		if (tabs.simple) tabComponents.push({
			xtype : 'choose_resort_simple',
			listeners : {
				resort_choosed : this.onResortChoosed,
				scope : this
			}
		});

		//Simple super destinations listing (grouped)
		if (tabs.grouped) tabComponents.push({
			xtype : 'choose_resort_groupedview',

			listeners : {
				resort_choosed : this.onResortChoosed,
				scope : this
			}
		});

		//Map View
		if (tabs.map) tabComponents.push({
			xtype : 'choose_resort_mapview',

			mapHtml : this.mapHtml || Ext.jx.getStoreValue("DEPT#CONDESMAPH"),
			supDesRegex : this.supDesRegexStr || Ext.jx.getStoreValue("DEPT#CONDESMAPR"),
			listeners : {
				resort_choosed : this.onResortChoosed,
				scope : this
			}
		});
		
		if (tabComponents.length > 1)
			this.embedd = new Ext.ux.TabPanel.Slideable({
				slots : true,
	
			 	layoutOnTabChange : true,
	
				activeTab : 0,
				
				items : tabComponents
			})
		else {
			tabComponents[0].header = false
			
			this.embedd = new Ext.Container({
				slots : true,
				layout : 'fit',
	
				items : tabComponents
			})
		}
		

		RL.form.ChooseResortComboBox.Intelligent.superclass.constructor.call(this, config);
	},


	initComponent : function() {
		RL.form.ChooseResortComboBox.Intelligent.superclass.initComponent.call(this);

		var resorts = Ext.jx.getStore("RESORT", "ALL");

		//creating a copy of RESORT to safely apply filters on it
		this.store = new Ext.data.Store();
		resorts.each(function(record){
			this.store.add(record.copy());
		}, this);

	},


	onResortChoosed : function(comp, record){
		this.store.clearFilter();
		this.onSelect(record);
	},


    //fix to fire early 'change' event
    onTypeAhead : function(){
        if(this.store.getCount() > 0){
        	var prevValue = this.getValue();

            var r = this.store.getAt(0);
            var newValue = r.data[this.displayField];
            var len = newValue.length;
            var selStart = this.getRawValue().length;
            if(selStart != len){
                this.setValue(r.data[this.valueField]);

                this.fireEvent('change', this, r.data[this.valueField], prevValue);

                this.selectText(selStart, newValue.length);
            }
        }
    }


});

Ext.reg('choose_resort_intell', RL.form.ChooseResortComboBox.Intelligent);

Ext.ns('RL.Quote');


RL.Quote.Summary = Ext.extend(Ext.Panel, {

	slots 					: true,

	tripType 				: null,

	//XXX model obj (was RL.Quote) 
	quote					: null,


	constructor : function (config) {
		config = config || {}

		Ext.apply(config, {

			baseCls		: 'x-services-bubble',

			bodyStyle : {
				'overflow-y':'auto',
				'overflow-x':'hidden',

				padding: '0px 5px 15px 10px',
				position : 'relative'
			},

			frame	: true,

			items : [
				RL.Defaults.DEV_MODE ? {
					xtype 	: 'RL.Quote.Summary.LoginLine',
					slot	: 'login'
				} : {
					xtype : 'container',
					slot : 'login',
					refresh : function () {}
				},
				{
					xtype 	: 'RL.Quote.Summary.Header',
					slot	: 'header',

					tripType	: config.tripType
				},
				{
					xtype : "buttongroup",

					columns : 2,
					//autoWidth : true,
					baseCls : 'x-frameless',

					items : [
						{
							xtype : 'button',
							slot : 'finalizeButton',

							name : 'finalBtn',

							iconCls : 'final-btn',

							text : 'finalize',
							scale : 'large',
							iconAlign : 'left',

							handler : this.onFinalizeQuote,
							scope : this
						},
						{
							xtype : 'button',
							slot : 'startOverButton',

							name:'startOverBtn',
							iconCls:'startover-btn',

							text: 'start over',
							scale: 'large',
							iconAlign: 'left',

							handler: this.onStartQuoteOver,
							scope : this
						}
					]
				},
				{
					xtype 	: 'RL.Quote.Summary.Footer',
					slot	: 'footer'
				},

				{
					xtype : 'container',
					slot : 'detailsContainer',

					layout : "card",

					baseCls: 'x-frameless',
					hideBorders : true,

					items : [
						{
							xtype : 'RL.Quote.Summary.Destination',
							slot : 'single',

							header : false,

							autoHeight : true,
							autoWidth : true,

							destPosition 	: 0
						},
						{
							xtype : 'RL.Quote.Summary.Multiple',
							slot : 'multi',

							autoHeight : true,
							autoWidth : true
						}
					]
				}
			]
		})


		this.addEvents('quote-finalize', 'quote-startover')
		this.enableBubble('quote-finalize', 'quote-startover')

		RL.Quote.Summary.superclass.constructor.call(this, config)
	},


	initComponent : function () {
		RL.Quote.Summary.superclass.initComponent.call(this)
		
		var slots = this.slots

		slots.detailsContainer.activeItem = slots[this.tripType]

		this.on('afterLayout', this.onAfterLayout, this, { single : true })

		var login = slots.login
		
		if (login) {
			login.on('show-login', this.onShowLogin, this)
			login.on('show-account', this.onShowAccount, this)
		}

		//subscribing to the 'login-success' event of user
		if (RL.Global.user) RL.Global.user.on('login-success', this.onUserLogedIn, this)
		
		this.quote.on('change', this.refresh, this)
	},
	
	
	destroy : function () {
		if (RL.Global.user) RL.Global.user.un('login-success', this.onUserLogedIn, this)
		
		this.quote.un('change', this.refresh, this)
		
		RL.Quote.Summary.superclass.destroy.call(this)
	},


	onUserLogedIn : function () {
		this.refresh()
	},


	onShowLogin : function (loginLine) {
		var loginPopup = new RL.Login.Popup({
			returnTrips : true
		})

		loginPopup.show(loginLine.el)
	},


	onShowAccount : function () {
		RL.Global.showUserAccount()
	},


	onFinalizeQuote : function () {
		this.fireEvent('quote-finalize')
	},


	onStartQuoteOver : function() {
		this.fireEvent('quote-startover')
	},


	switchType : function (tripType) {
		this.tripType = tripType
		this.slots.header.tripType = tripType

		this.slots.detailsContainer.layout.setActiveItem(this.slots[tripType])

		this.refresh()
	},


	onAfterLayout : function () {
		this.body.on('click', this.onBodyClick, this, { delay : 100 })

		this.refresh()
	},


	onBodyClick : function (event) {
		var delButton = event.getTarget('.del_btn')

		if (delButton) this.quote.removeBuildRecord(delButton.getAttribute('recordId'))
		
		var editButtonEl 	= event.getTarget('.edit_btn')
		
		if (editButtonEl) {
			
			var buildStore 		= Ext.jx.getStore('BUILD')
			var buildRecord 	= buildStore.getById(editButtonEl.getAttribute('recordId'))
			
			var editItemPopup = new RL.Build.Edit({
				quote			: this.quote,
				buildRecord 	: buildRecord
			})
			
			editItemPopup.show(editButtonEl)
		}
	},
	

	refresh : function () {
		var quoteProblems 		= this.quote.getQuoteProblems()
		var slots 				= this.slots

		this.refreshButtonsStates(quoteProblems)

		if (slots.login) slots.login.refresh()
		slots.header.refresh(quoteProblems)
		slots.footer.refresh(quoteProblems)

		var detailsContainer = slots.detailsContainer

		if (detailsContainer.rendered) {
			var summaryDetails = detailsContainer.layout.activeItem

			if (this.tripType == 'single') summaryDetails.destCode = Ext.jx.getStore('GTAW').getAt(0).get('GTAW#RESORT')

			summaryDetails.refresh(quoteProblems)
		}
	},
	
	
	refreshButtonsStates : function (quoteProblems) {
		var slots 				= this.slots

		if (quoteProblems)
			slots.finalizeButton.disable()
		else
			slots.finalizeButton.enable()
	},


	collapseDestinationSegment : function (destPosition, destCode) {
		if (this.tripType != 'multi') throw "Can't collapse destination segment in single destination mode"

		this.slots.multi.collapseDestinationSegment(destPosition, destCode)
	},


	expandDestinationSegment : function (destPosition, destCode) {
		if (this.tripType != 'multi') throw "Can't expand destination segment in single destination mode"

		this.slots.multi.expandDestinationSegment(destPosition, destCode)
	}


})

Ext.reg('rl-quote-summary', RL.Quote.Summary)

Ext.ns('RL.Quote.Summary');


RL.Quote.Summary.Destination = Ext.extend(Ext.Panel, {

	slots 						: true,

	destPosition				: null,
	destCode					: null,

	lastHTML					: null,


    expandDefaults				: {
        duration : 0.5
    },

    collapseDefaults 			: {
        duration : 0.5
    },

    cls							: "trip_details_review",
    


    constructor : function (config) {
		config = config || {}

		Ext.apply(config, {
		})

		RL.Quote.Summary.Destination.superclass.constructor.call(this, config)
	},



	initComponent : function () {
		RL.Quote.Summary.Destination.superclass.initComponent.call(this)
	},



	onRender : function () {
		RL.Quote.Summary.Destination.superclass.onRender.apply(this, arguments)

		this.refresh()
	},



	refresh : function () {
		if (!this.rendered) return

		var destRecord = Ext.jx.getStore("RESORT").data.map[ 'RESORT#SEARCHCODE=' + this.destCode ]

		if (destRecord) this.setTitle(destRecord.getName())

		var oldHTML = this.lastHTML
		this.lastHTML = this.getHTML()

		if (this.lastHTML != oldHTML) {
			this.body.update(this.lastHTML)

			this.body.highlight()
		}
	},



	getHTML : function () {
		var gtawRecord 		= Ext.jx.getStore('GTAW').getAt(0)
		var buildStore 		= Ext.jx.getStore('BUILD')

		var html			= []

		var destSeg			= this.destPosition + ':' + this.destCode

		buildStore.each(function (buildRecord) {

			var buildDestSeg = buildRecord.get('BUILD#DESTSEG')
			
			if (buildDestSeg && buildDestSeg != destSeg) return

			var recordProduct 		= buildRecord.getService()
			if (!recordProduct) return
			
			var recordVendor		= buildRecord.getVendor()
			var fromDate			= RL.Global.prettyDate(buildRecord.get('BUILD#DDATE'))
			var toDate				= RL.Global.prettyDate(buildRecord.get('BUILD#RDATE'))

			//the product type website show toggle must be on
			var showItemPrice		= recordProduct.isGDSAir() || recordProduct.get('SERVICE#CONPRICEOV') == 1 || (recordProduct.get('SERVICE#CONPRICEOV') != 2 && Ext.jx.getStoreValue("DEPT#CONPRICES") == 3)

			html.push(
				'<div class="selected">', recordProduct.data['SERVICE#DESCRIP'], '</div>',
				'<div class="service-items-date">', fromDate, ' to ', toDate, '</div>',
				'<div class="service-items-ttl">', buildRecord.data['VENDOR#VENDOR'], '</div>',
				buildRecord.data['#UNIT_DESC'] ? '<div class="service-items-desc">' + buildRecord.data['BUILD#UNITS'] + ': ' + buildRecord.data['#UNIT_DESC'] + '</div>' : ''
			)

			if (recordProduct.isGDSAir() ) {
				if (!RL.Global.airDisplayTpl) RL.Global.airDisplayTpl = new Ext.XTemplate(Ext.jx.getTable("_VENDOR_PRICING").templates.gdsair_line_compressed)

				//XXX need to update the width?
				//eastDetails.width=270;

				html.push(
					'<div class="service-items-desc">',
						RL.Global.airDisplayTpl.applyTemplate(buildRecord.data),
					'</div>'
				)
			}


			if (showItemPrice)
				html.push(
					'<div class="service-items-price">',
						'<div class="edit_btn" recordId="', buildRecord.id, '"><span>edit</span></div>',
						'<div class="del_btn" recordId="', buildRecord.id, '"><span>delete</span></div>',
						'<div class="x-clear"></div>', 
						'<div class="item-price">', buildRecord.get('BUILD#UNITS'), ' @ ', buildRecord.getNicePrice(), ' = ', buildRecord.getNiceTotalPrice(), '</div>',
					'</div>'
				)
			else
				html.push(
					'<div class="service-items-price">',
						'<div class="edit_btn" recordId="', buildRecord.id, '"><span>edit</span></div>',
						'<div class="del_btn" recordId="',buildRecord.id,'"><span>delete</span></div>',
					'</div>'
				)

		}, this)

		return html.join('')
	}

})


Ext.reg('RL.Quote.Summary.Destination', RL.Quote.Summary.Destination)

Ext.ns('RL.Quote');


RL.Quote.Summary.Multiple = Ext.extend(Ext.Container, {
	
	slots 					: true,
	
	destinationXType		: 'RL.Quote.Summary.Destination',
	
	
	constructor : function (config) {
		config = config || {}
		
		Ext.apply(config, {
			
		})
		
		
		RL.Quote.Summary.Multiple.superclass.constructor.call(this, config)
	},

	
	initComponent : function () {
		RL.Quote.Summary.Multiple.superclass.initComponent.apply(this, arguments)
		
		this.synchronize()
	},
	
	
	synchronize : function () {
		var buildStore 			= Ext.jx.getStore('BUILD')
		var processedSegments 	= {}
		
		
		buildStore.each(function (buildRecord) {
			
			var destSeg = buildRecord.get('BUILD#DESTSEG')
			
			
			if (!destSeg || processedSegments[destSeg]) return
			
			processedSegments[destSeg] = true
			
			var match = /(\d+):(.+)/.exec(destSeg)
			
			if (!this.slots[destSeg]) this.add({
				xtype : this.destinationXType,
				
				slot : destSeg,
				
				destCode : match[2],
				destPosition : match[1],
				
				collapsible : true
			})
			
		}, this)
		
		
		Ext.jx.each(this.slots, function (destinationComp, slot) {
			
			if (!processedSegments[slot]) this.remove(destinationComp)
		}, this)
	},
	
	
	refresh : function () {
		this.synchronize()
		
		Ext.jx.each(this.slots, function (destinationComp, slot) {
			destinationComp.refresh()
		}, this)
		
		this.doLayout()
	},
	
	
	collapseDestinationSegment : function (destPosition, destCode) {
		var destSeg = destPosition + ':' + destCode
		
		var segment = this.slots[destSeg]
		
		if (segment) segment.collapse({
			callback : function () {
				this.ownerCt.doLayout()
			},
			scope : this
		})
	},
	
	
	expandDestinationSegment : function (destPosition, destCode) {
		var destSeg = destPosition + ':' + destCode
		
		var segment = this.slots[destSeg]
		
		if (segment) segment.expand({
			callback : function () {
				this.ownerCt.doLayout()
			},
			scope : this
		})
	}
	
	

})


Ext.reg('RL.Quote.Summary.Multiple', RL.Quote.Summary.Multiple)
Ext.ns('RL.Quote');


RL.Quote.Summary.Footer = Ext.extend(Ext.Container, {

	slots 					: true,


	hidePriceReason			: null,


	constructor : function (config) {
		config = config || {}

		Ext.apply(config, {
			cls : "trip_details_main"
		})


		RL.Quote.Summary.Footer.superclass.constructor.call(this, config)
	},


	initComponent : function () {
		RL.Quote.Summary.Footer.superclass.initComponent.call(this)
	},


	onRender : function () {
		RL.Quote.Summary.Footer.superclass.onRender.apply(this, arguments)

		this.refresh(this.hidePriceReason)
	},


	refresh : function (hidePriceReason) {
		if (!this.rendered) return

		this.el.update(this.getHTML(hidePriceReason))
	},


	getHTML : function (hidePriceReason) {

		var gtawRecord 		= Ext.jx.getStore('GTAW').getAt(0)

		var showPricesRule 	= Ext.jx.getStoreValue("DEPT#CONTRIPPRI") == 0
		var showPrices		= gtawRecord.get('GTAW#PPPRICE') && showPricesRule && !hidePriceReason

		var html			= []

		if (showPrices) html.push(
			'<div><b><i>all prices are in ' + Ext.jx.getStoreValue('GTAW#CADCURR') + ' and are approximated until final quote</b></i></div>'
		)

		if (hidePriceReason) html.push(
			'<div><i>', hidePriceReason, '</i></div>'
		)

		return html.join('')
	}

})

Ext.reg('RL.Quote.Summary.Footer', RL.Quote.Summary.Footer)

Ext.ns('RL.Quote');


RL.Quote.Summary.Header = Ext.extend(Ext.Container, {
	
	slots 					: true,
	
	
	hidePriceReason			: null,
	tripType 				: null,
	
	cls 					: "trip_details_main",
	
	
	constructor : function (config) {
		config = config || {}
		
		Ext.apply(config, {
			
		})
		
		RL.Quote.Summary.Header.superclass.constructor.call(this, config)
	},

	
	initComponent : function () {
		RL.Quote.Summary.Header.superclass.initComponent.call(this)
	},
	
	
	onRender : function () {
		RL.Quote.Summary.Header.superclass.onRender.apply(this, arguments)
		
		this.refresh(this.hidePriceReason)
	},
	
	
	refresh : function (hidePriceReason) {
		if (!this.rendered) return
		
		this.el.update(this.getHTML(hidePriceReason))
	},
	
	
	getHTML : function (hidePriceReason) {
		
		var gtawRecord 		= Ext.jx.getStore('GTAW').getAt(0)
		var buildStore 		= Ext.jx.getStore('BUILD')
		var destRecord 		= gtawRecord.getResortRecord()
		
		var showPricesRule 	= Ext.jx.getStoreValue("DEPT#CONTRIPPRI") == 0
		var showPrices		= gtawRecord.get('GTAW#PPPRICE') && showPricesRule && !hidePriceReason
		
		var childNum		= gtawRecord.get('GTAW#CHILD')
		if (childNum == '0') childNum = ''
		
		var adultNum 		= gtawRecord.get('GTAW#ADULT')
		
		var adults			= !adultNum ? '': adultNum + (adultNum == 1 ? ' adult' : ' adults')
		var children		= !childNum ? '': ' / ' + childNum + (childNum == 1 ? ' child' : ' children')
		
		var fromDate		= RL.Global.prettyDate(gtawRecord.get('GTAW#DDATE'))
		var toDate			= RL.Global.prettyDate(gtawRecord.get('GTAW#RDATE'))
		
		var html			= []

		if (this.tripType == 'single' && destRecord && !RL.Global.getDefaultDestCode())
			html.push(
				'<div class="quote">', gtawRecord.getTypeDesc(), '</div>',
				'<div class="quote">', destRecord.data['RESORT#RESORT'], '</div>'
			)
		else
			html.push(
				'<div class="quote"> Your trip quote </div>'
			)

		html.push(
			'<div class="sum">'
		)

		if (this.tripType == 'single' && fromDate) html.push(
			fromDate, ' to ', toDate, '<br>'
		)
		
		html.push(
				adults, children,
			'</div>'
		)


		if (showPrices) html.push(
			'<div class="price">',
				Ext.jx.math.formatCurrency(gtawRecord.get('GTAW#PPPRICE')), ' per person',
				'<div class="price_total">', Ext.jx.math.formatCurrency(gtawRecord.get('GTAW#TOTPRICE')), ' total', '</div>',
			'</div>'
		)

		if (gtawRecord.get('GTAW#CUSTNUM')) html.push(
			'<div class="cust">', gtawRecord.get('PROSPW#FIRST'), ' ', gtawRecord.get('PROSPW#LAST'), ' ', gtawRecord.get('PROSPW#EMAIL'), '</div>'
		)
		
		if (!html.length) html.push('<br><br><i>As you add items to your trip quote they will appear here.</i>');

		
		return html.join('')
	}

})

Ext.reg('RL.Quote.Summary.Header', RL.Quote.Summary.Header)
Ext.ns('RL.PriceResult.Service')


RL.PriceResult.Service.Filter = Ext.extend(Ext.Toolbar, {

	slots 				: true,
	
	
	store 				: null,
	
	
	filters				: null,
	filtersByField		: null,
	
	
	initComponent : function () {
		this.beforeInitComponent()
		
		RL.PriceResult.Service.Filter.superclass.initComponent.call(this)
		
		this.afterInitComponent()
	},
	
	
	beforeInitComponent : function () {
	},
	
	
	afterInitComponent : function () {
		this.addEvents('filter-change')
		
		this.filters = []
		this.filtersByField = {}
		
		//why Ext initialize this.items only on render? nano-optimization, phew..
		this.initItems()
	},
	
	
	reset : function () {
		this.removeAll()
		
		this.filters = []
		this.filtersByField = {}
		
		this.store.clearFilter()
	},
	
	
	matchFilter : function (record) {
		var match = true
		
		Ext.each(this.filters, function (filter) {
			if (filter.value != null && record.get(filter.field) != filter.value) {
				match = false
				
				return false
			}
		}, this)
		
		return match
	},
	
	
	addFilter : function (field, options) {
		options = options || {}
		
		var filter = {
			field 	: field,
			value	: undefined
		}
		
		Ext.apply(filter, options)
		
		this.filters.push(filter)
		this.filtersByField[field] = filter
		
		if (!this.items.getCount()) this.add('Filter by:')
				
		var combo = new Ext.form.ComboBox({
			
			mode 			: 'local',
			triggerAction 	: 'all',
			editable 		: false,
			
			store : new Ext.data.ArrayStore({
				fields : [ 'id', 'value' ],
				idIndex : 0,
				
				data : this.getValuesFor(field)
			}),
			
			displayField : 'value',
			valueField	: 'id',
			
			emptyText : options.description,
			
			//force combo to display emptyText even when focused
		    preFocus : function () {}
		})
		
		combo.on('select', this.onValueSelected, this)
		
		combo.filter = filter
		filter.combo = combo
				
		var mgtco=this.parentResults.getConnectedMgtCo();
		if (mgtco){
			var i=this.store.find('#LINK_TO_VENDOR', new RegExp('VENDOR\#MGTCOID\='+mgtco+'$', '') )
			if (i > -1){
				var v=this.store.getAt(i).get('#LINK_TO_VENDOR')//'VENDOR#VENID=AVH&VENDOR#MGTCOID=AVH'
				this.updateFilters(combo.filter, v)
				combo.setValue(v)
			}
		}

		this.add(combo)
	},
	
	
	onValueSelected : function (combo, record, index) {
		this.updateFilters(combo.filter, record.get('id'))
	},
	
	
	updateFilters : function (changedFilter, value) {
		var store = this.store
		
		var wasSuspended = store.eventsSuspended
		
		if (!wasSuspended) store.suspendEvents()
		
		changedFilter.value = value
		
		if (value == null) {
			var combo = changedFilter.combo

			//force combo to display emptyText even when focused
			combo.hasFocus = false
			combo.clearValue()
		}
		
		var changedFilterIndex = this.filters.indexOf(changedFilter)
		
		for (var i = changedFilterIndex + 1; i < this.filters.length; i++) {
			var filter = this.filters[i]
			
			filter.value = undefined
			filter.combo.clearValue()
			filter.combo.store.removeAll()
		}
		
		this.store.clearFilter()

		//if there are no filters applied we need to keep the store unfiltered, so that its 'isFiltered()' method returns false
		if (this.haveFilter()) this.store.filterBy(this.matchFilter, this)
		
		for (var i = changedFilterIndex + 1; i < this.filters.length; i++) {
			var filter = this.filters[i]
			
			var combo = filter.combo
			var comboStore = combo.store
			
			comboStore.loadData(this.getValuesFor(filter.field))
			
			if (comboStore.getCount() > 2) 
				combo.show()
			else
				combo.hide()
		}
		
		if (!wasSuspended) {
			store.resumeEvents()
			
			store.publishUpdates()
		}
		
		this.fireEvent('filter-change', this, changedFilter.field, changedFilter.value)
	},
	
	
	haveFilter : function () {
		var haveFilter = false
		
		this.filters.each(function (filter) {
			if (filter.value !== undefined) haveFilter = true
		})
		
		return haveFilter
	},
	
	
	getValuesFor : function (field) {
		var encounteredValues = {}
		var values = [ [ null, '- All items -'] ]
		var filter = this.filtersByField[field]
		
		this.store.each(function (record) {
			
			var value = String(record.get(field))
			
			if (encounteredValues.hasOwnProperty(value)) return
			
			encounteredValues[value] = true
			
			var displayValue = filter.computeDisplayValue ? filter.computeDisplayValue(record) : value
			
			values.push([ value, displayValue ])
		})
		
		return values
	}

})


Ext.reg('RL.PriceResult.Service.Filter', RL.PriceResult.Service.Filter)
Ext.ns('RL.FieldTypes');


RL.FieldTypes.Vendor = Ext.extend(Ext.form.ComboBox, {

	listWidth			: 500,
	width				: 120,
	fieldLabel			: "Vendor",
	loadingText			: 'Searching...',
	//realValueField:'#LINK_TO_VENDOR',
	realValueField		: '#LINK_TO_SERVICE', //fixes a weird bug where LINK_TO_VENDOR was being populated into LINK_TO_SERVICE
	realDisplayField	: 'VENDOR#VENDOR',

	store				: [ ['', '...' ] ],
	mode				: 'local',
	triggerAction		: 'all',

	emptyText			: 'Vendors',

	typeAhead			: false,

	tpl					:'<tpl for="."><table class="search-item"><tr><td>'+
							'{['+
								'"<img style=\'float:left; margin:3px\' '+
									'src=\'"+Ext.jx.getStoreValue({tableName:"CONFIG",fieldName:"CONFIG#IMAGEPATH"})+"/TN_"+values["VENDOR#IMAGE1"]+'+
								'"\'>'+
								'<b>"+values["VENDOR#VENDOR"]+"</b>..."+'+
								'Ext.jx.stripTags(values["VENDOR#SHORT"],350)'+
							']}'+
						'</td></tr></table></tpl>',

	itemSelector		: 'table.search-item',


    initComponent : function(){

        RL.FieldTypes.Vendor.superclass.initComponent.call(this);

		this.on({
			beforerender:function(){
				this.loadParentFields();
				var vars=Ext.jx, eventName=RL.Global.getVendorDlEventName(this.destCode,this.productType), keyVal_type=this.productType+'-'+this.destCode;

				if (!RL.Global.downloadedVendorLists[eventName]){
					RL.Global.Events.on(eventName, this.vendorsDownloaded, this);
				}else{
					this.vendorsDownloaded(true);
				}
			},
			render:function(){
				Ext.jx.Misc.WebKitLateTriggerRender.defer(1,this);
			}
		});
	},


	loadParentFields : function(calledDirect) {
		if (this.destCode && this.productType) return true;

		var formResort = this.findParentBy(function(item){ return !!item.resortRecord });

		if (!formResort) return false;

		this.destCode=formResort.resortRecord.get('RESORT#SEARCHCODE');


		var formProduct = this.findParentBy(function(item){ return !!item.recordProduct });

		if (!formProduct) return false;

		this.productType=formProduct.recordProduct.get('SERVICE#CODE');

		return true;

	},

	vendorsDownloaded : function(calledDirect) {

		this.loadParentFields();

		var vars=Ext.jx, eventName=RL.Global.getVendorDlEventName(this.destCode,this.productType), keyVal_type=this.productType+'-'+this.destCode;

		if (!vars.vendors_type){
			this.hideItem();
			return;
		}

		var vendors_type=vars.vendors_type[keyVal_type];
		if (!vendors_type || vendors_type.length <= 1){

			this.hideItem();

		}else{
			this.store = new Ext.data.ArrayStore({
				fields: Ext.jx.getStore('VENDOR').fields.items
				//,sortInfo: this.store.sortInfo
			});
			this.store.add(vendors_type);
			this.displayField=this.realDisplayField;
			this.valueField=this.realValueField;

			//this.showItem();

		}

		if (!calledDirect){
			RL.Global.Events.un(eventName, this.vendorsDownloaded);
		}


	}


});

Ext.reg('vendor_selector', RL.FieldTypes.Vendor);

Ext.ns('RL.Vendor');


RL.Vendor.StreetView = Ext.extend(Ext.Panel, {

	vendorRecord 		: null,
	
	isShown				: false,
	

	initComponent : function () {

		Ext.apply(this, {
			slots 		: true,
			
			title		: 'StreetView',
			
			layout 		: 'fit',
			
			items : [
				{
					xtype : 'container',
					slot 	: 'mask',
					
					listeners : {
						afterlayout : function (self) {
							self.el.mask('Loading street view, please wait..')
						}
					}
					
				}
			]
		})
		//eof apply

		RL.Vendor.StreetView.superclass.initComponent.call(this)

		this.on('activate', this.onActivate, this)
	},
	
	
	afterShow : function (isActiveItem) {
		this.isShown = true
		
		if (isActiveItem) this.createPanorama()
	},

	
	onActivate : function () {
		if (!this.isShown) return
		
		this.createPanorama()
	},
	
	
	beforeDismiss : function () {
		var panorama = this.slots.panorama
		
		if (panorama) panorama.cleanup()
	},
	

	createPanorama : function () {
		if (this.slots.panorama) return
		
		this.remove(this.slots.mask)
		
		this.add({
			xtype : 'RL.Vendor.StreetView.Content',
			slot  : 'panorama',
			
			header : false,
			
			vendorAddress : this.vendorRecord.getAddress()
		})
		
		var panorama = this.slots.panorama
		
		this.doLayout()
		
		panorama.fireEvent('activate')
	}

})
//eof extend

Ext.reg('RL.Vendor.StreetView', RL.Vendor.StreetView)

Ext.ns('RL.Vendor.StreetView');


RL.Vendor.StreetView.Content = Ext.extend(Ext.ux.GMapPanel, {

	vendorAddress		: null,


	geocoder			: null,

	notAvailable		: false,


	initComponent : function () {

		Ext.apply(this, {
			title		: 'StreetView',

			gmapType	: 'panorama',

			border		: false,

			zoomLevel   : 0
		})
		//eof apply

		RL.Vendor.StreetView.Content.superclass.initComponent.call(this)

		this.on('activate', this.onActivate, this)
	},
	
	
	cleanup : function () {
		var map = this.getMap()
		
		if (!map) return
		
		map.remove()
	},
	
	
	onBeforeDestroy : function () {
		this.cleanup()
	}, 


	onActivate : function () {
		//to center mask message
		if (this.notAvailable) this.onMapError()
	},


	afterRender : function () {
		RL.Vendor.StreetView.Content.superclass.afterRender.apply(this, arguments)

		GEvent.bind(this.getMap(), 'error', this, this.onMapError);

		this.body.mask('Loading street view, please wait..')

        if (!this.geocoder) this.geocoder = new GClientGeocoder()

        this.geocoder.getLatLng(this.vendorAddress, this.centerStreetView.createDelegate(this))
	},


	centerStreetView : function (latlng) {
		this.body.unmask()

		if (latlng)
			this.getMap().setLocationAndPOV(latlng, {yaw: this.yaw, pitch: this.pitch, zoom: this.zoomLevel})
		else
			this.onMapError()
	},


	onMapError : function (error) {
		this.notAvailable = true

		this.body.mask("Sorry, streetview is not available for this address: " + this.vendorAddress)
	}

})
//eof extend

Ext.reg('RL.Vendor.StreetView.Content', RL.Vendor.StreetView.Content)


Ext.ns('RL.Destination');


RL.Destination.HotDeals = Ext.extend(Ext.Panel, {
	
	destRecord 				: null,
	
	slots					: true,
	
	
	//ala Joose - before : { initComponent }  
	initComponent : function () {
		Ext.apply(this, {
			title : 'Hot Deals',
			name  : 'Specials',
			
			hideBorders : true,
			
			items : [
				{
					xtype : 'container',
					slot : 'mask',
					
					height : 400,
					
					html : '&nbsp;'
				}
			],
			
			bodyStyle : 'overflow-y : auto;'
		})
		
		
		RL.Destination.Content.superclass.initComponent.call(this)
		
		this.on('activate', this.onActivate, this, { single : true })
	},
	
	
	onActivate : function () {
		//required for some unknown reason		
		this.slots.mask.show()
		
		this.slots.mask.setHeight(400) //for IE, of course
		
		this.doLayout()
		
		if (this.slots.iframe) return
		
		this.add({
			xtype : 'simple_iframe_panel',
			slot : 'iframe',
			
			height : 800,
			bodyStyle : { width : '100%' },
			//autoHeight : true,
			src: Ext.jx.getStoreValue("CONFIG#IREURL")+'/?screen=scnSpecials_Iframe&dest='+this.destRecord.data['RESORT#SEARCHCODE']+'&pl='+Ext.jx.getStoreValue('DEPT#DEPTNO')
		})
		
		this.doLayout()
		
		this.body.mask('Loading, please wait...')
		
		this.slots.iframe.on('load', this.onIframeLoaded, this)
	},
	
	
	onIframeLoaded : function () {
		this.remove(this.slots.mask)
		
		//required for some unknown reason
		this.slots.iframe.show()
		
		this.body.unmask()
	}
	

});
//eof extend

Ext.reg('RL.Destination.HotDeals', RL.Destination.HotDeals);

Ext.ns('RL.Vendor')


RL.Vendor.Inventory = Ext.extend(Ext.Panel, {

	pricingRecord	: null,
	vendorRecord	: null,
	searchForm		: null,
	
	
	constructor : function (config) {
		
		var vendorRecord = config.vendorRecord
		
		Ext.apply(config, {
			title 		: 'Inventory'
		})
		//eof apply
		
		RL.Vendor.Inventory.superclass.constructor.call(this, config)
	}
	
})
//eof extend


Ext.reg('RL.Vendor.Inventory', RL.Vendor.Inventory)
Ext.ns('RL.Account.Quotes');


RL.Account.Quotes.Helper = Ext.extend(ExtX.Grid.RowHelper, {
	
	init : function (grid) {
		RL.Account.Quotes.Helper.superclass.init.call(this, grid)
		
		this.addEvents('quote-edit', 'quote-book', 'quote-email')
	},
	
	
    createRowHelper : function () {
    	return new Ext.Panel({
    		
    		slots : true,
    		
    		width : 250,
    		height : 31,
    		
    		layout : 'column',
    		
    		bodyStyle : 'padding-top : 4px;',
    		
    		items : [
    			{
    				xtype : 'button',
    				slot : 'edit',
    				
    				text : 'Edit',
    				
    				columnWidth : 0.34,
    				
    				iconCls : 'rl-icon-quote-edit-small',
    				
    				handler : this.onEditQuote,
    				scope : this
    			},
    			{
    				xtype : 'container',
    				width : 10,
    				html : '&nbsp;'
    			},
    			{
    				xtype : 'button',
    				slot : 'book',
    				
    				text : 'Book',
    				
    				columnWidth : 0.33,

    				iconCls : 'rl-icon-quote-book-small',
    				
    				handler : this.onBookQuote,
    				scope : this
    			},
    			{
    				xtype : 'container',
    				width : 10,
    				html : '&nbsp;'
    			},
    			{
    				xtype : 'button',
    				slot : 'email',
    				
    				text : 'Email',
    				
    				columnWidth : 0.33,
    				
    				iconCls : 'rl-icon-quote-email-small',
    				
    				handler : this.onEmailQuote,
    				scope : this
    			}
    		]
    	})
    },
    
    
    onGridViewReady : function (grid) {
    	grid.getSelectionModel().selectFirstRow()
    	
    	if (grid.store.getCount()) this.showHelper(0)
    },
    
    
	onEditQuote : function () {
		this.fireEvent('quote-edit', this, this.record, this.rowIndex)
	},


	onBookQuote : function () {
		this.fireEvent('quote-book', this, this.record, this.rowIndex)
	},


	onEmailQuote : function () {
		this.fireEvent('quote-email', this, this.record, this.rowIndex)
	}
    
})


Ext.reg('RL.Account.Quotes.Helper', RL.Account.Quotes.Helper)
Ext.ns('RL.Account');


RL.Account.Header = Ext.extend(Ext.Container, {

	slots 					: true,


	constructor : function (config) {
		config = config || {}

		Ext.apply(config, {
			cls : "",

			items : [
				{
					xtype : 'toolbar',

					items : [
						{	
							xtype : 'tbtext',
							
							cls : 'rl-account-header-welcome',
							text : 'Welcome ' + RL.Global.user.getFullName() + '. Here are your Trips'
						},
						'->',
						{
							iconCls : 'rl-icon-find-alt',
							iconAlign: 'top',

							text : 'Update Profile',
							scale : 'large',

							handler : this.onUpdateProfile,
							scope	: this
						},
						{
							text : 'New Quote',
							scale : 'large',

							iconAlign : 'top',
							iconCls : 'rl-icon-back-to-quote',

							handler : this.onBackToQuote,
							scope	: this
						}
					]
				}
			]
		})


		RL.Account.Header.superclass.constructor.call(this, config)
	},


	initComponent : function () {
		RL.Account.Header.superclass.initComponent.call(this)

		this.addEvents('update-profile', 'back-to-quote')
		this.enableBubble('update-profile', 'back-to-quote')
	},


	onUpdateProfile : function () {
		this.fireEvent('update-profile', this)
	},


	onBackToQuote : function () {
		this.fireEvent('back-to-quote', this)
	}

})

Ext.reg('RL.Account.Header', RL.Account.Header)

Ext.ns('RL.Login');


RL.Login.Form = Ext.extend(Ext.Panel, {
	
	slots 					: true,
	
	returnTrips				: false,
	
	
	//overridable UI configs
	plain 					: true,
	buttonAlign 			: 'right',
	
	showCancelButton		: true,
	loginButtonConfig		: null,
	passwordReminderStyle	: null,
	

	beforeInitComponent : function () {
		
		Ext.apply(this, {
			
			layout : 'form',
			labelWidth : 70,
			
			bodyStyle : 'padding : 15px; overflow:visible',
			
			items : [
				{
					xtype : 'textfield',
					slot : 'username',
					
					allowBlank : false,
					
					width : 140,
					
					fieldLabel : 'Email'
				},
				{
		            xtype : 'container',
		            slot : 'forgetpassword',
		            
		            style : this.passwordReminderStyle,
	                html : '<div style="text-align: right"><a class="rl-loginform-forgetpwd">Email me my password</a></div>'
				},
				{
					xtype : 'container',
					height : 10,
					html : '&nbsp;'
				},
				{
					xtype : 'textfield',
					slot : 'password',
					
					allowBlank : false,
					
					width : 140,
					
					inputType : 'password',
					
					fieldLabel : 'Password'
				}
			],
			
			buttons : [
				Ext.applyIf(this.loginButtonConfig || {}, {
					text : 'Login',
					
					handler : this.onLoginClick,
					scope	: this,
					
					scale : 'medium',
					iconCls : 'rl-icon-login'
				}),
				{
					text : 'Cancel',
					
					handler : this.onCancelClick,
					scope	: this,
					
					scale : 'medium',
					iconCls : 'rl-icon-cancel'
				}
			]
		})
		
		if (!this.showCancelButton) this.buttons.pop()
	},

	
	initComponent : function () {
		this.beforeInitComponent()
		
		RL.Login.Form.superclass.initComponent.call(this)
		
		this.addEvents('loged-in', 'cancel', 'forgetpwd')
		this.enableBubble('loged-in', 'cancel', 'forgetpwd')
	},
	
	
	onRender : function () {
		RL.Login.Form.superclass.onRender.apply(this, arguments)
		
		this.el.on('click', this.onClick, this)
	},
	
	
	onLoginClick : function () {
		if (!RL.Defaults.DEV_MODE && !this.validate()) return
		
		var user = RL.Global.user
		
		var username = RL.Defaults.DEV_MODE ? 'jerry@reslogic.com' : this.slots.username.getValue()
		var password = RL.Defaults.DEV_MODE ? '132759' : this.slots.password.getValue()
		
		user.setUsername(username)
		user.setPassword(password)
		
		Ext.jx.mask(Ext.getBody(), 'Authorizing, please wait...', 'rl-mask-medium')
		
		user.authenticate(this.returnTrips, this.authenticateCallback, this)
	},
	
	
	authenticateCallback : function (user, success) {
		Ext.jx.unmask(Ext.getBody())
		
		if (success)
			this.fireEvent('loged-in', this)
		else {
			this.slots.username.markInvalid()
			this.slots.password.markInvalid()
		}
	},
	
	
	onCancelClick : function () {
		this.fireEvent('cancel', this)
	},
	
	
	onClick : function (event) {
		if (event.getTarget('.rl-loginform-forgetpwd')) {
			event.preventDefault()
			
			this.fireEvent('forgetpwd', this)
		}
	}

})

Ext.reg('RL.Login.Form', RL.Login.Form)
Ext.ns('RL.Login');


RL.Login.Popup = Ext.extend(Ext.Window, {
	
	slots 					: true,
	
	returnTrips				: false,
	
	

	beforeInitComponent : function () {
		
		Ext.apply(this, {
			
			title : 'Login:',
			
			iconCls : 'rl-icon-locked',
			
			modal : true,
			resizable : false,
			
			width : 280,
			height : 190,
			
			layout : 'fit',
			
			items : [
				{
					xtype : 'RL.Login.Form',
					slot : 'form',
					
					returnTrips	: this.returnTrips
				}
			]
		})
	},

	
	initComponent : function () {
		this.beforeInitComponent()
		
		RL.Login.Popup.superclass.initComponent.call(this)
		
		this.slots.form.on('cancel', this.close, this)
		this.slots.form.on('loged-in', this.onLogin, this)
	},
	
	
	onLogin : function () {
		this.close()
		
		RL.Global.showUserAccount()
	}

})

Ext.reg('RL.Login.Popup', RL.Login.Popup)
Ext.ns('RL.Model');


RL.Model.User = Ext.extend(Ext.util.Observable, {
	
	username		: null,
	password		: null,
	
	prospwRecord	: null,
	
	authenticated	: false,
	
	
	constructor : function (config) {
		Ext.apply(this, config)
		
		RL.Model.User.superclass.constructor.call(this, config)
		
		this.addEvents('login-success', 'login-failure', 'logout-success')
	},
	
	
	setUsername : function (value) {
		this.username = value
	},
	
	
	setPassword : function (value) {
		this.password = value
	},
	

	authenticate : function (returnTrips, callback, scope) {
		if (!RL.Defaults.DEV_MODE && (!this.username || !this.password)) throw "Can't authenticate user - some of credentials are missed"
		
		
		var actionParams = Ext.jx.Ajax.urlEncode({ 
			screen : 'js::action::logon', 
			pl : Ext.jx.getStoreValue('DEPT#DEPTNO'),
			consumer_email : this.username,
			consumer_password : this.password,
			return_trips : returnTrips ? '1' : '0'
		})
		

		var server = Ext.jx.Server.get()
		
		Ext.Ajax.request({
			timeout : 90,
			url: server+'?'+actionParams,
			method: 'GET',
			
			success : function (responseObject) {
				Ext.jx.Server.release(server)
				
				var response = responseObject.responseObject || eval(responseObject.responseText)
				
				if (response.ERROR || !response.PROSPW || returnTrips && !response.GTAW) {
					this.fireEvent('login-failure', this)
					
					if (callback) callback.call(scope || window, this, false)
					
					return
				}
				
				//setting PROSPW
				var prospwData
				
				Ext.jx.each(response.PROSPW.dataStorage, function (value) {
					prospwData = value
				})
				
				Ext.jx.getTable('PROSPW').setData(prospwData)
				
				this.prospwRecord = Ext.jx.getStore('PROSPW').getAt(0)
				
				
				if (returnTrips) {
					//setting GTAWQUOTES
					var gtawQuotesData = {
						meta : null,
						results : 0,
						rows : []
					}
					
					Ext.jx.each(response.GTAW.dataStorage, function (value) {
						if (!gtawQuotesData.meta) gtawQuotesData.meta = value.meta
						
						gtawQuotesData.results++
						
						gtawQuotesData.rows.push(value.rows[0])
					})
					
					gtawQuotesData = this.prepareQuotesData(gtawQuotesData)
	
					
					Ext.jx.setTable('GTAWQUOTES', {
						fields : gtawQuotesData.meta.fields
					})
					
					Ext.jx.getTable('GTAWQUOTES').setData(gtawQuotesData)
					
					Ext.jx.getStore('GTAWQUOTES').sort('GTAWQUOTES#RESNUM', 'DESC')
				}
				
				
				//notifying the world
				this.authenticated = true
				
				this.fireEvent('login-success', this)
				
				if (callback) callback.call(scope || window, this, true)
			},

			failure : function () {
				Ext.jx.Server.release(server)
				
				if (callback) callback.call(scope || window, this, false)
			},
			
			scope : this
		})
	},
	
	
	prepareQuotesData : function (data) {
		data.meta.tableName 	= 'GTAWQUOTES'
		data.meta.id 			= '#LINK_TO_GTAWQUOTES'
		
		Ext.jx.each(data.meta.fields, function (field) {
			field.name = field.name.replace(/GTAW/, 'GTAWQUOTES')
		}) 
		
		Ext.jx.each(data.rows, function (row, index) {
			var newRow = {}
			
			Ext.jx.each(row, function (value, name) {
				newRow[name.replace(/GTAW/, 'GTAWQUOTES')] = value
			})
			
			data.rows[index] = newRow
		})
		
		return data
	},
	
	
	applyDataToGTAW : function () {
		var gtawData 		= Ext.jx.getStore('GTAW').getAt(0).data
		var prospwData 		= this.prospwRecord.data
		
		for (var fieldName in prospwData) gtawData[fieldName] = prospwData[fieldName]
	},
	
	
	getQuotesStore : function () {
		return Ext.jx.getStore('GTAWQUOTES')
	},
	
	
	getFirstName : function () {
		return this.get('PROSPW#FIRST')
	},
	
	
	getLastName : function () {
		return this.get('PROSPW#LAST')
	},
	
	
	getFullName : function () {
		return this.getFirstName() + ' ' + this.getLastName()
	},
	
	
	getAuthToken : function () {
		return this.get('#CHECK2')
	},
	
	
	logout : function () {
		this.authenticated = false
		this.username = null
		this.password = null
		
		Ext.jx.getStore('PROSPW').removeAll()
		Ext.jx.getStore('GTAWQUOTES').removeAll()
		
		this.fireEvent('logout-success', this)
	},
	
	
	get : function () {
		if (!this.authenticated) throw "Can't 'get' - user isn't authenticated yet"
		
		var record = this.prospwRecord
		
		return record.get.apply(record, arguments)
	},
	
	
	set : function () {
		if (!this.authenticated) throw "Can't 'set' - user isn't authenticated yet"
		
		var record = this.prospwRecord
		
		return record.set.apply(record, arguments)
	}
})


Ext.ns('RL.Model');

//some kind of wrapper around GTAW table
RL.Model.Quote = Ext.extend(Ext.util.Observable, {
	
	user 			: null,
	
	loaded			: false,
	
	
	resno			: null,
	authToken		: false,
	
	isDirty			: true,
	
	
	
	constructor : function (config) {
		Ext.apply(this, config)
		
		RL.Model.Quote.superclass.constructor.call(this, config)
		
		RL.Global.ensureGtawRecord()
		RL.Global.getCurrency()
		
		this.addEvents('load-success', 'load-failure', 'change')
	},
	
	

	load : function (callback, scope) {
		
		if (!this.resno || !this.authToken) throw "Can't load quote - either res_num or check value is missed"
		
		var actionParams = Ext.jx.Ajax.urlEncode({ 
			screen 		: 'js::action::get_quote', 
			pl 			: Ext.jx.getStoreValue('DEPT#DEPTNO'),
			resno 		: this.resno,
			check 		: this.authToken
		})
		

		var server = Ext.jx.Server.get()
		
		Ext.Ajax.request({
			timeout : 90,
			url: server+'?'+actionParams,
			method: 'GET',
			
			success : function (responseObject) {
				Ext.jx.Server.release(server)
				
				var isError = false
				
				try {
					var response = responseObject.responseObject || eval(responseObject.responseText)
				} catch (e) {
					isError = true
				}
				
				
				if (isError || !response.GTAW || !response.BUILD || !response.PROSPW) {
					this.fireEvent('load-failure', this)
					
					if (callback) callback.call(scope || window, this, false)
					
					return
				}
				
				//setting data
				Ext.jx.setTable('GTAW', response.GTAW)
				Ext.jx.setTable('BUILD', response.BUILD)
				
				RL.Global.ensureGtawRecord()
				
				//gathering all resorts (can be several for multiple destionations quotes)
				var resortStore = Ext.jx.getStore('RESORT')
				var resortCodes = {}
				var resortCount = 1
				
				resortCodes[ gtawRecord.getResortRecord().get('RESORT#SEARCHCODE') ] = gtawRecord.getResortRecord()
				
				Ext.jx.getStore('BUILD').each(function (buildRecord) {
					var destSeg = buildRecord.get('BUILD#DESTSEG')
					
					var match = /(\d+):(.+)/.exec(destSeg)
					
					// ignoring a service line if it doesn't contain a destination segment (then its a single destination mode, already added from GTAW)
					// or if we already gathered that destination code
					if (!match || resortCodes[ match[2] ]) return
					
					resortCodes[ match[2] ] = resortStore.getAt(resortStore.find('RESORT#SEARCHCODE', match[2]));
					
					resortCount++
				}, this)
				
				
				//loading vendors for all resort records
				var	me			= this
				var loaded		= 0
				var success		= true
				
				var checkReady = function () {
					if (loaded == resortCount)
						if (success) {
							//notifying the world
							me.loaded = true
							
							me.isDirty = false
							
							me.fireEvent('load-success', me)
							
							if (callback) callback.call(scope || window, me, true)
						} else {
							me.fireEvent('load-failure', me)
							
							if (callback) callback.call(scope || window, me, false)
						}
				}
				
				Ext.jx.each(resortCodes, function (resortRecord, code) {
					RL.Global.getVendors(resortRecord, function (loadedSuccessfully) {
						success = success && loadedSuccessfully
						loaded++
						
						checkReady()
					})
				})
			},

			failure : function () {
				Ext.jx.Server.release(server)
				
				this.fireEvent('load-failure', this)
				
				if (callback) callback.call(scope || window, this, false)
			},
			
			scope : this
		})
	},
	
	
	getRecord : function () {
		return Ext.jx.getStore('GTAW').getAt(0)
	},
	
	
	book : function () {
		var server = Ext.jx.Server.get()
		
		var actionParams = Ext.jx.Ajax.urlEncode({ 
			screen 		: 'scnBookSteps', 
			resno 		: this.resno,
			check 		: this.authToken
		})
		
		
		window.location = server + '?' + actionParams
	},
	
	
	email : function () {
		var server = Ext.jx.Server.get()
		
		var actionParams = Ext.jx.Ajax.urlEncode({ 
			screen 		: 'scnEmailSteps', 
			resno 		: this.resno,
			check 		: this.authToken
		})
		
		
		window.location = server + '?' + actionParams
	},
	
	
	editBuildRecord : function (buildRecord, values) {
		Ext.apply(buildRecord.data, values)
		
		this.isDirty = true
		
		this.updateTSICalcs()
	},
	
	
	removeBuildRecord : function (recordOrId) {
		var buildStore 		= Ext.jx.getStore('BUILD')
		var buildRecord 	= recordOrId instanceof Ext.data.Record ? recordOrId : buildStore.getById(recordOrId)

		buildStore.remove(buildRecord)
		
		this.isDirty = true
		
		this.updateTSICalcs()
	},
	
	
	getQuoteProblems : function () {
		var buildStore 		= Ext.jx.getStore('BUILD')
		var requiredTsis 	= buildStore.getCount() >= Number(Ext.jx.getStoreValue("DEPT#NOREQTSI") || 1)
		var hidePrice 		= ''

		if (!requiredTsis) hidePrice += '* You need to select at least ' + Number(Ext.jx.getStoreValue("DEPT#NOREQTSI") || 1 ) + ' item(s). <br>'


		if (!hidePrice && RL.Global.tripType == 'single' && gtawRecord.data["GTAW#RESORT"]) {

			var destRecord = Ext.jx.getStore("RESORT").data.map['RESORT#SEARCHCODE='+gtawRecord.data["GTAW#RESORT"]]

			if (destRecord) {
				var missing = destRecord.checkAllRequiredProducts()

				if (missing.desc.length) hidePrice+='* You are missing the following required item(s): '+missing.desc+'. <br>'
			}
		}

		return hidePrice
	},
	
	
	finalize : function (callback, errback, scope) {

		if (RL.Global.user && RL.Global.user.authenticated) RL.Global.user.applyDataToGTAW()

		var values={};

		var gtawRecord = Ext.jx.getStore('GTAW').getAt(0);
		for (var fieldName in gtawRecord.data){
			values[fieldName]=gtawRecord.data[fieldName]
		}

		values['GTAW#DEPT']=Ext.jx.getStoreValue('DEPT#DEPTNO');

		var buildStore=Ext.jx.getStore('BUILD');

		var params=Ext.jx.Ajax.cleanFieldNamesForPost(values);

		var buildTransferFields=['#LINK_TO__VENDOR_PRICING','BUILD#DDATE','BUILD#RDATE','BUILD#UNITS','#NO_ADULTS','#NO_CHILDREN','BUILD#PNRCODE','BUILD#STARTTIME', 'BUILD#ENDTIME', 'BUILD#TYPE', 'BUILD#VENID', 'BUILD#MGTCOID'];
		var index=1;
		buildStore.each(function(buildRecord){
			var buildValues={};

			for(var n_index = 0; n_index < buildTransferFields.length ; n_index++){
				var fieldName=buildTransferFields[n_index];
				buildValues[fieldName]=buildRecord.data[fieldName];
			}

			Ext.jx.Ajax.cleanFieldNamesForPost(buildValues,params,'BUILD-'+index);
			index++;
		},this);

		var conn = new Ext.data.Connection();
		var server=Ext.jx.Server.getPrimary();
		var url=server+'?screen=js::action::update_quote&pl='+Ext.jx.getStoreValue('DEPT#DEPTNO');

		if (Ext.jx.getQueryString()['resno']){
			url+='&resno='+Ext.jx.getQueryString()['resno'];
			url+='&check='+Ext.jx.getQueryString()['check'];
		}

		conn.request({
			scope:this,
			timeout:60,
			url: url,
			params: {page_action:Ext.urlEncode(params)},
			method: 'POST',
			success: function(responseObject) {
				Ext.jx.Server.release(server);
				if (!responseObject.responseObject){
					eval('responseObject.responseObject='+responseObject.responseText);
				}
				var gtawResponse=responseObject.responseObject.GTAW.dataStorage.ALL.rows[0];
				var prospwResponse=responseObject.responseObject.PROSPW.dataStorage.ALL.rows[0];
				var buildResponse=responseObject.responseObject.PROSPW.dataStorage.ALL;

				for (var fieldName in gtawResponse){
					gtawRecord.set(fieldName,gtawResponse[fieldName]);
				}
				for (var fieldName in prospwResponse){
					gtawRecord.set(fieldName,gtawResponse[fieldName]);
				}

				var countRecordsStore=buildStore.getCount();
//								this.buildStore.removeAll();
				var countRecordsReturned=buildResponse.rows.length;
				//debugger;

//								for(var n_index = 0; n_index < countRecordsReturned; n_index++){
//									var buildRow=buildResponse.rows[n_index];
//									RL.Global.getWizard(this.searchForm).addServiceItem({data:buildRow});
//									//var data=Ext.apply({},buildRow);
//									//var buildRecord=new this.buildStore.reader.recordType(data);
//									//addServiceItem
//									//this.buildStore.add(buildRecord);
//								}

//				if ( RL.Defaults.DEV_MODE ) debugger;
//
//				if ( RL.Defaults.DEV_MODE && countRecordsReturned < countRecordsStore ){
//					//Ext.MessageBox.alert('Error, Saving Quote', 'Error. The system was not able to add all of your selected items to the quote.');
//					debugger;
//				}
				
				this.idDirty = false
				
				if (callback) callback.call(scope || window)
			},

			failure: function() {
				Ext.jx.Server.release(server);

				if (errback) errback.call(scope || window)
			}
		})
	},
	
	
	updateTSICalcs : function (notify) {
		var gtawRecord = Ext.jx.getStore('GTAW').getAt(0)
		var buildStore = Ext.jx.getStore('BUILD')
		
		var resPrice = 0

		buildStore.each(function (buildRecord) {
			var qty 		= Number(buildRecord.get('BUILD#UNITS'))
			var price 		= buildRecord.getPrice()
			var totalPrice 	= Math.round(qty * price)

			buildRecord.set('#SELL_PRICE_TOTAL', totalPrice)
			resPrice += totalPrice
		})

		gtawRecord.set('GTAW#TOTPRICE', resPrice)

		var adults = Number(gtawRecord.get('GTAW#ADULT'))
		var children = Number(gtawRecord.get('GTAW#CHILD') || 0)

		if (!adults || isNaN(adults)) {
			adults = Number(Ext.jx.getStoreValue("DEPT#TQNOADL")) || 2
			gtawRecord.set('GTAW#ADULT', adults)
		}

		if (!children || isNaN(children)) {
			children = 0
			gtawRecord.set('GTAW#CHILD', children)
		}

		gtawRecord.set('GTAW#PAX', adults + children)
		gtawRecord.set('GTAW#PPPRICE', Math.round(resPrice / (adults + children)))
		
		this.fireEvent('change')
	},
	
	
	addServiceItem : function (pricingRecord, values, n_dest, destCode) {

		var buildStore 	= Ext.jx.getStore('BUILD')
		var data 		= Ext.apply({}, pricingRecord.data)

		if (values) for (var key in values) {
			var value = values[key]

			if (value) data[key] = value
		}

		var buildRecord = new buildStore.reader.recordType(data)
		var buildData	= buildRecord.data

		var units = buildData['BUILD#UNITS'] = Number(buildData['BUILD#UNITS']) || 1;
		
		buildData['BUILD#DDATE']		= Ext.isDate(buildData['BUILD#DDATE']) ? buildData['BUILD#DDATE'] : Date.parseDate(buildData['BUILD#DDATE'],'m/d/Y');
		buildData['BUILD#RDATE']		= Ext.isDate(buildData['BUILD#RDATE']) ? buildData['BUILD#RDATE'] : Date.parseDate(buildData['BUILD#RDATE'],'m/d/Y');
		
		buildData['BUILD#SERVICE']		= units + ': ' + buildData['VENDOR#VENDOR'] + ' ' + (buildData['#UNIT_DESC'] || '' ) +'  ' + (buildData['BUILD#CITY'] || '' );
		buildData['#SELL_PRICE_TOTAL']	= buildData['BUILD#UNITS'] * buildData['#SELL_PRICE'];

		buildData['BUILD#DESTSEG'] = n_dest + ':' + destCode

		Ext.jx.getStore('GTAW').getAt(0).checkDatesSearch(buildRecord.getService(), buildData['BUILD#DDATE'], buildData['BUILD#RDATE']); //this will try to set the trip dates

		buildStore.add(buildRecord)
		
		//buildData['MGTCO#CPRODS']='GT,CT,SR,TH,LO'		
		if (buildData['MGTCO#CPRODS']){
			var o=RL.Global.connectedDestProducts[destCode]=RL.Global.connectedDestProducts[destCode] || {};						
			Ext.each ( buildData['MGTCO#CPRODS'].split(','), function(c){
				o[c]=buildData['BUILD#MGTCOID']
			})			
		}
		if (buildData['MGTCO#CPRODGRPS']){
			var o=RL.Global.connectedDestProdGroups[destCode]=RL.Global.connectedDestProdGroups[destCode] || {};						
			Ext.each ( buildData['MGTCO#CPRODGRPS'].split(','), function(c){
				o[c]=buildData['BUILD#MGTCOID']
			})			
		}
		

		this.idDirty = true
		
		this.updateTSICalcs()
		
		return buildRecord
	}
	
	
})


Ext.ns('RL.Quote.Finalize');


RL.Quote.Finalize.Spinner = Ext.extend(Ext.Window, {

	initComponent : function () {
		
		Ext.apply(this, {
			width: 700,
			height: 450,
			
			closable: false,
			modal: true,
			
			html : [
				'<table class="finalize_quote_container" width=100% height=100%><tr valign=center><td align=center>',
				'<div class=finalize_quote_img></div>',
				'<div class=finalize_quote_content>Please wait while we are preparing your quote . . . </div>',
				'</td></tr></table>'
			].join('')
		})
		
		RL.Quote.Finalize.Spinner.superclass.initComponent.call(this)
	}

});



Ext.reg('RL.Quote.Finalize.Spinner', RL.Quote.Finalize.Spinner)
Ext.ns('RL.Quote.Finalize');


RL.Quote.Finalize.Identity = Ext.extend(Ext.Window, {

	slots			: true,


	initComponent : function () {

		Ext.apply(this, {

			title	: "Customer Information",

			width		: 700,
			autoHeight	: true,

			modal 		: true,
			resizable 	: false,

			items	: [
				RL.Defaults.DEV_MODE ? {
					title : 'Existing members',

					frame : true,

					autoHeight : true,

					items : [
						{
							xtype : 'RL.Login.Form',
							slot : 'login',

							returnTrips : false,

							frame : false,
							plain : false,

							width : 600,
							height : 130,

							buttonAlign : 'left',
							showCancelButton : false,

							loginButtonConfig : {
								text : 'continue',
								scale : 'large',

								iconCls : 'addmember-btn',

								style : {
									'margin-left' : '25px'
								}
							},
							
							passwordReminderStyle : 'float: right; position: relative; top: -20px; left: -215px;'
						}
					]
				}:{
					slot : 'login',
					xtype:'container'
				},
				{
					xtype : 'cust_save',
					slot : 'form',

					autoHeight : true
				}
			]
		})

		RL.Quote.Finalize.Identity.superclass.initComponent.call(this)

		this.addEvents('ready')

		this.slots.form.on('ready', this.onReady, this)
		this.slots.login.on('loged-in', this.onReady, this)
	},



	onReady : function () {
		this.hide()

		this.fireEvent('ready', this)

		this.close()
	}

});



Ext.reg('RL.Quote.Finalize.Identity', RL.Quote.Finalize.Identity)

Ext.ns('RL.Quote');


RL.Quote.Summary.LoginLine = Ext.extend(Ext.Container, {

	slots 					: true,


	constructor : function (config) {
		config = config || {}

		Ext.apply(config, {
			cls : "rl-quote-summary-login"
		})


		RL.Quote.Summary.LoginLine.superclass.constructor.call(this, config)
	},


	initComponent : function () {
		RL.Quote.Summary.LoginLine.superclass.initComponent.call(this)

		this.addEvents('show-login', 'show-account')
	},


	onRender : function () {
		RL.Quote.Summary.LoginLine.superclass.onRender.apply(this, arguments)

		this.refresh()

		this.el.on('click', this.onClick, this)
	},


	onClick : function (event) {
		if (event.getTarget('.rl-quote-summary-login-link')) {
			event.preventDefault()

			this.fireEvent('show-login', this)
		}

		if (event.getTarget('.rl-quote-summary-account-link')) {
			event.preventDefault()

			this.fireEvent('show-account', this)
		}
	},


	refresh : function () {
		if (!this.rendered) return

		this.el.update(this.getHTML())
	},


	getHTML : function () {
		var html			= []

		html.push(
			'<a class="rl-quote-summary-account-link">My Trips </a> ',
			'<a class="rl-quote-summary-login-link"> Login</a>',
			'<div class="x-clear"></div>'
		)

		return html.join('')
	}

})

Ext.reg('RL.Quote.Summary.LoginLine', RL.Quote.Summary.LoginLine)

Ext.ns('RL');


RL.Account = Ext.extend(Ext.Container, {
	
	slots 					: true,
	
	

	beforeInitComponent : function () {
		
		Ext.apply(this, {
			
			layout : 'columnfit',
			
			items : [
				{
					xtype : 'container',
					html : '&nbsp;',
					columnWidth : 0.5
				},
				{
					xtype : 'container',
					width : 700,
					
					layout : 'row-fit',
					
					items : [
						{
							xtype : 'RL.Account.Header',
							height : 60
						},
						{
							xtype : 'RL.Account.Quotes'
						}
					]
				},
				{
					xtype : 'container',
					html : '&nbsp;',
					columnWidth : 0.5
				}
			]
			
		})
	},

	
	initComponent : function () {
		this.beforeInitComponent()
		
		RL.Account.superclass.initComponent.call(this)
		
		this.on('back-to-quote', this.onBackToQuote, this)
		this.on('update-profile', this.onUpdateProfile, this)
		
		this.on('quote-open', this.onOpenQuote, this)
	},
	
	
	onUpdateProfile : function () {
		new Ext.Window({
			title : 'Update profile stub',
			
			height : 80,
			width : 160
		}).show()
	},
	
	
	onBackToQuote : function () {
		RL.Global.startQuoteOver()
	},
	
	
	onOpenQuote : function (rowActions, grid, record, action, row, col, iconCls) {
		
		Ext.jx.mask(Ext.getBody(), 'Loading your quote, please wait...', 'rl-mask-medium')
		
		var quote = new RL.Model.Quote({
			user 		: RL.Global.user,
			
			resno		: record.get('GTAWQUOTES#RESNUM'),
			authToken	: record.get('#CHECK')
		})
		
		quote.load(this.afterQuoteLoad, this)
	},
	
	
	afterQuoteLoad : function (quote, success) {
		Ext.jx.unmask(Ext.getBody())
		
		if (!success) { 
			Ext.Msg.show({
		   		title  :  'Error',
		   		msg: 'Sorry, there was an error during loading of your quote #' + quote.resno + '. Please try again in a few minutes.',
			   	buttons: Ext.Msg.OK,
			   	icon: Ext.MessageBox.ERROR
			})
			
			return
		}
		
//		this.publish('quote-loaded', quote)
		
		RL.Global.showContentQuote(quote)
	}
	
})

Ext.reg('RL.Account', RL.Account)
Ext.ns('RL.Account');


RL.Account.Quotes = Ext.extend(Ext.grid.GridPanel, {

	slots 					: true,

	quoteActions			: null,


	beforeInitComponent : function () {

		var quoteActions = this.quoteActions = new Ext.ux.RowActions({

	 		actions : [
	 			{
					name : 'openQuote',
					id : 1,
					dataIndex : 'dummyIndex', //huh
					iconCls : 'rl-icon-quote-edit',

					text : 'open',

					autoWidth : false,
			 		width : 70,
					fixed : true,

					tooltip : 'Open this quote',

					listeners : {
						action : this.onOpenQuote,
						scope : this
					}
				}
			]
		})
		

		Ext.apply(this, {
			cls : 'rl-account-quotes-grid',

			plugins : [ quoteActions ],

			viewConfig : {
				forceFit : true
			},

			selModel : new Ext.grid.RowSelectionModel({ singleSelect : true }),

			columns : [
				quoteActions.get('openQuote'),
				{
					header : 'Trip No.',

					dataIndex : 'GTAWQUOTES#RESNUM',
					align : 'center'
				},
				{
					header : 'Destination',
					dataIndex : 'dummyIndex',

					renderer : this.destinationNameRenderer
				},
				{
					header : 'From',
					dataIndex : 'GTAWQUOTES#DDATE',
					align : 'center'
				},
				{
					header : 'To',
					dataIndex : 'GTAWQUOTES#RDATE',
					align : 'center'
				}
			],


//			hideHeaders : true,

			store : RL.Global.user.getQuotesStore()
		})
	},


	initComponent : function () {
		this.beforeInitComponent()

		RL.Account.Quotes.superclass.initComponent.call(this)

		this.addEvents('quote-open')
		this.enableBubble('quote-open')
	},


	destinationNameRenderer : function (value, cell, record, row, col, store) {
		var resortStore = Ext.jx.getStore('RESORT')

		return resortStore.getAt(resortStore.find('RESORT#SEARCHCODE', record.get('GTAWQUOTES#RESORT'))).get('RESORT#RESORT')
	},
	
	
	onOpenQuote : function (rowActions, grid, record, action, row, col, iconCls) {
		this.fireEvent('quote-open', rowActions, grid, record, action, row, col, iconCls)
	}
})

Ext.reg('RL.Account.Quotes', RL.Account.Quotes)


//		var quotesHelper = new RL.Account.Quotes.Helper({
//			hideOnEsc 			: false,
//			keepHelperVisible	: true
//		})
//		
//		quotesHelper.on({
//			scope 			: this,
//			
//			'quote-edit' 	: this.onEditQuote,
//			'quote-book' 	: this.onBookQuote,
//			'quote-email' 	: this.onEmailQuote
//		})

Ext.jx.setTable({
	GTAW:{
		templates:{
			description:
				'{[ values._record.getValue("RESORT#RESORT") ]}<br>'+
				'{GTAW#DDATE} to {GTAW#RDATE}<br>'+
				'{GTAW#ADULT} adults {GTAW#CHILD} children<br>'
		},

		FuncsRow:{
			
			isFinalized : function () {
				return this.get('GTAW#RESNUM')
			},
			
			
			isMutable : function () {
				return this.get('GTAW#RESNUM') && this.get('GTAW#TYPE') != 'B' && this.get('GTAW#TYPE') != 'S'
			},
			
			
			isBooking : function () {
				return this.get('GTAW#TYPE') == 'B'
			},
			

			getTypeDesc : function () {
				var gtawRecord = Ext.jx.getStore('GTAW').getAt(0);

				var resNum=gtawRecord.get('GTAW#RESNUM');
				if (!resNum) { return '' }

				var types={P:'Proposal',B: 'Confirmation', S: 'Confirmation Request', D: 'Inactive', C: 'Cancellation'};
				return types[gtawRecord.get('GTAW#TYPE') || 'P']+': '+gtawRecord.get('GTAW#RESNUM');
			},
			

			getResortRecord : function() {
				var resortStore = Ext.jx.getStore('RESORT');
				return resortStore.getAt(resortStore.find('RESORT#SEARCHCODE', this.get('GTAW#RESORT')));
			},

			
			organizeBuildByType : function () {
				var types = {}

				var buildStore = Ext.jx.getStore('BUILD')

				buildStore.each(function (buildRecord) {
					var recordProduct = buildRecord.getService()
					
					if (!recordProduct) return
					
					var serviceCode = recordProduct.data['SERVICE#CODE']
					
					var type = types[serviceCode] = types[serviceCode] || []
					
					type.push(buildRecord)
				})
				
				return types
			},
			
			
			getAdultsNum : function () {
				return Number(this.get('GTAW#ADULT') || 0)
			},
			

			getChildrenNum : function () {
				return Number(this.get('GTAW#CHILD') || 0)
			},
			
			
			checkDatesSearch : function (record, searchStartDate, searchEndDate, searchDest){

				if ( searchStartDate && searchEndDate && !Ext.jx.getStore('BUILD').getCount()){

					if (searchDest) this.data['GTAW#RESORT']=searchDest;

					//perform the opposite of the ddateplus and rdateminus logic
					var startPlus=Number(record.get('SERVICE#DDATEPLUS'));
					if (isNaN(startPlus)) startPlus=0;
					this.data['GTAW#DDATE']=searchStartDate.add('d', -1 * startPlus);

					var endMinus=Number(record.get('SERVICE#RDATEMINUS'));
					if (isNaN(endMinus)) endMinus=0;
					this.data['GTAW#RDATE']=searchEndDate.add('d', endMinus);

				}
			}

		}
	}
});



////additional dataControl to keep the information about airports
////will be filled with a single record and attached to every gtawRecord in onAdd() listener
////will be available as gtawRecord._gtawAirRecord as record (not the datacontrol itself)
////XXX should be included in GTAW itself?
//Ext.jx.setTable({
//	"GTAW_AIR" : {
//        "fields": {
//            "GTAWAIR#FROM_AIRPORT": {
//                "maxLength": 20,
//                "name": "GTAWAIR#FROM_AIRPORT",
//                "fieldType": "string"
//            },
//			"GTAWAIR#TO_AIRPORT": {
//                "maxLength": 20,
//                "name": "GTAWAIR#TO_AIRPORT",
//                "fieldType": "string"
//            }
//        }
//	}
//});

Ext.jx.setTable({
    BUILD:{

		FuncsRow:{
			getService:function(){
				var productType;
				if (this.recordProduct){
					return this.recordProduct;
				}
				if ((productType=this.get('BUILD#TYPE') || this.get('VENDOR#VENTYPE'))) {
					return this.recordProduct=Ext.jx.getRecord({tableName:'SERVICE',recordId:'SERVICE#CODE='+productType});
				}
			},
			
			
			getVendor : function () {
				if (this.recordVendor) return this.recordVendor
				
				var linkToVendor = this.get("#LINK_TO_VENDOR")
				
				if (!linkToVendor) linkToVendor = 'VENDOR#VENID=' + this.get('BUILD#VENID') + '&VENDOR#MGTCOID=' + (this.get('BUILD#MGTCOID') || '~~NULL~~')
				
				return this.recordVendor = Ext.jx.vendors[linkToVendor]
			},
			
			
			getPrice : function () {
				return Number(this.get('#SELL_PRICE') || this.get('BUILD#PRICE'))
			},
			
			
			getNicePrice : function () {
				return Ext.jx.math.formatCurrency(this.getPrice())
			},
			
			
			getTotalPrice : function () {
				return Number(this.get('#SELL_PRICE_TOTAL') || this.get('BUILD#TPRICE'))
			},
			
			
			getNiceTotalPrice : function () {
				return Ext.jx.math.formatCurrency(this.getTotalPrice())
			}
		}
    }
});


Ext.jx.setTable({
	SUPERDES:{
		templates:{
			dests:[
				'{[ Ext.jx.Template.clearSearchItems("resortDropdown") ]}',
				'<tpl for=".">',
					'{[ !values._record.getDests().items.length ? "" : ',
						'"<table><tr><td>"+',
							'values._record.getImageHtml(1,"TN_")+',
							'values._record.getName("bold")+',
							'values._record.getDescRaw("browse")+',
						'"</td></tr></table>"',
					' ]}',
					'<tpl for="_record.getDests().items">',
						'{[',
							'Ext.jx.Template.setSearchItem("resortDropdown",values)+',
							'"<div class=\'search-item\' recordId=\'"+values.get("#LINK_TO_RESORT")+"\'>"+',
								'values.template("shortdescription")+',
							'"</div>"',
						']}',
					'</tpl>',
				'</tpl>'],
			longdescription:
				'<table><tr><td>'+
				'<b>{SUPERDES#NAME}</b>...{[ Ext.jx.ignoreNull(values["SUPERDES#MULTIPLE"]) ]}'+
				'</td></tr></table>'
		},
		FuncsRow:{
			getName : function (nameType){
				var resortRecord=this;
				var html='';
				var name=resortRecord.get("SUPERDES#NAME");
				if (nameType==='bold'){
					html='<b>'+name+'</b>...';
				}else{
					html=name;
				}
				return html;
			},
			getDescRaw : function (descType){
				var superDestRecord=this;
				var html='';
				if (descType==='browse'){
					html=Ext.jx.stripTags(superDestRecord.get("SUPERDES#MULTIPLE") || superDestRecord.get("SUPERDES#SINGLE"), 800);
				}else if (descType==='full'){
					html=superDestRecord.get("SUPERDES#SINGLE") || superDestRecord.get("SUPERDES#MULTIPLE");
				}
				return html;
			},
			getDests : function(){
				var superDestRecord=this;
				if (!superDestRecord._dests) {
					var allDests=Ext.jx.getStore("RESORT","ALL");
					var code=superDestRecord.get('SUPERDES#CODE');
					if (code){
						superDestRecord._dests=allDests.query('RESORT#SUPERDES',code);
						superDestRecord._dests.keySort();
					}else{
						superDestRecord._dests=new Ext.util.MixedCollection();
					}
				}
				return superDestRecord._dests;
			},
			getImageHtml : function(imageNo, imagePrefix){
				var superDestRecord=this;
				if (!imageNo){
					imageNo=1;
				}
				if (!imagePrefix){
					imagePrefix='TN_';
				}
				var image=superDestRecord.get("SUPERDES#IMAGE"+imageNo);
				if (!image){
					return '';
				}
				var imagePath=Ext.jx.getStoreValue({tableName:"CONFIG",fieldName:"CONFIG#IMAGEPATH"})+'/';
				var html="<img style='float:left; margin:3px' src='"+imagePath+imagePrefix+image+"'>";
				return html;
			},
			getContent : function (){
				var superDestRecord=this;

				var contentFrame={
				    items:[{
				    	layout:'fit',
				    	height:50,
				    	width:600,
				    	//items:[{
						    title: superDestRecord.data['SUPERDES#NAME'],
						    layout:'column'
						//}]
					},{
						id:'superdesContentDetail',
						autoHeight:true
					}]
				};

				var contentItems=[{
					title:'Description',
					sort:-1,
					item:{html: superDestRecord.template('longdescription')}

				}];

				return contentFrame;

			},

			//onAddInternal: function(){
			//	var superDestRecord=this;
			//	//this.render();
			//	//centersuperdes.doLayout();
			//
			//},

			getCarousel : function (){
				var resortRecord=this;
				var carousel={

		            layoutConfig: {
		                pagedScroll: true,
		                loopCount:1,
			            scrollButtonPosition:'split',
			            marginScrollButtons: 1
		            },

		            layout: 'carousel',
		            items: []
		        };

				var imageBase=Ext.jx.getStoreValue({tableName:"CONFIG",fieldName:"CONFIG#IMAGEPATH"});
				for (var i=1; i<=10; i++){
					var imageName=resortRecord.data['RESORT#IMAGE'+i];
					if (!imageName){ continue }
					carousel.items.push({
					    style: { margin: '1px 1px 1px 1px'},
		                html:{tag: 'img', width:250, height:200, src: imageBase+'/fs_'+imageName, style:{width:250, height:200}}
					});
				}

				if (carousel.items.length){
					return carousel;
				}else{
					return {};
				}

		    }

		},
		forms:{
			DEST:{
				ztest:true,
				listeners:{
					//beforeconnect:function(dataControl){
					//	dataControl.record.onAddInternal();
					//}
				},
				anchor:"100% 100%",
				layout:"fit",
				autoHeight:true,
				//autoscroll:true,
			    items:[{
					height:600,
			        layout:"border",
			        items:[{
						region:"center",
						title:"Choose a resort",
						layout:"fit",
						items: [{
							xtype:'dataview',
							singleSelect:true,
							emptyText: 'No Resorts to display',
							style:{
								overflow:'auto'
							},
							layout:"fit",
							itemSelector:'div.search-item',
						    selectedClass : "x-view-selected",
						    overClass:"x-view-selected",

							listeners:{
								click:function(dataView, index, node, event){
									Ext.jx.debug(node.getAttribute('recordId')+' clicked '+index);

								},
								beforerender:function(){
									this.store=Ext.jx.getStore("SUPERDES","ALL");
									this.tpl=new Ext.XTemplate(Ext.jx.getTable("SUPERDES").templates.dests);
								}
							}
						}]
					}]
			    }]
			}
		}
	}
});

Ext.jx.setTable({
	VENDOR:{
		templates:{
			description:
				'<table><tr><td style="font-weight:normal">'+
				'<img style="float:left; margin:3px" src="{[Ext.jx.getStoreValue("CONFIG#IMAGEPATH")]}/BR_{VENDOR#IMAGE1}">'+
				'<b>{VENDOR#VENDOR}</b>...{[ Ext.jx.stripTags(values["VENDOR#SHORT"],800) ]}'+
				'</td></tr></table>',
			description_nopic: '<b>{VENDOR#VENDOR}</b>...{[Ext.jx.stripTags(values["VENDOR#SHORT"],800) ]}',
			longdescription:
				'<table><tr><td style="font-weight:normal">'+
				'<img style="float:left; margin:3px" src="{[Ext.jx.getStoreValue("CONFIG#IMAGEPATH")]}/BR_{VENDOR#IMAGE1}">'+
				'<b>{VENDOR#VENDOR}</b>...{[ Ext.jx.ignoreNull(values["VENDOR#LONG"])|| Ext.jx.ignoreNull(values["VENDOR#SHORT"]) ]}'+
				'</td></tr></table>'
		},
		FuncsRow:{
			getDesc : function(){
				return Ext.jx.stripTags(Ext.jx.ignoreNull(this.data["VENDOR#SHORT"]) || Ext.jx.ignoreNull(this.data["VENDOR#LONG"]) ,800)
			},


			hasPictures : function(){
				return this.data["VENDOR#IMAGE1"] && this.data["VENDOR#IMAGE2"];
			},


			hasMap : function(){
				return this.getService().get('#B_USEMAPS') && this.hasWellFormedStreetAddress()
			},


			hasStreetView : function(){
				return this.getService().get('SERVICE#WRMSTVIEW') && this.hasWellFormedStreetAddress()
			},


			hasCalendar : function(){
				return !this.getService().isGDSLodging()
					&& this.getService().get('#B_USEINVENTORY')
					&& Ext.jx.getStoreValue("DEPT#INVRULES")
					&& Ext.jx.getStoreValue("DEPT#INVRULES").substr(0,1) == 'Y';
			},


			getShortDesc:function(){
				var vendorRecord 	= this
				var html 			= []

				var desc = Ext.jx.stripTags(vendorRecord.data["VENDOR#SHORT"],800)
				var imagePath 	= Ext.jx.getStoreValue("CONFIG#IMAGEPATH")
				var image 		= !vendorRecord.data["VENDOR#IMAGE1"] ? '' : '<img src = "' + imagePath + '/BR_' + vendorRecord.data["VENDOR#IMAGE1"] + '" alt = "" />'

				var rowActions = new RL.PriceResult.PricingRowActions(); 

				html.push(
					'<div class = "prodtype_short_desc">',
						'<div class = "prodtype_ldg_header">',
							'<div class = "prodtype_header_style1">'
				)

				if (image && vendorRecord.data["VENDOR#IMAGE2"])
					html.push(rowActions.getInline("more-info-pictures"))

				if (vendorRecord.data["VENDOR#LONG"] || vendorRecord.data["VENDOR#CAT1NAME"] || vendorRecord.data["VENDOR#CAT2NAME"] || vendorRecord.data["VENDOR#CAT3NAME"] || vendorRecord.data["VENDOR#CAT4NAME"] || vendorRecord.data["VENDOR#CAT5NAME"] || vendorRecord.data["VENDOR#CAT6NAME"] || vendorRecord.data["VENDOR#CAT7NAME"]) html.push(rowActions.getInline("more-info"))


//				if (!1 && vendorRecord.get('VENDOR#LONG')){
//					html.push(		rowActions.getInline("more-info-content"))
//				}


				if (RL.Defaults.DEV_MODE) html.push(rowActions.getInline("more-info-inventory"))

				if (this.hasMap())
					html.push(rowActions.getInline("more-info-map"))

				if (this.hasStreetView())
					html.push(rowActions.getInline("more-info-streetview"))


				if (vendorRecord.hasCalendar())
					html.push(rowActions.getInline("more-info-calendar"))


				html.push(
							'</div>',
							vendorRecord.data['VENDOR#VENDOR'],
						'</div>'
				)

				if (image || desc) html.push(
							'<div class = "prodtype_ldg_desc">',
								image,
								'<ul>',
									'<li>',
										desc,
									'</li>',
								'</ul>',
							'</div>'
				)

				html.push(
					'</div>'//closes class = prodtype_short_desc
				)

				return html.join('')
			},


			getService:function(){
				var vendorRecord=this;
				var recordProduct=Ext.jx.getRecord({tableName:'SERVICE',recordId:'SERVICE#CODE='+vendorRecord.get('VENDOR#VENTYPE')});
				return recordProduct;
			},


			hasWellFormedStreetAddress : function () {
				var address = this.getStreetAddress()

				//the address is not empty and do not looks like a 'p.o. box'
				return address && !/o\.?\s*box/i.test(address)
			},


			getStreetAddress : function () {
				var address

				if (this.get('VENDOR#CITY')) //use the new way
					address = this.get('VENDOR#ADDRESS1') || this.get('VENDOR#ADDRESS2')
				else if (this.get('VENDOR#CITY1'))
					address = this.get('VENDOR#ADDR1') || this.get('VENDOR#ADDR2')

				return address
			},


			getAddress: function(){
				var vendorRecord=this;
				var address=this.getStreetAddress();
				if (address){
					if (vendorRecord.get('VENDOR#CITY')){ //use the new way
						address+=(address ? ',' : '')+vendorRecord.get('VENDOR#CITY')
						if (vendorRecord.get('VENDOR#STATE')) address+=(address ? ',' : '')+vendorRecord.get('VENDOR#STATE');
						//address+=' '+vendorRecord.get('VENDOR#ZIP'); //the zip was killing google maps street view
						if (vendorRecord.get('VENDOR#COUNTRY')) address+=(address ? ',' : '')+vendorRecord.get('VENDOR#COUNTRY');
					}else{
						address+=(address ? ',' : '')+vendorRecord.get('VENDOR#CITY1')
						if (vendorRecord.get('VENDOR#STATE1')) address+=(address ? ',' : '')+vendorRecord.get('VENDOR#STATE1');
						//address+=' '+vendorRecord.get('VENDOR#ZIP1'); //the zip was killing google maps street view
						if (vendorRecord.get('VENDOR#COUNTRY1')) address+=(address ? ',' : '')+vendorRecord.get('VENDOR#COUNTRY1');
					}
				}
				return address;
			},
			// Custom function to set the calendars store params Ok so it can ckech the correct DATA on ecah vendor id
			getCalendarStore: function(firstday,lastday,VENID,MGTCOID,VENTYPE){  //monthly periods Only
					var ddate = '.DDATE%3D' + firstday.format('m') + '%252F' + firstday.format('d') + '%252F' + firstday.format('Y') + '%26';
					var rdate = '.RDATE%3D' + lastday.format('m')  + '%252F' + lastday.format('d')  + '%252F' + firstday.format('Y') + '%26';
					x_MGTCOID = '';
					if  (MGTCOID==''||MGTCOID==undefined||MGTCOID==null){
						x_MGTCOID ='~~NULL~~';
					} else {
						x_MGTCOID = MGTCOID ;
					}
					var server=Ext.jx.Server.get();
					var myurl = server+'?screen=js::ext_data_store::_VENDOR_INVENTORY&pl='+Ext.jx.getStoreValue('DEPT#DEPTNO')+'&page_action=' ;
					myurl+= ddate + rdate +'VENDOR.MGTCOID%3D'+ x_MGTCOID + '%26VENDOR.VENID%3D'+ VENID +'%26VENDOR.VENTYPE%3D' + VENTYPE;
					tmpStore=new Ext.data.Store({ //url: 'inventory_res/json_reslogicd.php',
						proxy: new Ext.data.ScriptTagProxy({ url:myurl}),

						reader: new Ext.data.JsonReader(
							{root:'rows',id:'#LINK_TO__VENDOR_INVENTORY',totalProperty: 'results'},
							[
								{name:'#LINK_TO__VENDOR_INVENTORY',  type: 'string'},
								{name:'_VENDOR_INVENTORY#MGTCOID',   type: 'string'},
								{name:'_VENDOR_INVENTORY#INV_DATE',  type: 'string'},
								{name:'_VENDOR_INVENTORY#PRICECODE', type: 'string'},
								{name:'_VENDOR_INVENTORY#BLACKOUT',  type: 'string'},
								{name:'_VENDOR_INVENTORY#AVAIL',  	 type: 'string'},
								{name:'_VENDOR_INVENTORY#TOTINV',  	 type: 'string'},
								{name:'_VENDOR_INVENTORY#USED',  	 type: 'string'},
								{name:'_VENDOR_INVENTORY#VENID',  	 type: 'string'},
								{name:'_VENDOR_INVENTORY#UNITSAY',   type: 'string'},
								{name:'_VENDOR_INVENTORY#MINNGTS',   type: 'string'}
							]
						),

						listeners:{
							load: function(){
								Ext.jx.Server.release(server);

							},
							loadexception: function(){
								Ext.jx.Server.release(server);
							}
						}
					});
					return tmpStore;
			}

		}

	}

});


Ext.jx.setTable({
	'_VENDOR_PRICING':{
		templates:{
			gdsair:
				'<tpl for=".">'+
					'{[ values._record.template("gdsair_line") ]}'+
				'</tpl>',
			gdsair_line:[
				"<TABLE cellSpacing='0' cellPadding='2' border='0' width=100% class=gdsAirRecord>",
				"	<TBODY>",
				"		<TR bgColor='#ffff99'>",
				"			<TD width='20'>&nbsp;</TD>",
				"			<TD colSpan='3' width='100%'>",
				"				<span class=\"ux-row-action-item\"  qtip=\"Add the item to your quote\" actionIndex=0  style=\"width:45px\">",
				"				<img src={[Ext.BLANK_IMAGE_URL]} class=\"ux-row-action-blank-icon  add-to-cart-orange\"/>&#160;</span>",
				"				&nbsp;&nbsp;&nbsp; <B>{#SELL_PRICE}</B> {BUILD#CURRENCY} <B>Roundtrip</B>",
				"			</TD>",
				"		</TR>",
				"		<TR bgColor='whitesmoke'>",
				"			<TD width='20'>&nbsp;</TD>",
				"			<TD colSpan='3'><table width='100%' cellSpacing='0' cellPadding='0'>",
				"					<TR>",
				"						<td>",
				"							<b>Departure</b>",
				"						</td>",
				"						<td align='right'>",
				"							<B>{#TRIP1_AIRLINE_NAME}</B>&nbsp;&nbsp;<IMG src='wrm_client/images/gds/airven/tn_{#TRIP1_AIRLINE_CODE}.gif' align='top' border='0'>",
				"						</td>",
				"					</TR>",
				"				</table>",
				"			</TD>",
				"		</TR>",
				"		<TR vAlign='top'>",
				"			<TD width='20'>&nbsp;</TD>",
				"			<td>",
				"				<table cellSpacing='0' cellPadding='0' width='100%'>",
				"					<tr>",
				"						<TD width='20'>&nbsp;</TD>",
				"						<td>						",
				"							<table cellSpacing='0' cellPadding='0' valign=top>",
				"							<tr valign=top>						",
				"								<td zwidth='157'>",
				"									<b>Depart</b> {#TRIP1_START_AIRP_NAME} ({#TRIP1_START_AIRP_CODE})<br>",
				"									<b>Arrive</b> {#TRIP1_END_AIRP_NAME} ({#TRIP1_END_AIRP_CODE}) ",
				"								</td>",
				"							</tr>",
				"							</table>",
				"						</td>",
				"						<TD width='10'></td>",
				"						<TD zwidth='124'>",
				"							<b>{#TRIP1_START_DATE_PRETTY}</b><BR>",
				//"							Duration: {#TRIP1_DURATION_PRETTY}",
				"						</TD>",

				"						</TD>",
				"						<TD width='10'></td>",
				"						<TD zwidth='124'>",

				"							<table cellSpacing='0' cellPadding='0' valign=top>",
				"							<tr valign=top>						",
				"								<TD zwidth='100'>",
				"									<B>{#TRIP1_START_TIME_PRETTY}</B><br>",
				"									<B>{#TRIP1_END_TIME_PRETTY}</B>",
				"								</TD>",
				"							</tr>",
				"							</table>",
				"						</TD>",



				"						<TD width='5'></td>",
				"						<TD zwidth='76'>",
				"							Flight: {#TRIP1_START_FLIGHT_NUM}<br>",
				"							{#TRIP1_STOPS_PRETTY}",
				"						</TD>",
				"					</tr>",
				"				</table>",
				"			</td>",
				"		</TR>",
				"		<TR><td height=5></td></tr>		",
				"		<TR bgColor='whitesmoke'>",
				"			<TD width='20'>&nbsp;</TD>",
				"			<TD colSpan='3'>",
				"				<table width='100%' cellSpacing='0' cellPadding='0''>",
				"					<TR>",
				"						<td>",
				"							<b>Return</b>",
				"						</td>",
				"						<td align='right'>",
				"							<B>{#TRIP2_AIRLINE_NAME}</B>&nbsp;&nbsp;<IMG src='wrm_client/images/gds/airven/tn_{#TRIP2_AIRLINE_CODE}.gif' align='top' border='0'>",
				"						</td>",
				"					</TR>",
				"				</table>",
				"			</TD>",
				"		</TR>",
				"		<TR vAlign='top'>",
				"			<TD width='20'>&nbsp;</TD>",
				"			<td>",
				"				<table cellSpacing='0' cellPadding='0' width='100%'>",
				"					<tr>",
				"						<TD width='20'>&nbsp;</TD>",
				"						<td>						",
				"							<table cellSpacing='0' cellPadding='0' valign=top>",
				"							<tr valign=top>						",
				"								<td zwidth='157'>",
				"									<b>Depart</b> {#TRIP2_START_AIRP_NAME} ({#TRIP2_START_AIRP_CODE})<br>",
				"									<b>Arrive</b> {#TRIP2_END_AIRP_NAME} ({#TRIP2_END_AIRP_CODE}) ",
				"								</td>",
				"							</tr>",
				"							</table>",
				"						</td>",
				"						<TD width='10'></td>",
				"						<TD zwidth='124'>",
				"							<b>{#TRIP2_START_DATE_PRETTY}</b><BR>",
				//"							Duration: {#TRIP2_DURATION_PRETTY}&nbsp;",
				"						</TD>",
				"						<TD width='10'></td>",
				"						<TD zwidth='124'>",

				"							<table cellSpacing='0' cellPadding='0' valign=top>",
				"							<tr valign=top>						",
				"								<TD zwidth='100'>",
				"									<B>{#TRIP2_START_TIME_PRETTY}</B><br>",
				"									<B>{#TRIP2_END_TIME_PRETTY}</B>",
				"								</TD>",
				"							</tr>",
				"							</table>",
				"						</TD>",


				"						<TD width='5'></td>",
				"						<TD zwidth='76'>",
				"							Flight: {#TRIP2_START_FLIGHT_NUM}<br>",
				"							{#TRIP2_STOPS_PRETTY}",
				"						</TD>",
				"					</tr>",
				"				</table>",
				"			</td>",
				"		</TR>",
				"		<TR><td height=5></td></tr>",
				"		<TR>",
				"			<TD width='20'>&nbsp;</TD>",
				"			<TD colSpan='3'>&nbsp;",
				"			</TD>",
				"		</TR>",
				"		<TR><td height=5></td></tr>",
				"	</TBODY>",
				"</TABLE>"
			],

			gdsair_line_compressed:[
				"<div class='flights-trip departure-trip'>",
					"<div class='trip-label'>Departure</div>",
					"<div class='airport-label depart-airport'>Depart</div>",
					"<div class='airport'>{#TRIP1_START_AIRP_NAME} ({#TRIP1_START_AIRP_CODE}) flight {#TRIP1_START_FLIGHT_NUM}</div>",
					"<div class='airport-label arrive-airport'>Arrive</div>",
					"<div class='airport'>{#TRIP1_END_AIRP_NAME} ({#TRIP1_END_AIRP_CODE})</div>",
					"<div class='flight-stops'>{#TRIP1_STOPS_PRETTY}</div>",
				"</div",

				"<div class='flights-trip return-trip'>",
					"<div class='trip-label'>Return</div>",
					"<div class='airport-label depart-airport'>Depart</div>",
					"<div class='airport'>{#TRIP2_START_AIRP_NAME} ({#TRIP2_START_AIRP_CODE}) flight {#TRIP2_START_FLIGHT_NUM}</div>",
					"<div class='airport-label arrive-airport'>Arrive</div>",
					"<div class='airport'>{#TRIP2_END_AIRP_NAME} ({#TRIP2_END_AIRP_CODE})</div>",
					"<div class='flight-stops'>{#TRIP2_STOPS_PRETTY}</div>",
				"</div"
			],

			longdescription:
				'<table><tr><td>'+
				'<b>{SUPERDES#NAME}</b>...{[ Ext.jx.ignoreNull(values["SUPERDES#MULTIPLE"]) ]}'+
				'</td></tr></table>'
		},

		FuncsRow:{

			getVendor:function(){
				return Ext.jx.vendors[this.get('#LINK_TO_VENDOR')];
			},

			getService:function(){
				return Ext.jx.getRecord({tableName:'SERVICE',recordId:'SERVICE#CODE='+(this.get('BUILD#TYPE')||this.get('VENDOR#VENTYPE'))});
			}
		}


	}

});

Ext.jx.setTable({
	RESORT:{
		templates:{
			shortcleandesc:[
				'{[',
					'values._record.getImageHtml(1,"TN_")+',
					'values._record.getName("bold")+',
					'values._record.getDescRaw("browse",400)',
				']}'],
			shortdescription:[
				'<table><tr><td>',
					'{[',
						'values._record.getImageHtml(1,"TN_")+',
						'values._record.getName("bold")+',
						'values._record.getDescRaw("browse",400)',
					']}',
				'</td></tr></table>'],
			description:
				'<table><tr><td>'+
				'<img style="float:left; margin:3px" src="{[Ext.jx.getStoreValue("CONFIG#IMAGEPATH")]}/BR_{RESORT#IMAGE1}">'+
				'<b>{RESORT#RESORT}</b>...{[ Ext.jx.stripTags(values["RESORT#MULTIPLE"],800) ]}'+
				'</td></tr></table>',

			description_nopic: '<b>{RESORT#RESORT}</b>...{[ Ext.jx.stripTags(values["RESORT#MULTIPLE"],700) ]}',

			longdescription:
				'<table><tr><td>'+
				'<img style="float:left; margin:3px" src="{[Ext.jx.getStoreValue("CONFIG#IMAGEPATH")]}/BR_{RESORT#IMAGE1}">'+
				'<b>{RESORT#RESORT}</b>...{[ Ext.jx.ignoreNull(values["RESORT#MULTIPLE"]) ]}'+
				'</td></tr></table>'
		},
		FuncsRow:{

			getDesc : function(){
				return Ext.jx.stripTags(Ext.jx.ignoreNull(this.data["RESORT#MULTIPLE"]) || Ext.jx.ignoreNull(this.data["RESORT#SINGLE"]) ,800)
			},

			hasPictures : function(){
				return this.data["RESORT#IMAGE1"] && this.data["RESORT#IMAGE2"];
			},

			checkAllRequiredProducts : function(){

				var missing={desc:'', index:{}};
				var requiredProducts=this.getRequiredProducts();
				var gtawRecord = Ext.jx.getStore('GTAW').getAt(0);
				var products=Ext.jx.getStore('SERVICE')

				var types=gtawRecord.organizeBuildByType();
				var requiredProducts=this.getRequiredProducts();
				for (var code in requiredProducts){

					if (!types[code]){

						var product=products.data.map['SERVICE#CODE=' + code];
						if (product){

							missing.index[code]=1;

							if (missing.desc.length) missing.desc+=', ';
							missing.desc+=product.data['SERVICE#DESCRIP'];
						}
					}

				}
				return missing;

			},

			getRequiredProducts : function(){
				if (this.requiredProducts) return this.requiredProducts;
				this.requiredProducts = {};

				var serviceStore = Ext.jx.getStore('SERVICE');

				var proddef = this.data['RESORT#PRODDEF'].split(',');

				Ext.jx.each(proddef, function(raw) {
					var productName = Ext.util.Format.trim(raw.substr(0, 2));
					if (productName == '') return;

					var product = serviceStore.data.map['SERVICE#CODE=' + productName];
					if (!product) return;
					if (product.data['SERVICE#TLVISIBLE'] != 'Y') return;

					var productRequired = Ext.util.Format.trim(raw.substr(2, 1));
					if (productRequired != 2) return;

					this.requiredProducts[productName]=1;

				},this);

				return this.requiredProducts;
			},

			getProducts : function(){
				if (this.products) return this.products;
				this.products = [];

				var serviceStore = Ext.jx.getStore('SERVICE');

				var proddef = this.data['RESORT#PRODDEF'].split(',');

				Ext.jx.each(proddef, function(raw) {
					var productName = Ext.util.Format.trim(raw.substr(0, 2));
					if (productName == '') return;

					var product = serviceStore.data.map['SERVICE#CODE=' + productName];
					if (!product) return;
					if (product.data['SERVICE#TLVISIBLE'] != 'Y') return;

					this.products.push(product);
				},this);

				return this.products;
			},


			getSuperDestRecord : function(){
				var superDests = Ext.jx.getStore("SUPERDES");
				var code = this.get('RESORT#SUPERDES');

				return superDests.query('SUPERDES#CODE', code).itemAt(0);
			},

			getQuoteBubble : function (){
				return {html:'Will return the display to start a quote here'};
			},
			getName : function (nameType){
				var resortRecord=this;
				var html='';
				var name=resortRecord.get("RESORT#RESORT");
				if (nameType==='bold'){
					html='<b>'+name+'</b>...';
				}else{
					html=name;
				}
				return html;
			},
			getDescRaw : function (descType, maxLen){
				var resortRecord=this;
				var html='';
				if (descType==='browse'){
					html=this.getDesc();
				}else if (descType==='full'){
					html=resortRecord.get("RESORT#SINGLE") || resortRecord.get("RESORT#MULTIPLE");
				}
				return html;
			},
			getImageHtml : function(imageNo, imagePrefix){
				var resortRecord=this;
				if (!imageNo){
					imageNo=1;
				}
				if (!imagePrefix){
					imagePrefix='TN_';
				}
				var image=resortRecord.get("RESORT#IMAGE"+imageNo);
				if (!image){
					return '';
				}
				var imagePath=Ext.jx.getStoreValue({tableName:"CONFIG",fieldName:"CONFIG#IMAGEPATH"})+'/';
				var html="<img style='float:left; margin:3px' src='"+imagePath+imagePrefix+image+"'>";
				return html;
			},


			getContent : function (active){
				var resortRecord=this;

				var items=[];
				items.push({
					title:'Pictures',
					name:'Pictures',
					alwaysDoLayout:true,
					sort:-2,
					items:[
						{
							height : 70,
							html: Ext.jx.stripTags(resortRecord.data["RESORT#MULTIPLE"],800)
						},
						resortRecord.getCarousel()
					]
				});

				if (resortRecord.data["RESORT#SINGLE"]){
					items.push({
						title:'Content',
						name:'Content',
						sort:-1,
						html: resortRecord.data["RESORT#SINGLE"]
					})
				}


				for (var i=1; i<=7; i++){
					if (!resortRecord.data['RESORT#CAT'+i+'NAME'] || !resortRecord.data['RESORT#CAT'+i+'INFO']){
						continue;
					}

					items.push({
						title:resortRecord.data['RESORT#CAT'+i+'NAME'],
						name:'RESORT#CAT'+i+'NAME',
						sort:resortRecord.data['RESORT#CAT'+i+'ORDER'],
						items:[{
							xtype: 'panpanel',
							html: resortRecord.data['RESORT#CAT'+i+'INFO']
						}]
					});
				}



				items=items.sort(function(a,b){ return a.sort-b.sort })

				var activeTab=0;
				Ext.each(items, function(item, index){
					if (active && active===item.name){
						activeTab=index;
					}
				});

				return {
					xtype:'tabpanel',
					enableTabScroll: true,
					listeners:{
						beforerender:function(){
							var tt = new Ext.Template(
								 '<li class="{cls}" id="{id}"><a class="x-tab-strip-close" onclick="return false;"></a>',
								 '<a href="#" onclick="return false;"><em>',
								 '<span class="x-tab-strip-inner prodtype_round_button"><span  class="x-tab-strip-text {iconCls}">{text}</span></span>',
								 '</em></a></li>'
							);
							tt.disableFormats = true;
							tt.compile();
							this.itemTpl = tt;
						},

						render:function(){
							var wrap=this.header.child('.x-tab-strip-wrap');
							wrap.addClass('prodtype_ldg_header');
							var ul=wrap.child('ul');
							ul.addClass('remove-background');
							ul.createChild({tag:'li', html: resortRecord.data['RESORT#RESORT']},ul.child('li'));
							ul.child('.x-tab-strip-inner').addClass('prodtype_round_button');
							wrap.child('.x-tab-strip-top').addClass('remove-border');
						}
					},
//					deferredRender:false,
					deferredRender : true,
					layoutOnTabChange : true,

					plugins:Ext.jx.plugins.Tab_Fix,
					//layoutConfig : { renderHidden : true },
					//defaults:{bodyStyle:'padding:5px', border: false, autoHeight:true, hideMode:'offsets'},
//					plain:true,
					activeTab: activeTab,
					border:false,

					height:300,
					items:items

				}
			},


			getCarousel : function (){
				var resortRecord=this;
				var carousel={
					xtype : 'container',
					autoEl : 'div',
					height : 200,

		            layoutConfig: {
		                pagedScroll: true,
		                loopCount:1,
			            scrollButtonPosition:'split',
			            marginScrollButtons: 1
		            },

		            layout: 'carousel',
		            items: []
		        };

				var imageBase=Ext.jx.getStoreValue({tableName:"CONFIG",fieldName:"CONFIG#IMAGEPATH"});
				for (var i=1; i<=10; i++){
					var imageName=resortRecord.data['RESORT#IMAGE'+i];
					if (!imageName){ continue }
					carousel.items.push({
					    style: { margin: '1px 1px 1px 1px'},
		                html:{tag: 'img', width:250, height:200, src: imageBase+'/fs_'+imageName, style:{width:250, height:200}}
					});
				}

				if (carousel.items.length){
					return carousel;
				}else{
					return {};
				}

		    }

		}
	}
});

Ext.jx.setTable({
	SERVICE:{
		FuncsRow:{

			isGDSLodging : function(){
				return this.data['#B_USELODGINGGDS']
			},

			isGDSAir : function(){
				return this.data['#B_USEGDS'] && !this.data['#B_USELODGINGGDS']
			},


			getTimesCats : function(){
				var recordProduct=this;
				if (recordProduct._timesCats) {
					return recordProduct._timesCats;
				}
				var allTimes=Ext.jx.getStore("TIMES","ALL");
				var code=recordProduct.get('SERVICE#CODE'); code='GO';
				var allTimesTemp=recordProduct._times=!code ? new Ext.util.MixedCollection() : allTimes.query('TIMES#PRODUCT',code);

				var store = new Ext.data.ArrayStore({
					fields: allTimes.fields.items
				});

				store.add(allTimesTemp.items);
				//Ext.applyIf(store, Ext.data.GroupingStore.prototype); 
				//store.groupBy('TIMES#CATEGORY'); //there is no reason to use this unless i'm throwing it in a grid

				store.sort('TIMES#LABEL');
				var cats={};
				store.each(function(r){
					var catName=r.data['TIMES#CATEGORY']|| ' ';
					if (!cats[catName]) cats[catName]=[];
					cats[catName].push(r);
				})

				return recordProduct._timesCats=cats;

			},

			isPerPerson:function(){
				var recordProduct=this;
				return (recordProduct.get('SERVICE#AUTOCALC')==1 || recordProduct.get('#B_AUTO_CALC_UNITS_FROM_PAX')==1);
			},

			allowSkip: function (){

				var allow=true;
				if (RL.Global.getTripType() === 'single' ){

					var gtawRecord = Ext.jx.getStore('GTAW').getAt(0), destRecord=Ext.jx.getStore("RESORT").data.map['RESORT#SEARCHCODE='+gtawRecord.data["GTAW#RESORT"]];

					if (destRecord){
						var missing=destRecord.checkAllRequiredProducts();
						allow=!missing.index[this.data['SERVICE#CODE']];
					}
				}
				return allow;
			}

		}

	}
});

Ext.jx.setTable({
    GTAW:{
        forms:{

			SAVE_QUOTE_WIZARD:{
	        	xtype:'wizard',
				stepTitleTpl:'',
			    anchor: '100% 100%',
			    layout: 'border',
			    plain: true,
			    bodyStyle:'padding:5px;',
			    buttonAlign:'right',
			    closable: true,
			    items: [{
			        region: 'west',
			        width: 150,
			        html: '<div class=wizardBookingImg></div>'
			    },{
			        frame: true,
			        region: 'center',
			        layout: 'anchor',
			        bodyStyle: 'padding:5px',
			        items:[{
			            stepTitleItem: true
			        },{
			            anchor: '100% 100%',
			            layout:'card',
			            activeItem: 0,
			            defaults: {border: false},
			            autoScroll:true
			        }]
			    }],
			    buttons:[{
			        text: 'Previous',
			        wizardButton:'prev'
			    },{
			        text: 'Next',
			        wizardButton:'next'
			    },{
			        text: 'Finish',
			        wizardButton:'finish'
			    }],
				listeners:{
					finish:function(){
						var values=this.getValues();
						var gtawRecord = Ext.jx.getStore('GTAW').getAt(0);
						Ext.jx.debug('error: logic not finished');
						//gtawRecord.finalizeQuote(values);
						//this.ownerCt.hide();
					}
				}
			},

        	SAVE_QUOTE_FINAL:{
				stepTitle:'Finishing',
				//xtype: 'fieldset',
				title:'Please wait while we are preparing your quote.',
				autoHeight: true,
				border: true,
				//defaultType: 'textfield',
				collapsible: false,
				width:480

			},


			BOOK_WIZARD:{
	        	xtype:'wizard',
			    anchor: '100% 100%',
			    layout: 'border',
			    plain: true,
			    bodyStyle:'padding:5px;',
			    buttonAlign:'right',
			    closable: true,
			    items: [{
			        region: 'west',
			        width: 150,
					baseCls:'wizardBookingImg',
					html:'&#160'
			        //html: '<div class=wizardBookingImg></div>',
					//style:{
					//	"background-color":'yellow'
					//}
			    },{
			        frame: true,
			        region: 'center',
			        //layout: 'anchor',
			        bodyStyle: 'padding:5px',
			        //items:[{
			        //    stepTitleItem: true
			        //},{
			            //anchor: '100% 100%',
			            layout:'card',
			            activeItem: 0,
			            defaults: {border: false},
			            autoScroll:true
			        //}]
			    }],
			    buttons:[{
			        text: 'Previous',
			        wizardButton:'prev'
			    },{
			        text: 'Next',
			        wizardButton:'next'
			    },{
			        text: 'Finish',
			        wizardButton:'finish'
			    }]
			},
			BOOK_WIZARD_TERMS:{
		        stepTitle:'Terms & Conditions',
		        noValidate:true,
		        items: [{
		            xtype: 'panel',
		            layout: 'fit',
		            name:'deptTerms',
		            border:true,
		            autoScroll: true,
		            height: 300,
		            frame: true
		        },{
		            xtype: 'radio',
		            name: 'termsAccept',
		            value: true,
		            boxLabel: 'I accept the license agreement',
		            checked: true,
		            allowBlank: false
		        },{
		            xtype: 'radio',
		            name: 'termsAccept',
		            value: false,
		            checked: false,
		            boxLabel: 'I do not accept the license agreement'
		        }],
		        listeners: {
		        	beforerender:function(){
		        		var dept=Ext.jx.getRecord({tableName:'DEPT'});
		        		this.findField('deptTerms').html=dept.get('DEPT#WEBTERMS');
		        	},
		            beforestepchange:function(){
		                var accepts=false;
		                this.cascade(function(f){
		                    if(f.name==='termsAccept' && f.value){
		                        accepts=f.getValue();
		                        return false;
		                    }
		                });

		                if (!accepts){
		                    Ext.MessageBox.alert('Terms and Conditions', "In order to proceed, you must accept our license agreement.");
		                    return false;
		                }

		            }
		       }

			},

			BOOK_WIZARD_CUSTOMER:{
				stepTitle:'Customer',
				xtype: 'fieldset',
				title:'Customer Information',
				autoHeight: true,
				border: true,
				defaultType: 'textfield',
				collapsible: false,
				width:480,
				items: [{
					fieldLabel: 'First Name',
					name: 'PROSPW#FIRST',
					width: 200,
					allowBlank: false
				},{
					fieldLabel: 'Last Name',
					name: 'PROSPW#LAST',
					width: 200,
					allowBlank: false
				},{
					fieldLabel: 'Group/Company',
					name: 'PROSPW#GROUP_NAME',
					width: 200,
					allowBlank: false
				},{
					fieldLabel: 'Email',
					name: 'PROSPW#EMAIL',
					width: 200,
					vtype: 'email',
					allowBlank: false
				},{
					fieldLabel: 'Email Opt-In',
					name: 'PROSPW#EMAILSPEC',
					xtype: 'checkbox',
					value: 'false',
					allowBlank: true
				},{
					fieldLabel: 'Address 1',
					name: 'PROSPW#ADDRESS',
					width: 200,
					allowBlank: false
				},{
					fieldLabel: 'Address 2',
					name: 'PROSPW#ADDRESS2',
					width: 200,
					allowBlank: true
				},{
					fieldLabel: 'City',
					name: 'PROSPW#CITY',
					width: 200,
					allowBlank: false
				},{
					fieldLabel: 'State/Province',
					name: 'PROSPW#STATE',
					width: 200,
					allowBlank: false
				},{
					fieldLabel: 'Zip/Postal Code',
					name: 'PROSPW#ZIP',
					width: 200,
					allowBlank: false
				},{
					fieldLabel: 'Phone (day)',
					name: 'PROSPW#PHONE_DAY',
					width: 200,
					allowBlank: false
				},{
					fieldLabel: 'Phone (night)',
					name: 'PROSPW#PHONE_NITE',
					width: 200,
					allowBlank: false
				}],
				listeners:{
					invalid:function(){
		            	Ext.MessageBox.alert('Missing fields', "Please put in the missing fields.");
					}
				}


			},

			BOOK_WIZARD_PAX_COUNT:{

		        stepTitle: 'Passenger Count',
		        items: [{
		            xtype: 'fieldset',
		            autoHeight: true,
		            defaultType: 'textfield',
		            collapsible: false,
		            items: [
		            {
		                fieldLabel: 'No. Adults',
		                name:'passengerNoAdult',
		                allowBlank: false,
		                minValue:1,
		                maxValue:50,
		                decimalPrecision:0,
		                width:50,
		                xtype:'uxspinner'
		            },{
		                fieldLabel: 'No. Children',
		                name:'passengerNoChild',
		                minValue:0,
		                maxValue:50,
		                decimalPrecision:0,
		                width:50,
		                xtype:'uxspinner'
		            }]
		        }],
		        listeners : {
		            beforeshow: function () {
		            },
		            beforestepchange: function () {
		            }
		        }
			},

			BOOK_WIZARD_PAX_NAMES:{
		        stepTitle: 'Passenger Names',
		        name:'passenger',
		        items: [{}],
		        listeners: {
		            beforeshow : function() {
		            },
		            beforestepchange : function() {
		            }
		        }
			},

			BOOK_WIZARD_PAX_NAMES_SINGLE:{
				xtype:'fieldset',
				//title: 'Traveler ' + Ext.util.Format.capitalize(type) + ' #' + index,
				collapsible: false,
				autoHeight: true,
				labelWidth:80,
				items: [{
					xtype:'textfield',
					fieldLabel: 'First Name',
					width: '200',
					allowBlank: false
				},{
					xtype:'textfield',
					fieldLabel: 'Last Name',
					width: '200',
					allowBlank: false
				},{
					hideLabel:true,
					labelAlign: 'left',
					xtype: 'radio',
					value: "adult",
					boxLabel: 'Adult',
					height: 20
					//checked: (type == "adult") ? true : false

				},{
					hideLabel:true,
					labelAlign: 'left',
					xtype: 'radio',
					value: "child",
					boxLabel: 'Child',
					height: 20
					//checked: (type == "child") ? true : false
				},{
					fieldLabel: 'Age',
					allowBlank: false,
					//minValue: (type == "adult") ? 18 : 2,
					//maxValue:(type == "adult") ? 120 : 17,
					decimalPrecision:0,
					width:50,
					xtype:'uxspinner'
				}]

			},
			BOOK_WIZARD_CREDIT_CARD:{

				stepTitle: 'Credit Card Information',
				items: [{
					xtype: 'fieldset',
					autoHeight: true,
					defaultType: 'textfield',
					collapsible: false,
					items: [{
						fieldLabel: 'Amount',
						width: 75,
						allowBlank: false
					},{
						xtype: 'combo',
						fieldLabel: 'Type',
						store: ['Visa', 'MasterCard', 'American Express', 'Discover'],
						typeAhead: true,
						mode: 'local',
						triggerAction: 'all',
						emptyText: '',
						listWidth: 120,
						width: 120,
						forceSelection: true,
						allowBlank: false,
						selectOnFocus: true
					},{
						fieldLabel: 'Credit Card No.',
						width: 200,
						allowBlank: false
					},{
						//xtype: 'monthfield', //not supported in v3
						fieldLabel: 'Expiration Date',
						format : 'm/Y',
						useDayDate : 31,
						allowBlank: false
					},{
						fieldLabel: 'Name on Card',
						width: 200,
						allowBlank: false
					},{
						fieldLabel: 'Security Code',
						width: 35,
						allowBlank: false
					},{
						fieldLabel: 'Billing Address',
						width: 200,
						allowBlank: false
					}]
				}],
				listeners: {
					beforestepchange : function() {

					}
				}
			}
		}
	}
});



//var registerWin = new Ext.Window({
//    name: 'bookingWindow',
//    title: 'Reservation Booking Process Wizard',
//    width: 700,
//    height: 450,
//    layout: 'anchor',
//    items:[bookingWizard]
//});

//Ext.onReady( function() {
//    registerWin.show();
//
//
//});

Ext.namespace('Ext.jx.Misc');



(function(){
	
	var html = '<select class=quantityDropdown>';
	
	for (var i = 0; i <= 100; i++) html += '<option value=' + i + '>' + i + '</option>';
	
	html += '</select>';

	
	Ext.jx.Misc.getSimpleQtyActionCol = function () {
		return {
			header		: 'Quantity',
			width		: 50, 
			renderer 	: function (v, p, record, rowIndex) {
				return html
			}
		}
	}
	
})();



Ext.jx.setTable({
	PRODGRP:{
		
		Funcs : {
			getNonEmptyGroups : function() {
				var res = [];
				
				var prodGroupStore = Ext.jx.getStore('PRODGRP');
				
				prodGroupStore.each(function(recordProdGroup){
					if (recordProdGroup.data['PRODGRP#TLVISIBLE'] != 1) return;
					
					if (recordProdGroup.getProducts().getCount()) res.push(recordProdGroup);
				});
				
				return res;
			},
			
			
			getProductsCodes : function () {
				var productTypes = [];
				var nonEmptyGroups = this.getNonEmptyGroups();
				
				Ext.each(nonEmptyGroups, function(productGroup) {
					var pgProducts = productGroup.getProducts();
					
					pgProducts.each(function(recordProduct){
						productTypes.push(recordProduct.get('SERVICE#CODE'));
					});
				});
				
				return productTypes;
			}
		},
		

		FuncsRow:{

			getProducts : function(){
				var recordProdGroup=this;
				if (recordProdGroup._products) {
					return recordProdGroup._products;
				}
				var allProducts=Ext.jx.getStore("SERVICE","ALL");
				var code=recordProdGroup.get('PRODGRP#PGID');
				return recordProdGroup._products=!code ? new Ext.util.MixedCollection() : allProducts.query('SERVICE#PGID',code);
			}

		}

	}
});

Ext.jx.setTable({
	RESORT:{
		templates:{
			description:
				'<table><tr><td>'+
				'<img style="float:left; margin:3px" src="{[Ext.jx.getStoreValue("CONFIG#IMAGEPATH")]}/BR_{RESORT#IMAGE1}">'+
				'<b>{RESORT#RESORT}</b>...{[ Ext.jx.stripTags(values["RESORT#MULTIPLE"],800) ]}'+
				'</td></tr></table>',
			description_nopic: '<b>{RESORT#RESORT}</b>...{[ Ext.jx.stripTags(values["RESORT#MULTIPLE"],700) ]}',

			longdescription:
				'<table><tr><td>'+
				'<img style="float:left; margin:3px" src="{[Ext.jx.getStoreValue("CONFIG#IMAGEPATH")]}/BR_{RESORT#IMAGE1}">'+
				'<b>{RESORT#RESORT}</b>...{[ Ext.jx.ignoreNull(values["RESORT#MULTIPLE"]) ]}'+
				'</td></tr></table>'
		},
		forms:{
			INFO:{
				getCarousel: function(){

					var resortRecord=this;
					var carousel={

						layoutConfig: {
							pagedScroll: true,
							loopCount:1,
							scrollButtonPosition:'split',
							marginScrollButtons: 1
						},

						layout: 'carousel',
						items: []
					};

					var imageBase=Ext.jx.getStoreValue({tableName:"CONFIG",fieldName:"CONFIG#IMAGEPATH"});
					for (var i=1; i<=10; i++){
						var imageName=resortRecord.data['RESORT#IMAGE'+i];
						if (!imageName){ continue }
						carousel.items.push({
							style: { margin: '1px 1px 1px 1px'},
							html:{tag: 'img', width:250, height:200, src: imageBase+'/fs_'+imageName, style:{width:250, height:200}}
						});
					}

					if (carousel.items.length){
						return carousel;
					}else{
						return {};
					}


				},
				about:'formResortInfo',
				anchor:"100% 100%",
				layout:"fit",
				items:[{
					style:{padding:'0px !important', margin:'0px !important'},
					height:562,
					layout:"border",
					items:[{
					    region:"center",
					    id:"centerRegionVariables",
						forceFit:true,
						anchor:"100% 100%",
						layout:"fit",
						autoScroll:true,
						style:{padding:'0px !important', margin:'0px !important'},
				        //frame:true,
						items:[{
							html: '&nbsp;'
							}
							//resortRecord.getCarousel()
						]


					}]
				}],
				listeners : {
					beforerender:function(){
						//var form = this.findParentBy(function(item){ return item.about==='formResortInfo' },this);
						var resortRecord = this.resortRecord;
						var center = this.findBy(function(item){ return item.id==='centerRegionVariables' },this)[0];
						//var destBanner = this.findBy(function(item){ return item.id==='destBanner' },this)[0];
						center.removeRange();
						center.add({
							html:resortRecord.template('longdescription')},
							resortRecord.getCarousel()
						);
						center.doLayout();
					}
				}
			}
		}
	}
});

Ext.jx.setTable({
	
	PROSPW : {
	}
})
Ext.jx.setTable({
	SUPERDES:{
		templates:{
			description:
				'{[ values._record.getValue("RESORT#RESORT") ]}<br>'+
				'{GTAW#DDATE} to {GTAW#RDATE}<br>'+
				'{GTAW#ADULT} adults {GTAW#CHILD} children<br>'
		},
		FuncsRow:{
			getTitle:function(){

				var resNum=this.get('GTAW#RESNUM');
				if (!resNum) { return '' }

				var types={P:'Quote',B: 'Booking'};
				return types[this.get('GTAW#TYPE')]+': '+this.get('GTAW#RESNUM');
			}

        },
		forms:{
			DEST:{
				ztest:true,
				listeners:{
					//beforeconnect:function(dataControl){
					//	//dataControl.record.onAddInternal();
					//	//alert('connected record');
					//}
				},
				anchor:"100% 100%",
				layout:"fit",
				autoHeight:true,
				about:"superdes",
                items:[{
					id:'destBanner',
					autoHeight:true,
			        items:[{
			        	style:{display:'none'}
			    	}]

				},{
					height:600,
			        layout:"border",
                    items:[{
			            region:"center",
			            title:"test",

						xtype:'tabpanel',
						enableTabScroll: true,
						plugins:Ext.jx.plugins.Tab_Fix,
						layoutConfig : { renderHidden : true },
						defaults:{
							bodyStyle:{
								padding:'5px'
							},
							border: false,
							autoHeight:true,
							hideMode:'offsets'
						},
						//listeners:{
						//	'beforetabchange':function(tabPanel, currentTab, newTab){
						//		if (newTab) { return newTab.validate() }
						//	}
						//},

						plain:true,
						activeTab: 0,
						border:false,
						id:'wizard_steps_tabs',
						about:'wizard_steps_tabs',
						items:[{
							title:'Resorts',
							anchor:"100% 100%",
							layout:"fit",
							id:'tabVariables',
                            items:[{
								layout:"border",
								height:562,
								//forceFit:true,
								//autoHeight:true,
								items:[{
                                        region:"center",
										forceFit:true,
										anchor:"100% 100%",
										layout:"fit",
										style:{padding:'0px !important', margin:'0px !important'},
										id:'centerRegionVariables',
								        frame:true,
                                        autoScroll:true,
									    items: new Ext.DataView({
											id:'dv',
											style:{
												overflow:'auto'
											},
											//store: 'Ext.jx.getStore("RESORT","ALL")',
											loadingText: 'Testing Superdes...',
											tpl: '<tpl for="."><table class="search-item"><tr><td>'+
												'{['+
												'"<img style=\'float:left; margin:3px\' '+
												'src=\'"+Ext.jx.getStoreValue({tableName:"CONFIG",fieldName:"CONFIG#IMAGEPATH"})+"/TN_"+values["RESORT#IMAGE1"]+'+
												'"\'>'+
												'<b>"+values["RESORT#RESORT"]+"</b>: "+'+
												'Ext.jx.stripTags(values["RESORT#MULTIPLE"])'+
												']}'+
												'</td></tr></table></tpl>',
											autoShow:true,
											autoHeight:true,
											singleSelect:true,
											overClass:'x-view-over',
											itemSelector:'table.search-item',
											listeners:{
												beforerender : function() {
													var store1 = Ext.jx.getStore("RESORT","ALL");
													store1.sort('RESORT#RESORT');
													this.store = store1;

												},
												click : function(d, i, n, e) {

													var test = this.getSelectedRecords()[0];
													var resortRecord = Ext.jx.getRecord({tableName:"RESORT",recordId:test.id})
													
													var forml = new RL.PriceSearch.Service();

													lform.recordProduct=resortRecord;
													lform.title="Lodging";
													var formo=Ext.jx.getTable('RESORT').getForm('INFO');

													oform=Ext.jx.copyForm(formo);
                                                    oform.resortRecord=resortRecord;
													//form.gtawRecord=gtawRecord;
													oform.title="Overview";
													var o_wizard_steps_tabs=this.findParentBy(function(item){ return item.about==='wizard_steps_tabs' },this);

													var dest = o_wizard_steps_tabs.ownerCt;
													var destBanner = dest.ownerCt.findBy(function(item){ return item.id==='destBanner' },this)[0];

													destBanner.removeRange();
													destBanner.add({
														html:resortRecord.data['RESORT#TOPBANNER']
													});
													destBanner.doLayout();

                                                    o_wizard_steps_tabs.removeRange(1);
													o_wizard_steps_tabs.add(oform);
													o_wizard_steps_tabs.add(lform);
												}
											},
											emptyText: 'No Resorts to display'

									})

								}]
							}]

						}]


			          }]
			     }]
			}
		}
	}
});

Ext.ns('RL.Cust');


RL.Cust.Save = Ext.extend(Ext.Panel, {
	
	defaults		: { border : false },

	frame			: true,

//	autoWidth		: true,
//	autoHeight		: true,

	border			: false,
	cls				: 'new-members',

	stepTitle 		: 'Customer',

	title			: 'New Members',

	
	
	constructor : function (config) {
		config = config || {};


		var buttons = [{
			xtype : 'button',
			
			text : 'continue',
			scale : 'large',
			
			iconCls : 'addmember-btn',
			iconAlign: 'left',
			
			handler: this.onContinue,
			scope : this,
			
			style:{
				'margin-left' : '25px'
			}
		}]

		
		if (Ext.jx.getStoreValue('DEPT#CONANON')!=1 && Ext.jx.getStoreValue('DEPT#CONANON')!=2) {
			buttons.push({
				xtype:'button',
				text: '<b>no thanks</b>',
				//iconCls: 'addmember-skip-btn',
				scale: 'medium',

				//scale: 'large',
				//iconAlign: 'left',
				handler: this.onSkip,
				scope : this,
				style:{
					'margin-left':'200px'
					//'padding':'0 10px 0 10px'
				}
			})
		}

		Ext.apply(config, {
			
			layout : 'form',

			items: [!Ext.jx.getStoreValue('DEPT#CONCUSTASK')? {} :{
				baseCls: 'profile-pitch',
				html:Ext.jx.getStoreValue('DEPT#CONCUSTASK')
			},{
				fieldLabel: 'First Name',
				name: 'PROSPW#FIRST',
				width: 200,
				xtype: 'textfield'
				
			},{
				fieldLabel: 'Last Name',
				name: 'PROSPW#LAST',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'Group/Company',
				name: 'PROSPW#GROUP_NAME',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'ARC/IATA No.',
				name: 'PROSPW#IATA',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'Email',
				name: 'PROSPW#EMAIL',
				width: 200,
				vtype: 'email',
				xtype: 'textfield'
			},{
				fieldLabel: 'Email Opt-In',
				name: 'PROSPW#EMAILSPEC',
				value: 'false',
				xtype: 'checkbox'
			},{
				fieldLabel: 'Address 1',
				name: 'PROSPW#ADDRESS',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'Address 2',
				name: 'PROSPW#ADDRESS2',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'City',
				name: 'PROSPW#CITY',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'State/Province',
				name: 'PROSPW#STATE',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'Zip/Postal Code',
				name: 'PROSPW#ZIP',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'Country',
				name: 'PROSPW#COUNTRY',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'Phone (day)',
				name: 'PROSPW#PHONE_DAY',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'Phone (night)',
				name: 'PROSPW#PHONE_NITE',
				width: 200,
				xtype: 'textfield'
			},{
				fieldLabel: 'Fax',
				name: 'PROSPW#FAX',
				width: 200,
				xtype: 'textfield'
			},{
				baseCls: 'required-fields-note',
				width:300,
				html:'An asterisk (*) denotes a required field.'
			//},{
			//
			//	xtype: "buttongroup",
			//	columns: 2,
			//	autoWidth:true,
			//	//border:false,
			//	//xtype: "toolbar",
			//	//slot : "toolbar",
			//	baseCls: 'x-frameless',
			//	//cls: 'x-frameless',
			//
			//	items:buttons

			}],
			
			buttons : buttons,
			
			buttonAlign : 'left'
		});
		//eof apply

		RL.Cust.Save.superclass.constructor.call(this, config);
	},


	initComponent : function(){
		RL.Cust.Save.superclass.initComponent.call(this);
		
		this.addEvents('ready')
	},
	
	

	onContinue : function(){
		if (!this.validate()) {
			this.onInvalid()
			return
		}
		
		var gtawRecord 	= Ext.jx.getStore('GTAW').getAt(0);
		var values		= this.getValues();
		
		var validField	= /#/;
		
		for (var field in values){
			if (validField.test(field)) gtawRecord.data[field]=values[field];
		}
		
		this.fireEvent('ready', this)
	},


	onSkip : function(){
		this.fireEvent('ready', this)
	},

	
	onInvalid : function () {
		Ext.MessageBox.show({
			icon: Ext.MessageBox.ERROR,
			buttons: Ext.Msg.OK,
			title:'Validation Error',
			msg:'Please fill out all required fields'
		});
	},

	
	onRender : function (ct, position) {

		var dept 		= Ext.jx.getRecord({tableName:'DEPT'});
		var custValid 	= dept.get('DEPT#CUSTVALID'); //this contains a concatened list of boolean values on whether or not to display a field and whether that field is required
		
		var fieldStack = [
			"PROSPW#FIRST",	"PROSPW#LAST",		"PROSPW#GROUP_NAME",	"PROSPW#EMAIL",		"PROSPW#PHONE_DAY",		"PROSPW#PHONE_NITE",
			"PROSPW#FAX",	"PROSPW#ADDRESS",	"PROSPW#ADDRESS2",		"PROSPW#CITY",		"PROSPW#STATE",			"PROSPW#ZIP",			"PROSPW#COUNTRY",
			"PROSPW#IATA",	"PROSPW#EMAILSPEC",	"PROSPW#SALESREP",		undefined,			"PROSPW#SYSTEM2",		"PROSPW#REFDES"
		]
		

		for (var fieldIndex=0, marker=0; fieldIndex < fieldStack.length; fieldIndex++, marker+=2 ) {
			var fieldName = fieldStack[fieldIndex];
			if (!fieldName) continue

			var field = this.findBy(function(item){ return item.name===fieldName })[0];
			if (!field) continue 

			var display = (custValid.length >= marker+1 && custValid.substr(marker,1) === 'Y');
			var require = (display && custValid.substr(marker+1,1) === 'Y');
			
			if (display) {
				if (require){
					field.fieldLabel='* '+field.fieldLabel;
					field.allowBlank=false;
				} else
					field.allowBlank=true;

				if (fieldName=='PROSPW#EMAILSPEC') field.checked = true;

			} else {
				field.hideItem();//doesn't work here because it is not part of the form yet
				field.inputType = 'hidden';
			}
		}


		RL.Cust.Save.superclass.onRender.call(this, ct, position);
	}


});
//eof extend

Ext.reg('cust_save', RL.Cust.Save);


//XXX not used code?
//RL.Cust.Save_Wizard = Ext.extend(Ext.ux.Wizard, {
//
//	layout: 'border',
//	plain: true,
//	bodyStyle:{
//		padding:'5px'
//	},
//	buttonAlign:'right',
//	closable: true,
//	buttons:[{
//		text: 'Previous',
//		wizardButton:'prev'
//	},{
//		text: 'Next',
//		wizardButton:'next'
//	},{
//		text: 'Finish',
//		wizardButton:'finish'
//	}],
//
//	constructor : function(config) {
//		config=config || {};
//
//		Ext.apply(config,{
//
//			items: [{
//				region: 'west',
//				width: 150,
//				baseCls:'wizardBookingImg',
//				html:'&#160'
//				//html: '<div class=wizardBookingImg></div>',
//				//style:{
//				//	"background-color":'yellow'
//				//}
//			},{
//				frame: true,
//				region: 'center',
//				//layout: 'anchor',
//				bodyStyle: {
//					padding:'5px'
//				},
//				//items:[{
//				//    stepTitleItem: true
//				//},{
//					//anchor: '100% 100%',
//					hideBorders:true,
//					layout:'card',
//					activeItem: 0,
//					defaults: {border: false, autoScroll:true}
//				//}]
//			}]
//		});
//
//		RL.Cust.Save_Wizard.superclass.constructor.call(this, config);
//	}
//
//
//
//
//
//});
//
//Ext.reg('cust_save_wizard', RL.Cust.Save_Wizard);

