/**
 * @author 3Devil
 */
Ext.namespace('VDC');
var vdc_dbg;
var __debug = false;
var eHandler;

var __states = [
        ['AL', 'Alabama'],
        ['AZ', 'Arizona'],
        ['AR', 'Arkansas'],
        ['CA', 'California'],
        ['CO', 'Colorado'],
        ['CT', 'Connecticut'],
        ['DE', 'Delaware'],
        ['DC', 'District of Columbia'],
        ['FL', 'Florida'],
        ['GA', 'Georgia'],
        ['HI', 'Hawaii'],
        ['ID', 'Idaho'],
        ['IL', 'Illinois'],
        ['IN', 'Indiana'],
        ['IA', 'Iowa'],
        ['KS', 'Kansas'],
        ['KY', 'Kentucky'],
        ['LA', 'Louisiana'],
        ['ME', 'Maine'],
        ['MD', 'Maryland'],
        ['MA', 'Massachusetts'],
        ['MI', 'Michigan'],
        ['MN', 'Minnesota'],
        ['MS', 'Mississippi'],
        ['MO', 'Missouri'],
        ['MT', 'Montana'],
        ['NE', 'Nebraska'],
        ['NV', 'Nevada'],
        ['NH', 'New Hampshire'],
        ['NJ', 'New Jersey'],
        ['NM', 'New Mexico'],
        ['NY', 'New York'],
        ['NC', 'North Carolina'],
        ['ND', 'North Dakota'],
        ['OH', 'Ohio'],
        ['OK', 'Oklahoma'],
        ['OR', 'Oregon'],
        ['PA', 'Pennsylvania'],
        ['RI', 'Rhode Island'],
        ['SC', 'South Carolina'],
        ['SD', 'South Dakota'],
        ['TN', 'Tennessee'],
        ['TX', 'Texas'],
        ['UT', 'Utah'],
        ['VT', 'Vermont'],
        ['VA', 'Virginia'],
        ['WA', 'Washington'],
        ['WV', 'West Virginia'],
        ['WI', 'Wisconsin'],
        ['WY', 'Wyoming']
    ];

var __cctype = [
		['MC','Master Card'],
		['VISA','Visa'],
		['DISCOVER','Discover'],
		['AMEX','American Express']
	];
	
var __curentcctype = false;

function __getOption(_options, oid, rid) {
	oid = parseInt(oid, 10);
	rid = parseInt(rid, 10);
	for (option in _options) {
		if (option == "remove") {
			continue;
		}
		co = _options[option];
		if (parseInt(co.oid, 10) == oid) {
			for (result in co.results) {
				if (result == "remove") {
					continue;
				}
				ro = co.results[result];
				if (parseInt(ro.rid, 10) == rid) {
					return[co.name, ro.option, ro.optionid, ro.price];
				}
			}
		}
	}
	return [];
}

function isValidZipCode(value) {
	var re = /^\d{5}([\-]\d{4})?$/;
	return (re.test(value));
}

function isValidCreditCard(value) {
	if (!__curentcctype) {
		return false;
	}
	
	switch (__curentcctype) {
		case 'MC':
			if (/^5[1-5][0-9]{14}$/.test(value)) {
				return true;
			}
			else {
				return false;
			}
			break;
		case 'VISA': 
			if (/^4[0-9]{12}(?:[0-9]{3})?$/.test(value)) {
				return true;
			}
			else {
				return false;
			}
			break;
		case 'DISCOVER': 
			if (/^6011[0-9]{12}$/.test(value)) {
				return true;
			}
			else {
				return false;
			}
			break;
		case 'AMEX': 
			if (/^3[47][0-9]{13}$/.test(value)) {
				return true;
			}
			else {
				return false;
			}
			break;
	}
}
function isValidExpirationDate(value) {
	if (/(0[1-9]|1[012])\/(19|20)[0-9]{2}/.test(value)) {
		return true;
	} else {
		return false;
	}
}
VDC.ProductsPanel = function(config) {
	Ext.apply(this, {
		collapsible:false,
		border:false,
		width:200,
		height:460,
		x:741,
		y:111,
		layout:'border',
		lines:false,
		bodyStyle:'background-color:transparent; z-index:50000',
		cls:'vdc-products-list'
	});
	
	this.Toggle = new Ext.Button({
		root:this,
		text:"Preview Positions",
		enableToggle:true,
		pressed:false,
		tooltip:'Click to Show/Hide Positions on Island',
		listeners: {
			toggle : {
				fn: function (b,pressed) {
					this.root.app.Zones.showAll(pressed);
				}
			}
		}
	});
	
	this.MPanel = new Ext.Panel({
		region:'east',
		collapsible: true,
		cmargins: '0 0 0 0',
		title: 'Island Options',
		width:200,
		maxSize:200,
		minSize:24,
        rootVisible:false,
        lines:false,
        autoScroll:true,
        collapseFirst:false,
//		collapsed:true,
		titleCollapse:true,
		cls:'vdc-panel x-hidden',
		autoShow:true,
		floatable: false,
		listeners: {
			beforecollapse: {
				fn : function(p) {
					p.ownerCt.app.SlideBox.MPanel.collapse(false);
					p.ownerCt.app.Details.MPanel.collapse(false);					
				}
			},
			collapse : {
				fn : function(p) {
					pos = p.ownerCt.getPosition(true);
					p.ownerCt.setPosition(pos[0] + p.width - p.minSize, pos[1]);
					p.ownerCt.setSize({
						width: p.minSize
					});
				}
			},
			beforeexpand : {
				fn : function(p) {
					pos = p.ownerCt.getPosition(true);
					p.ownerCt.setPosition(pos[0] - p.width + p.minSize, pos[1]);
					p.ownerCt.setSize({
						width: p.width
					});
				}
			}
		},
		layout: 'accordion',
		layoutConfig : {
			animate:false,
			fill:true,
			titleCollapse:true,
			hideCollapseTool:true
		},
		buttons:[this.Toggle]
	});
	
	this.items = [
		this.MPanel,
		new Ext.Panel({
			region:'center',
			border: false,
			lines:false,
			bodyStyle:'background-color:transparent'	
		})
	];
	
	Ext.apply(this, config);
	VDC.ProductsPanel.superclass.constructor.call(this);
};
Ext.extend(VDC.ProductsPanel, Ext.Panel, {
	setZone: function (z) {
		if (z > this.MPanel.items.getCount()) {
			return false;
		}
		cp = this.MPanel.find('zoneId',z)[0] || false;
		if (cp && !cp.disabled) {
			cp.expand();
		}
	}
});

VDC.PricePanel = function(config) {
	Ext.apply(this, {
		border:false,
		lines:false,
		width: 250,
		height: 170,
		x: -1,
		y: -2,
		layout:'border',
		bodyStyle:'background-color:transparent; z-index:50000',
		cls:'vdc-price-box'		
	});
	
	this.MPanel = new Ext.Panel({
		region:'north',
		collapsible: true,
		cmargins: '0 0 0 0',
		bodyStyle: 'padding: 10px 20px; 0px 20px;background-color:transparent',
		cls:'vdc-panel x-hidden',
		autoShow:true,
		title: 'Setup Price',
		collapsedTitle: 'Setup Price',
		collapsedTitleStyle: 'font-weight:bold; line-height:20px; padding-left:5px; color:' + (__priceColor || "#FFFFFF"),
		titleCollapse:true,
		width:250,
		maxSize:120,
		height:170,
		minSize:22,
        rootVisible:false,
		border:true,
        lines:true,
		bodyBorder:true,
        autoScroll:false,
        collapseFirst:false,
//		collapsed:true,
		floatable: false,
		autoWidth: false,
		labelWidth: 100,
		layout:'form',
		listeners: {
			'collapse' : {
				fn : function(p) {
					p.ownerCt.setSize({
						height: p.minSize
					});					
				},
				scope: this
			},
			'beforeexpand' : {
				fn : function(p) {
					p.ownerCt.setSize({
						height: p.height
					});										
				},
				scope: this
			}
		}
	});

/*	
	this.base_price = this.MPanel.add(new Ext.form.MoneyField({
		fieldLabel: 'Base Price',
		name: 'base_price',
		readOnly: true,
		width: 100,
		cls: 'input-right x-hidden',
		value: '0',
		inputValue: '0'
	}));
*/	
	this.island_price = this.MPanel.add(new Ext.form.MoneyField({
		fieldLabel: 'Island Price',
		name: 'island_price',
		width: 100,
		readOnly: true,
		cls: 'input-right',
		value: '0',
		inputValue: '0'
	}));

	this.options_price = this.MPanel.add(new Ext.form.MoneyField({
		fieldLabel: 'Hardware Price',
		name: 'option_price',
		width: 100,
		readOnly: true,
		cls: 'input-right',
		value: '0',
		inputValue: '0'
	}));
	
	this.shipping = this.MPanel.add(new Ext.form.MoneyField({
		fieldLabel: 'Shipping',
		name: 'shipping',
		readOnly: true,
		width: 100,
		cls: 'input-right',
		value: '0',
		inputValue: '0'
	}));
	
	this.total = this.MPanel.add(new Ext.form.MoneyField({
		fieldLabel: 'Total Price',
		name: 'total',
		readOnly: true,
		width: 100,
		itemCls: 'vdc-price',
		cls: 'input-right input-red',
		value: '0',
		inputValue: '0'
	}));
/*
	this.MPanel.add(new Ext.Button({
		text: 'Request Quote',
		cls: 'vdc-quote',
		minWidth: 200,
		handler: function() {
			app.doQuote();
		}
	}));
*/
	this.MPanel.add(new Ext.Button({
		text: 'Checkout',
		cls: 'vdc-quote',
		minWidth: 200,
		handler: function() {
			app.doCheckout();
		}
	}));

	this.items = [
		this.MPanel,
		new Ext.Panel({
			region:'center',
			border: false,
			lines:false,
			bodyStyle:'background-color:transparent'	
		})
	];

	Ext.apply(this, config);
	VDC.PricePanel.superclass.constructor.call(this);
};
Ext.extend(VDC.PricePanel, Ext.Panel, {
	recalculate: function() {
		var tot = 0;
		var shipping = 0;
		var total = 0;
		
		for (i in this.app.setup) {
			if (this.app.setup[i]) {
				if (Ext.type(this.app.setup[i]) == "array") {
					if (!this.app.setup[i].length) {
						continue;
					}
					for (k in this.app.setup[i]) {
						if (Ext.type(this.app.setup[i][k]) == "function") {
							continue;
						}
						data = this.app.PStore.getById(this.app.setup[i][k]).data;
						tot += parseFloat(data.price);
						//shipping += parseFloat(data.shipping);
						for (j in this.app.options[this.app.setup[i][k]]) {
							cp = parseFloat(__getOption(data.options, j, this.app.options[this.app.setup[i][k]][j])[3]);
							tot += isNaN(cp) ? 0.0 : cp;
						}
					}
				}
				else {
					data = this.app.PStore.getById(this.app.setup[i]).data;
					tot += parseFloat(data.price);
					//shipping += parseFloat(data.shipping);
					for (j in this.app.options[this.app.setup[i]]) {
						cp = parseFloat(__getOption(data.options, j, this.app.options[this.app.setup[i]][j])[3]);
						tot += isNaN(cp) ? 0.0 : cp;
					}
				}
			}
		}

		for (i in this.app.standard_setup) {
			if (i == 999) {
				continue;
			}
			if (this.app.standard_setup[i]) {
				if (Ext.type(this.app.standard_setup[i]) == "array") {
					if (!this.app.standard_setup[i].length) {
						continue;
					}
					for (k in this.app.standard_setup[i]) {
						if (Ext.type(this.app.standard_setup[i][k]) == "function") {
							continue;
						}
						data = this.app.PStore.getById(this.app.standard_setup[i][k]).data;
						tot += parseFloat(data.price);
						//shipping += parseFloat(data.shipping);
						for (j in this.app.options[this.app.standard_setup[i][k]]) {
							cp = parseFloat(__getOption(data.options, j, this.app.options[this.app.standard_setup[i][k]][j])[3]);
							tot += isNaN(cp) ? 0.0 : cp;
						}
					}
				}
				else {
					data = this.app.PStore.getById(this.app.standard_setup[i]).data;
					tot += parseFloat(data.price);
					//shipping += parseFloat(data.shipping);
					for (j in this.app.options[this.app.standard_setup[i]]) {
						cp = parseFloat(__getOption(data.options, j, this.app.options[this.app.standard_setup[i]][j])[3]);
						tot += isNaN(cp) ? 0.0 : cp;
					}
				}
			}
		}
		
		if (tot != parseFloat(this.options_price.getValue())) {
			this.options_price.setValue(tot);
			this.MPanel.body.highlight();
		}
		
//		tot = tot + parseFloat(this.additional.getValue());
//		tot = tot + parseFloat(this.base_price.getValue());
		shipping = this.getShipRate(tot);
		total = parseFloat(this.island_price.getValue()) + tot + shipping;
		this.total.setValue(total);
		this.shipping.setValue(shipping);
		this.layout.north.collapsedEl.first().update(__totalprice + ": " + Ext.util.Format.usMoney(total));
	},
	
	getShipRate: function(value) {
		value = parseFloat(value);
		if (value > 0 && value <= 29.99) return 8.99;
		if (value >= 30 && value <= 49.99) return 12.00;
		if (value >= 50 && value <= 74.99) return 16.00;
		if (value >= 75 && value <= 149.99) return 25.00;
		if (value >= 150 && value <= 199.99) return 30.00;
		if (value >= 200 && value <= 249.99) return 35.00;
		if (value >= 250 && value <= 399.99) return 39.00;
		if (value >= 400) return 0.00;
		return 0.00;
	}
});

VDC.SlidePanel = function (config) {
	Ext.apply(this,{
		border:false,
		width: 660,
		height: 140,
		x: -2,
		y: 431,
		layout:'border',
		lines:false,
		bodyStyle:'background-color:transparent; z-index:50000',
		cls:'vdc-slide-box'
	});
	
	this.MPanel = new Ext.Panel({
		region:'west',
		collapsible: true,
		cmargins: '0 0 0 0',
		bodyStyle: 'padding: 10px; text-align: center',
		width:660,
		maxSize:660,
		minSize:24,
        rootVisible:false,
        lines:false,
        autoScroll:false,
        collapseFirst:false,
		collapsed:true,
		hideCollapseTool:true,
		cls:'vdc-panel',
		floatable: false,
		layout:'absolute',
		listeners: {
			'collapse' : {
				fn : function(p) {
					p.ownerCt.setWidth(p.minSize);
					p.ownerCt.ownerCt.ownerCt.SlideScroll.hide();
					p.ownerCt.hide();
				},
				scope: this
			}
			,'beforeexpand' : {
				fn : function(p) {
					p.ownerCt.show();
					p.ownerCt.setWidth(p.maxSize);
				},
				scope: this
			}
			,'expand' : {
				fn : function(p) {
					if (p.items.length > 6) {
						p.ownerCt.ownerCt.ownerCt.SlideScroll.show();
					}
				}
			}
			,'render' : {
				fn: function(ct) {
					this.body.ownerCt = this;
					this.body.on('mousewheel', function(e) {
						var dir = e.getWheelDelta();
						this.scroll(dir == 1 ? 'top' : 'down', 140, true);
					});
				}
			}
		}
	});
	
	this.items = [
		this.MPanel,
		new Ext.Panel({
			region:'center',
			border: false,
			lines:false,
			bodyStyle:'background-color:transparent'
		})
	];	
	
	Ext.apply(this, config);
	VDC.SlidePanel.superclass.constructor.call(this);
};
Ext.extend(VDC.SlidePanel, Ext.Panel, {	
	addItem: function(record, dir, prefix, selected) {
//		console.log(record.data.pid, ' ', selected);
		selected = selected || false;
		ai = this.app.ProductsList.MPanel.layout.activeItem || false;
		inactive = ai.zoneId ? this.app.restrictions[ai.zoneId].indexOf(parseInt(record.data.pid, 10)) != -1 || false : false;
		this.MPanel.add(new VDC.ProductSelection({
			source:this.app.island.sets + dir + prefix + record.data.src + '.png',
			image:this.app.island.sets + 'tn/' + dir + record.data.src + '.jpg',
			price:Ext.util.Format.usMoney(record.data.price),
//			ctitle:record.data.name + ' #' + record.data.pid,
			ctitle:record.data.name,
			record:record,
			productID: record.data.pid,
			y:Math.floor(this.MPanel.items.length/6)*140,
			x:(this.MPanel.items.length%6)*110
		}, selected, inactive, ai.multiSelect));
	},
	
	setAll: function(flag) {
		Ext.each(this.MPanel.items.getRange(), function(obj){
			obj.setValue(flag);
		});
	},
	
	setProduct: function(pid, flag) {
		Ext.each(this.MPanel.items.getRange(), function(obj){
			if(obj.productID == pid) {
				obj.findByType('checkbox')[0].setValue(flag);
			}
		});
	},
	
	removeAll: function() {
		while(app.SlideBox.MPanel.remove(app.SlideBox.MPanel.items.get(0), true)) {}
	}
});

VDC.ProductSelection = function(config, selected, inactive, check) {
	selected = selected || false;
	inactive = inactive || false;
	check = check || false;
	this.image = 'images/grill.jpg';
	this.ctitle = 'Title';
	this.price = '$0.00';
	this.inactive = inactive;
	this.check = check;
	Ext.apply(this, config);
	
	Ext.apply(this, {
		vdctype:'product-selector',
		width:110,
		height:140,
		layout:'absolute',
		cls:'vdc-panel' + (selected ? ' selected' : ''),
		baseCls:'vdc-img-panel',
		items:[{
			xtype:'box',
			autoEl: {tag:'img', src:this.image},
			cls:'vdc-img',
			x:15,
			y:35
		}, {
			xtype:'checkbox',
			cls:'vdc-check' + (this.check ? '' : ' x-hidden'),
			x:78,
			y:37,
			checked:selected
		}, {
			xtype:'box',
			x:78,
			y:37,
			autoEl: {tag:'img', src:'/cdt/empty.gif', style:'width:16px;height:16px;z-index:55000'}
		}, {
			xtype:'box',
			autoEl: {tag:'span', html:this.ctitle},
			width:100,
			x:5,
			y:8
		}, {
			xtype:'box',
			autoEl: {tag:'span', html:this.price},
			width:110,
			y:118
		}]
	});

	VDC.ProductSelection.superclass.constructor.call(this);
};
Ext.extend(VDC.ProductSelection, Ext.Panel, {
	onRender: function(ct) {
		VDC.ProductSelection.superclass.onRender.call(this, ct);
		if (this.inactive) {
			this.addClass('inactive');
		}
		this.body.ownerCt = this;
		this.body.on('click', function(e) {
			this.ownerCt.onClick(this);
			//e.stopEvent();
		});
		this.body.on('dblclick', function(e){
			this.ownerCt.onDblClick(this);
			//e.stopEvent();
		});
		if (Ext.isIE) {
			this.body.on('mouseenter', function(){
				this.ownerCt.addClass('vdc-img-panel-over');
			});
			this.body.on('mouseleave', function(){
				this.ownerCt.removeClass('vdc-img-panel-over');
			});
		}
		else {
			this.body.on('mouseover', function(){
				this.ownerCt.addClass('vdc-img-panel-over');
			});
			this.body.on('mouseout', function(){
				this.ownerCt.removeClass('vdc-img-panel-over');
			});
		}
	},
	
	setValue: function(flag) {
//		this.findByType('checkbox')[0].setValue(flag);
		if (flag) {
			this.addClass('selected');
		}
		else {
			this.removeClass('selected');
		}
	},
	
	onClick: function() {
		this.ownerCt.ownerCt.setAll(false);
		this.setValue(true);
		this.ownerCt.ownerCt.app.Details.load({
			image: this.image,
			name: this.record.data.name,
			descr: this.record.data.descr,
			price: Ext.util.Format.usMoney(this.record.data.price),
			source: this.source,
			pid: this.record.data.pid,
			manual : this.record.data.manual,
			specs: this.record.data.specs,
			brochure: this.record.data.brochure,
			linedrawing: this.record.data.linedrawing,
			width: this.record.data.width,
			height: this.record.data.height,
			depth: this.record.data.depth,
			sku: this.record.data.sku,
			mfg: this.record.data.mfg
		});
		this.ownerCt.ownerCt.app.ProductsList.MPanel.layout.activeItem.selectedProduct = this.record.data.pid;
	},

	onDblClick: function() {
//		if (Ext.isGecko && __debug) console.log('detailsLoad >' + this.record.data.pid);
		this.ownerCt.ownerCt.setAll(false);
		this.setValue(true);
/*		this.ownerCt.ownerCt.app.Details.load({
			image: this.image,
			name: this.record.data.name,
			descr: this.record.data.descr,
			price: Ext.util.Format.usMoney(this.record.data.price),
			source: this.source,
			pid: this.record.data.pid,
			manual : this.record.data.manual,
			specs: this.record.data.specs,
			brochure: this.record.data.brochure,
			linedrawing: this.record.data.linedrawing,
			width: this.record.data.width,
			height: this.record.data.height,
			depth: this.record.data.depth,
			sku: this.record.data.sku,
			mfg: this.record.data.mfg
		});
*/		this.ownerCt.ownerCt.app.ProductsList.MPanel.layout.activeItem.selectedProduct = this.record.data.pid;
		this.ownerCt.ownerCt.app.Option.load(this.record.data.pid);
	}
});

VDC.ScrollSection = function(config) {
	Ext.apply(this, {
		vdctype: 'scroller',
		x:658,
		y:430,
		width:25,
		height:140,
		layout:'absolute',
		bodyStyle:'z-index:50000',
		border:false,
		lines:false,
		items:[
			new Ext.Panel({
				border:false,
				lines:false,
				width:25,
				height:70,
				x:0,
				y:0,
				cls:'vdc-arrow-up',
				listeners: {
					'render': {
						fn: function(ct) {
							this.body.ownerCt = this;
							this.body.on('click', function(e) {
								this.ownerCt.ownerCt.target.body.scroll('up',140,true);
							});
							this.body.on('mouseover', function(e) {
								this.addClass('vdc-over');
							});
							this.body.on('mouseout', function(e) {
								this.removeClass('vdc-over');
							});
						}
					}
				}
			}),
			new Ext.Panel({
				border:false,
				width:25,
				height:70,
				x:0,
				y:70,
				cls:'vdc-arrow-down',
				listeners: {
					'render': {
						fn: function(ct) {
							this.body.ownerCt = this;
							this.body.on('click', function(e) {
								this.ownerCt.ownerCt.target.body.scroll('down',140,true);
							});
							this.body.on('mouseover', function(e) {
								this.addClass('vdc-over');
							});
							this.body.on('mouseout', function(e) {
								this.removeClass('vdc-over');
							});
						}
					}
				}
			})
		]
	});

	Ext.apply(this, config);
	VDC.ScrollSection.superclass.constructor.call(this);
};
Ext.extend(VDC.ScrollSection, Ext.Panel);

VDC.Details = function(config) {
	Ext.apply(this,{
		border:false,
		width: 450,
		height: 300,
		x: 0,
		y: 130,
		layout:'border',
		lines:false,
		bodyStyle:'background-color:transparent; z-index:50000',
		cls:'vdc-details-box',
		pid:0
	});
	
	this.Launcher = new Ext.Button({
		root: this,
		text:'Add to Island',
		cls:'vdc-add',
		minWidth:150,
		handler: function(b, e) {
			this.root.app.Option.load(this.root.pid);
		}
	});
	
	this.MPanel = new Ext.Panel({
		region:'west',
		collapsible: true,
		cmargins: '0 0 0 0',
		bodyStyle: 'padding: 5px;',
		title: 'Product Details',
		width:450,
		maxSize:450,
		minSize:20,
        rootVisible:false,
        lines:false,
        autoScroll:true,
        collapseFirst:false,
		collapsed:true,
		floatable: false,
		buttons:[
			this.Launcher
		],
		listeners: {
			'collapse' : {
				fn : function(p) {
//					pos = p.ownerCt.getPosition(true);
//					p.ownerCt.setSize({width: p.minSize});
					this.hide();
				},
				scope: this
			},
			'beforeexpand' : {
				fn : function(p) {
//					pos = p.ownerCt.getPosition(true);
//					p.ownerCt.setSize({width: p.width});
					this.show();
					this.ownerCt.ownerCt.IDetails.MPanel.collapse();
				},
				scope: this
			}
		}
	});
	
	this.items = [
		this.MPanel,
		new Ext.Panel({
			region:'center',
			border: false,
			lines:false,
			bodyStyle:'background-color:transparent'	
		})
	];	
	
	Ext.apply(this, config);
	VDC.Details.superclass.constructor.call(this);	
};
Ext.extend(VDC.Details, Ext.Panel, {
	load: function(record) {
/*
		if (this.pid == record.pid) {
			this.MPanel.expand();
			return true;
		}
*/		
		this.MPanel.collapse(false);
		if (!this.template) {
			this.template = new Ext.XTemplate(
				"<img src='{image}' style='float:left;margin:0 10px 0 0;' />"
				,"<div style='font-weight:bold;font-size:115%;text-align:center;margin-bottom:5px'>"
				,'<tpl if "mfg">{mfg} </tpl>'
				,"{name}</div>"
				,"<div style='text-align:center;margin-bottom:5px;font-size:120%'><b>{price}</b></div>"
				,"<div style='text-align:center;margin-bottom:5px;font-size:120%'>Product SKU: <b>[{sku}]</b></div>"
				,'<tpl if="manual || specs || brochure || linedrawing"><div class="vdc-specs">'
				,'<p><b>Documentation</b> (Click to download)</p>'
				,'<tpl if="manual">[<a href="{manual}" target="_blank">Manual</a>]</tpl>'
				,'<tpl if="specs"> [<a href="{specs}" target="_blank">Product Specification</a>]</tpl>'
				,'<tpl if="brochure"> [<a href="{brochure}" target="_blank">Brochure</a>]</tpl>'
				,'<tpl if="linedrawing"> [<a href="{linedrawing}" target="_blank">Line Drawings</a>]</tpl>'
				,"</div></tpl>"
				,'<tpl if "width &gt; 0 || height &gt; 0 || depth &gt; 0">'
				,'<div class="vdc-specs"><b>Product Dimensions</b><br/>'
				,'<tpl if="width"><b>W</b>idth: <b>{width}" </b></tpl>'
				,'<tpl if="height"><b>H</b>eight: <b>{height}" </b></tpl>'
				,'<tpl if="depth"><b>D</b>epth: <b>{depth}" </b></tpl>'
				,'</div></tpl>'
				,"<div style='text-align:justify;line-height:125%;clear:both'>{descr}</div>"
				,'<tpl if="width &gt; 0 || height &gt; 0 || depth &gt; 0"><div class="vdc-dimens">'
				,"</div></tpl>"				
			);
		}

		this.pid = record.pid;
		this.MPanel.body.update(this.template.applyTemplate(record));
		this.MPanel.expand(false);
	}
});

VDC.OptionsSelector = function(config) {
	this.Form = new Ext.FormPanel({
		width:450,
		lines:false,
		border:false,
		bodyBorder:false,
		bodyStyle:'padding:8px;background-color:transparent',
		labelWidth:200,
		items:[{
			xtype:'hidden',
			name:'pid',
			value:0
		}],
		buttons:[{
			text:'OK',
			minWidth:100,
			root:this,
			handler: function() {
				if (this.ownerCt.getForm().isValid()) {
					Ext.each(this.ownerCt.findByType('combo'), function(obj){
						this.root.app.options[this.root.productId][obj.name] = obj.getValue();
					}, this);
					this.root.app.setIsland(this.root.zoneId, this.root.productId);
					this.root.app.Details.MPanel.collapse(false);
					this.root.app.Option.hide();
				}
			}
		}]
	});
	
	Ext.apply(this,{
		width:465,
		modal:true,
		title:'Choose Right Options',
		closable:true,
		closeAction:'hide',
		resizable:false,
		draggable:false,
		lines:false,
		bodyBorder:false,
		bodyStyle:'padding:8px;background-color:transparent',
		items:[this.Form],
		pid:0,
		app:this
	});
	
	Ext.apply(this, config);
	VDC.OptionsSelector.superclass.constructor.call(this);
};
Ext.extend(VDC.OptionsSelector, Ext.Window, {
	load: function(pid, override) {
		if (!this.rendered) {
			this.show();
			this.hide();
		}

		var tValue;
		while (this.Form.remove(this.Form.items.get(0), true)) {}
		
		p = this.app.PStore.getById(pid);
//		if (Ext.isGecko && __debug) console.log(p.data);			
		if (p.data.options && p.data.options.length > 0) {
			this.zoneId = this.app.ProductsList.MPanel.layout.activeItem.zoneId;
			this.productId = pid;
			
			for(var i=0,c=p.data.options.length;i<c;i++) {
				var temp = [];
				var def = null;
				for (t in p.data.options[i].results) {
					if (t != "remove") {
						if (def === null) {
							def = p.data.options[i].results[t].rid;
						}						
						temp[t] = p.data.options[i].results[t];
					}
				}

//				tValue = this.app.options[pid][p.data.options[i].oid];
				tValue = this.app.options[pid][p.data.options[i].oid] === undefined ? 
					(p.data.options[i].mandatory == "Y" ? null : def) : this.app.options[pid][p.data.options[i].oid];
					
				this.Form.add({
					xtype:'combo',
					plugins:new Ext.ux.plugins.PriceCombo(),
					fieldLabel:p.data.options[i].name + (p.data.options[i].mandatory == "N" ? '' : ' (required option)'),
					id:'oid_' + p.data.options[i].oid,
					name: p.data.options[i].oid,
					mode:'local',
					width:200,
					editable:false,
					forceSelection:true,
					allowBlank:p.data.options[i].mandatory == "N",
					blankText:'This option is required',
					msgTarget:'under',
					triggerAction:'all',
					emptyText:'Select Option',
					store: new Ext.data.SimpleStore({
						data:temp,
						id:'rid',
						fields:[
							{
								name: 'rid',
								mapping: 'rid'
							},{
								name: 'option',
								mapping: 'option'
							}, {
								name: 'price',
								mapping: 'price'
							}
						]
					}),
					displayField:'option',
					valueField:'rid',
					priceField:'price',
					value:tValue
				});
			}
			this.doLayout();
			this.show();	
		}
		else {
			cz = this.app.ProductsList.MPanel.layout.activeItem.zoneId;
			this.app.Details.hide();
			this.app.setIsland(cz,pid);
		}
	}
});

VDC.IDetails = function(config) {
	Ext.apply(this, {
		border:false,
		lines:false,
		width: 290,
		height: 350,
		x: 270,
		y: -1,
		layout:'border',
		bodyStyle:'background-color:transparent; z-index:50000',
		cls:'vdc-price-box'		
	});
	
	this.MPanel = new Ext.Panel({
		region:'north',
		collapsible: true,
		cmargins: '0 0 0 0',
		bodyStyle: 'padding: 5px 5px; 5px 5px',
		cls:'x-hidden',
		autoShow:true,
		title: 'Island Details',
		collapsedTitle: 'Island Details:<span style="color:#666;margin-left:70px;">Click here to view &#0187;</span>',
		collapsedTitleStyle: 'font-weight:bold; line-height:20px; padding-left:5px; color:#000000',
		titleCollapse:true,
		width:290,
		maxSize:350,
		height:350,
		minSize:22,
        rootVisible:false,
		border:true,
        lines:true,
		bodyBorder:true,
        autoScroll:true,
        collapseFirst:false,
//		collapsed:true,
		floatable: false,
		autoWidth: false,
		labelWidth: 100,
		layout:'form',
		listeners: {
			'collapse' : {
				fn : function(p) {
					p.ownerCt.setSize({
						height: p.minSize
					});					
				},
				scope: this
			},
			'beforeexpand' : {
				fn : function(p) {
					p.ownerCt.setSize({
						height: p.height
					});
					this.ownerCt.ownerCt.Details.MPanel.collapse();
				},
				scope: this
			}
		}
	});
		
	this.items = [
		this.MPanel,
		new Ext.Panel({
			region:'center',
			border: false,
			lines:false,
			bodyStyle:'background-color:transparent'	
		})
	];

	Ext.apply(this, config);
	VDC.IDetails.superclass.constructor.call(this);
};
Ext.extend(VDC.IDetails, Ext.Panel, {
	load: function(record) {
		if (record.pid) {
			record.data = this.app.PStore.getById(record.pid).data;
		}
		if (!this.template) {
			this.template = new Ext.XTemplate(
				"<b>{island}</b><br/>"
				,"<img src='{sets}/linedrawing.jpg' style='float:left;margin:10px 5px 5px 0;' />"
				,'<tpl for="data">'
				,'<tpl if="manual || specs || brochure || linedrawing"><div class="vdc-specs">'
				,'<p><b>Documentation</b> (Click to download)</p>'
				,'<tpl if="linedrawing">[<a href="{linedrawing}" target="_blank">Detailed Linedrawing</a>]</tpl>'
				,"</div></tpl>"
				,'<tpl if "width &gt; 0 || height &gt; 0 || depth &gt; 0">'
				,'<div class="vdc-specs"><b>Product Dimensions</b><br/>'
				,'<tpl if="width"><b>W</b>idth: <b>{width}" </b></tpl>'
				,'<tpl if="height"><b>H</b>eight: <b>{height}" </b></tpl>'
				,'<tpl if="depth"><b>D</b>epth: <b>{depth}" </b></tpl>'
				,'</div></tpl>'
				,'<p><b>Description</b></p>'
				,"<p style='text-align:justify'>{descr}</p>"
				,'</tpl>'
			);
		}		
		this.MPanel.body.update(this.template.applyTemplate(record));
	},
	
	load2: function(record) {
		if (record.pid) {
			record.data = this.app.PStore.getById(record.pid).data;
		}
		if (!this.template) {
			this.template = new Ext.XTemplate(
				"<b>{island}</b><br/>"
				,"<img src='{sets}/linedrawing.jpg' style='float:left;margin:10px 5px 5px 0;' />"
				,'<tpl for="data">'
				,'<tpl if="manual || specs || brochure || linedrawing"><div class="vdc-specs">'
				,'<p><b>Documentation</b> (Click to download)</p>'
				,'<tpl if="linedrawing">[<a href="{linedrawing}" target="_blank">Detailed Linedrawing</a>]</tpl>'
				,"</div></tpl>"
				,'<tpl if "width &gt; 0 || height &gt; 0 || depth &gt; 0">'
				,'<div class="vdc-specs"><b>Product Dimensions</b><br/>'
				,'<tpl if="width"><b>W</b>idth: <b>{width}" </b></tpl>'
				,'<tpl if="height"><b>H</b>eight: <b>{height}" </b></tpl>'
				,'<tpl if="depth"><b>D</b>epth: <b>{depth}" </b></tpl>'
				,'</div></tpl>'
				,'<p><b>Description</b></p>'
				,"<p style='text-align:justify'>{descr}</p>"
				,'</tpl>'
			);
		}		
		this.MPanel.body.update(this.template.applyTemplate(record));
	}
});

VDC.Application = function(config) {
 	Ext.apply(this, {
        layout:'fit',
        width:954,
        height:602,
		closable:false,
		title:_application,
        closeAction:'destroy',
        plain: false,
		modal: false,
		resizable: false,
		draggable: false,
		url: false,
		renderTo: document.body,
		pState: {},
		cls:'x-hidden',
		autoShow:true,
		pToggled:false,
		tools:[{
			id:'email',
			root:this,
			handler: function() {
				app.doEmail();
			},
			qtip:'E-Mail to a friend your design',
			scope: this
		},{
			id:'print',
			root:this,
			handler: function() {
				app.doPrint();
			},
			qtip:'Print your design',
			scope: this
		},{
			id:'login',
			root:this,
			handler: function() {
				if (this.userinfo.userid !== '') {
					this.doLogout();
				} else {
					this.doLogin();
				}
			},
			scope: this,
			qtip: 'Sign In into the application'
		},{
			id:'profile',
			root:this,
			handler: function() {
				app.doProfile();
			},
			qtip:'Update your profile',
			scope: this
		},{
			id:'help',
			handler: function() {
				if (this.Instructions.hidden || !this.Instructions.rendered) {
					this.Instructions.show();
				}
				else {
					this.Instructions.hide();
				}
			},
			qtip:'Show/Hide the application help',
			scope: this
		}]
	});
	
	Ext.apply(this, config);
	
	this.EData = [];
	
	this.IRecord = Ext.data.Record.create([
			{name:'id', mapping:'id'},
			{name:'icon', mapping:'icon'},
			{name:'island', mapping:'island'}
	]);
	
	this.StoreA = new Ext.data.Store({
		data:this.EData,
		reader: new Ext.data.ArrayReader({
			id:'id'
		}, this.IRecord),
		autoLoad:true
	});
	
	this.StoreB = new Ext.data.Store({
		data:this.EData,
		reader: new Ext.data.ArrayReader({
			id:'id'
		}, this.IRecord),
		autoLoad:true
	});
	
	if (this.url) {
		this.Store = new Ext.data.JsonStore({
			url: this.url,
			root: 'islands',
			id: 'id',
			ownerCt: this,
			listeners: {
				'load': {
					fn: function(st, records, options){
						//this.ownerCt.show();
																
						Ext.each(records, function(rec, index){
							if (parseFloat(rec.data.baseprice) > 0) {
								app.StoreB.add(new app.IRecord({
									'id': rec.data.id,
									'icon': rec.data.icon,
									'island': rec.data.island
								}));
							}
							else {
								app.StoreA.add(new app.IRecord({
									'id': rec.data.id,
									'icon': rec.data.icon,
									'island': rec.data.island
								}));
							}
						});

						sA = app.StoreA.getRange();
						Ext.each(sA, function(rec, index){
							try {
								cnt = app.SLandingRight.getComponent(0).items.getCount();
							} catch(e) {
								cnt = 0;
							}
							this.getComponent(0).add(new Ext.Panel({
								x: (cnt % 3) * 210 + 10,
								y: Math.floor(cnt / 3) * 160 + 10,
								width: 200,
								height: 150,
								onwerCt: this,
								cls: rec.data.icon + '-n',
								border: false,
								id: rec.data.id,
								listeners: {
									'render': {
										fn: function(c){
											this.body.ownerCt = this;
											this.body.on('click', function(){
												app.switchIsland(this.ownerCt.id);
												app.SLandingRight.hide();
											});
											this.body.on('dblclick', function(){
											});
											if (Ext.isIE) {
												this.body.on('mouseenter', function(){
													this.ownerCt.addClass('lp-over')
													;
												});
												this.body.on('mouseleave', function(){
													this.ownerCt.removeClass('lp-over');
												});
											}
											else {
												this.body.on('mouseover', function(){
													this.ownerCt.addClass('lp-over');
												});
												this.body.on('mouseout', function(){
													this.ownerCt.removeClass('lp-over');
												});
											}
										}
									}
								}
							}));
						}, this.ownerCt.SLandingRight);
						this.ownerCt.SLandingRight.doLayout();
						
						sB = app.StoreB.getRange();
						Ext.each(sB, function(rec, index){
							try {
								cnt = app.SLandingLeft.getComponent(0).items.getCount();
							} catch(e) {
								cnt = 0;
							}
							this.getComponent(0).add(new Ext.Panel({
								x: (cnt % 3) * 210 + 10,
								y: Math.floor(cnt / 3) * 160 + 10,
								width: 200,
								height: 150,
								onwerCt: this,
								cls: rec.data.icon + '-n',
								border: false,
								id: rec.data.id,
								listeners: {
									'render': {
										fn: function(c){
											this.body.ownerCt = this;
											this.body.on('click', function(){
												app.switchIsland(this.ownerCt.id);
												app.SLandingLeft.hide();
											});
											this.body.on('dblclick', function(){
											});
											if (Ext.isIE) {
												this.body.on('mouseenter', function(){
													this.ownerCt.addClass('lp-over');
												});
												this.body.on('mouseleave', function(){
													this.ownerCt.removeClass('lp-over');
												});
											}
											else {
												this.body.on('mouseover', function(){
													this.ownerCt.addClass('lp-over');
												});
												this.body.on('mouseout', function(){
													this.ownerCt.removeClass('lp-over');
												});
											}
										}
									}
								}
							}));
						}, this.ownerCt.SLandingLeft);
						this.ownerCt.SLandingLeft.doLayout();
						
						if (!__islandLoad) {
							this.ownerCt.LandingPage.show();
						}
						if (__islandLoad !== false) {
							this.ownerCt.switchIsland('custom_' + __islandLoad);
						}
					}
				}
			
			}
		});
	}
	else {
		this.Store = false;
	}
		
	if (this.purl) {
		this.PStore = new Ext.data.JsonStore({
			url: this.purl,
			root: 'products',
			id: 'pid',
			fields: ['pid', 'name', 'descr', 'src', 'options', {
				name: 'price',
				type: 'float'
			}, {
				name: 'shipping',
				type: 'float'
			}, 'manual', 'brochure', 'specs', 'linedrawing', {
				name: 'width',
				type: 'float'
			}, {
				name: 'height',
				type: 'float'
			}, {
				name: 'depth',
				type: 'float'
			}, {
				name: 'sku',
				type: 'string'
			}, {
				name: 'mfg',
				type: 'string'
			}],
			ownerCt: this,
			listeners: {
				'load': {
					fn: function(st, records, options){
						if (this.ownerCt.Store) {
							this.ownerCt.Store.load();
						}
					}
				}
			}
		});
	}
	else {
		this.PStore = false;
	}
	
	this.PriceList = new VDC.PricePanel({
		app: this
	});
	this.ProductsList = new VDC.ProductsPanel({
		app: this
	});

	this.SlideBox = new VDC.SlidePanel({
		app: this
	});
	this.SlideScroll = new VDC.ScrollSection({target: this.SlideBox.MPanel});
	this.Details = new VDC.Details({
		app: this
	});
	
	this.Option = new VDC.OptionsSelector({
		app: this
	});
	
	this.Busy = Ext.isIE6 ? new Ext.Panel({
		width: 1,
		height: 1,
		x: -10,
		y: -10
	}) : new Ext.Panel({
		width: 100,
		height: 100,
		x: 420,
		y: 250,
		layout: 'absolute',
		bodyStyle:'background:url(cdt/loaderbg.png) no-repeat transparent; z-index:51000',
		items:{
			xtype:'box',
			autoEl:{
				tag:'img',
				src:'cdt/loading.gif'
			},
			x:34,
			y:34
		}
	});	
/*
	this.QDetails = new Ext.Panel({
		bodyStyle: 'padding:8px;font-size:120%;font-weight:bold;background-color:yellow;color:maroon',
		html:'For better pricing on hardware quote it today!',
		width:270,
		x:270,
		y:-1,
		width:330,
		height:32,
        rootVisible:false,
		border:true,
        lines:true
	});
*/	
	this.MPanel = new Ext.Panel({
		x:0,
		y:0,
		width:940,
		height:600,
		border:false,
		hideBorder:true,
		lines:false,
		layout:'absolute',
		autoShow:true,
		app:this,
		listeners: {
			'enable':{
				fn: function(p) {
					if (!Ext.isIE6) {
						p.app.Busy.hide();
					}
				}
			},
			'disable':{
				fn: function(p) {
					if (!Ext.isIE6) {
						p.app.Busy.show();
					}
				}
			}
		},
		items:[{
			xtype:'box',
			autoEl:{tag:'div', 'class':'welcome'}
		}]
	});

	this.Zones = new Ext.Panel({
		x:0,
		y:0,
		width:940,
		height:600,
		border:false,
		hideBorder:true,
		lines:false,
		layout:'absolute',
		app:this,
		bodyStyle:'background-color:transparent; z-index:50000',
		first:false,
		toggled:false,
		showAll:function(flag) {
			Ext.each(this.items.getRange(), function(c){
				if (flag) {
					c.el.stopFx().fadeIn({
						duration: 0.1
					});
				}
				else {
					c.el.stopFx().fadeOut({
						duration: 0.1,
						useDisplay: true
					});
				}
			});
			this.first = flag;
		}
	});
	
	this.QuoteForm = new Ext.FormPanel({
		labelWidth:150,
        reader : new Ext.data.JsonReader({
			root: "contact"
        }, [
            {name: 'quote[fname]', mapping:'fname'}, 
            {name: 'quote[lname]', mapping:'lname'},
            {name: 'quote[email]', mapping:'email'},
            {name: 'quote[phone]', mapping:'phone'},
            {name: 'quote[address]', mapping:'address'},
            {name: 'quote[city]', mapping:'city'},
			{name: 'quote[zip]', mapping:'zip'},
			{name: 'quote[state]', mapping:'state'}
        ]),
		waitMsgTarget:true,
		cls:'vdc-panel',
		border:false,
		width:505,
		height:450,
		items:[{
			xtype:'fieldset',
			width:500,
			height:80,
			title:'Quote Type Requested (You may select more than one)',
			items:[{
				xtype: 'checkbox',
				fieldLabel: 'Hardware only',
				name: 'quote[hardware]',
				boxLabel:'<font size="1">Hardware package only. DOES NOT include island</font>',
				checked:true
			},{
				xtype: 'checkbox',
				fieldLabel: 'Island plus Hardware',
				name: 'quote[all]',
				boxLabel:'<font size="1">Includes complete island and all hardware in quote</font>'
			}]
		},{
			xtype:'fieldset',
			width:500,
			height:300,
			title:'Contact &amp; Additional Information',
			items:[{
					xtype:'textfield',
					fieldLabel:'First Name<font color="red">*</font>',
					name:'quote[fname]',
					allowBlank:false,
					width:300,
					blankText:'First Name is Required',
					msgTarget:'side'
				}, {
					xtype:'textfield',
					fieldLabel:'Last Name<font color="red">*</font>',
					name:'quote[lname]',
					allowBlank:false,
					width:300,
					blankText:'Last Name is Required',
					msgTarget:'side'
				}, {
					xtype:'textfield',
					fieldLabel:'Email Address<font color="red">*</font>',
					name:'quote[email]',
					allowBlank:false,
					width:300,
					blankText:'E-Mail Address is Required',
					vtype:'email',
					vTypeText:'E-Mail Address is Invalid',
					msgTarget:'side'
				}, {
					xtype:'textfield',
					fieldLabel:'Phone Number<font color="red">*</font>',
					name:'quote[phone]',
					allowBlank:false,
					width:300,
					blankText:'Phone Number is Required',
					msgTarget:'side'
				}, {
					xtype:'textfield',
					fieldLabel:'Address',
					name:'quote[address]',
					width:300
				}, {
					xtype:'textfield',
					fieldLabel:'City',
					name:'quote[city]',
					width:300
				}, {
					xtype:'textfield',
					fieldLabel:'Zip Code<font color="red">*</font>',
					name:'quote[zip]',
					allowBlank:false,
					width:300,
					blankText:'Zip Code is Required',
					msgTarget:'side',
					validator:isValidZipCode,
					invalidText:'Zip Code is Invalid'
				}, {
					xtype:'combo',
					width:300,
					fieldLabel:'State',
					name:'quote[state]',
					editable:true,
					typeAhead:true,
					forceSelection:true,
					triggerAction:'all',
					emptyText:'Select State',
					store: __states
				}, {
					xtype:'textarea',
					width:300,
					height:50,
					fieldLabel:'Comments',
					name:'quote[comments]'
			}]
		}],
		buttons:[{
			text:'Submit Request',
			minWidth:200,
			cls:'vdc-quote',
			handler: function() {
				if (app.userinfo.userid === "") {
					Ext.example.msg('<font color="red">Failure</font>', 'User must be signed in before quote!', 5);
					//Ext.Msg.alert('Failure!', 'User must be logged in before quote!');
					return false;
				}
				else {
					app.QuoteForm.getForm().submit({
						url: 'cdt_quote.php',
						params: {
							islandid: app.island.pid,
							setup: Ext.util.JSON.encode(app.setup),
							hwoptions: Ext.util.JSON.encode(app.getCurrentOptions()),
							islandname: app.CIsland.getComponent(1).getValue()
						},
						method:"POST",
						success: function(){
							app.QuoteWindow.hide();
							//Ext.Msg.alert('Status', 'Your quote request has been successfully sent.');
							Ext.example.msg('<font color="green">Status</font>', 'Your quote request has been successfully sent.', 3);
						},
						failure: function(form, action){
							if (action.failureType == 'client') {
								Ext.example.msg('<font color="red">Failure</font>', 'Missing fields! Can\'t proceed with quote submission.', 3);
	//							Ext.Msg.alert('Form', 'Missing fields!');
							}
							else {
								if (action.failureType == 'server') {
									obj = Ext.util.JSON.decode(action.response.responseText);
//									Ext.example.msg('<font color="red">Failure</font>', 'Profile Update failed!<br/>' + obj.errors.reason, 5);
									Ext.example.msg('<font color="red">Failure</font>', 'Quote didn\'t went trough!', 3);
	//								Ext.Msg.alert('Update Failed!', obj.errors.reason);
								}
								else {
									Ext.example.msg('<font color="red">Failure</font>', 'Server is unreachable:' + action.response.responseText, 3);
	//								Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
								}
							}
						}
					});
				}
			}
		}, {
			text: 'Cancel',
			minWidth:90,
			handler: function() {
				app.QuoteWindow.hide();
			}
		}]
	});
	
	this.QuoteWindow = new Ext.Window({
		modal:true,
		width:525,
		closable:true,
		draggable:false,
		resizable:false,
		bodyStyle:'padding:5',
		closeAction:'hide',
		cls:'vdc-window',
		title:'Request a Price Quote',
		items:[this.QuoteForm],
		listeners: {
			beforeshow:{
				fn: function() {
					app.keyLocked = true;
					app.QuoteForm.getForm().reset();
					app.QuoteForm.getForm().load({
						url:'cdt_userinfo.php'
					});
				}
			},
			hide: {
				fn: function() {
					app.keyLocked = false;
				}
			},
			'show' : {
				fn: function() {
					setTimeout('app.QuoteForm.getComponent(1).getComponent(8).focus();',250);
				}
			}
		}
	});

	this.CheckoutForm = new Ext.FormPanel({
		labelWidth:170,
        reader : new Ext.data.JsonReader({
			root: "contact"
        }, [
            {name: 'firstname', mapping:'fname'}, 
            {name: 'lastname', mapping:'lname'},
            {name: 'email', mapping:'email'},
            {name: 'phone', mapping:'phone'},
            {name: 'b_address', mapping:'address'},
            {name: 'b_city', mapping:'city'},
			{name: 'b_zipcode', mapping:'zip'},
			{name: 'b_state', mapping:'state'}
        ]),
//		waitMsgTarget:true,
		url: 'cdt_checkout.php',
		cls:'vdc-panel',
		border:false,
		width:870,
		height:450,
		layout:'absolute',
		items:[{
			xtype:'fieldset',
			width:420,
			height:380,
			title:'Contact Information',
			items:[{
				xtype:'textfield',
				fieldLabel:'First Name<font color="red">*</font>',
				name:'firstname',
				allowBlank:false,
				width:200,
				blankText:'First Name is Required',
				msgTarget:'side'
			}, {
				xtype:'textfield',
				fieldLabel:'Last Name<font color="red">*</font>',
				name:'lastname',
				allowBlank:false,
				width:200,
				blankText:'Last Name is Required',
				msgTarget:'side'
			}, {
				xtype:'textfield',
				fieldLabel:'Email Address<font color="red">*</font>',
				name:'email',
				allowBlank:false,
				width:200,
				blankText:'E-Mail Address is Required',
				vtype:'email',
				vTypeText:'E-Mail Address is Invalid',
				msgTarget:'side'
			}, {
				xtype:'textfield',
				fieldLabel:'Phone Number<font color="red">*</font>',
				name:'phone',
				allowBlank:false,
				width:200,
				blankText:'Phone Number is Required',
				msgTarget:'side'
			}, {
				xtype:'label',
				html:'Billing Address',
				style:'color:green;text-decoration:underline'
			}, {
				xtype:'textfield',
				fieldLabel:'Address<font color="red">*</font>',
				name:'b_address',
				width:200,
				allowBlank:false,
				blankText:'Address is Required',
				msgTarget:'side'
			}, {
				xtype:'textfield',
				fieldLabel:'City<font color="red">*</font>',
				name:'b_city',
				width:200,
				allowBlank:false,
				blankText:'City is Required',
				msgTarget:'side'
			}, {
				xtype:'textfield',
				fieldLabel:'Zip Code<font color="red">*</font>',
				name:'b_zipcode',
				allowBlank:false,
				width:200,
				blankText:'Zip Code is Required',
				msgTarget:'side',
				validator:isValidZipCode,
				invalidText:'Zip Code is Invalid'
			}, {
				xtype:'combo',
				width:200,
				fieldLabel:'State<font color="red">*</font>',
				name:'b_state',
				editable:true,
				typeAhead:true,
				forceSelection:true,
				triggerAction:'all',
				emptyText:'Select State',
				store: __states,
				allowBlank:false,
				blankText:'State is Required',
				msgTarget:'side'
			}, {
				xtype:'label',
				html:'Shipping Address (if different from billing address)',
				style:'color:green;text-decoration:underline'
			}, {
				xtype:'textfield',
				fieldLabel:'Address',
				name:'s_address',
				width:200
			}, {
				xtype:'textfield',
				fieldLabel:'City',
				name:'s_city',
				width:200
			}, {
				xtype:'textfield',
				fieldLabel:'Zip Code',
				name:'s_zipcode',
				width:200
			}, {
				xtype:'combo',
				width:200,
				fieldLabel:'State',
				name:'s_state',
				editable:true,
				typeAhead:true,
				forceSelection:true,
				triggerAction:'all',
				emptyText:'Select State',
				store: __states
			}]
		},{
			xtype:'fieldset',
			width:420,
			height:380,
			x:430,
			y:0,
			title:'Payment Details',
			items:[{
				xtype:'textfield',
				fieldLabel:'Cardholder Name<font color="red">*</font>',
				name:'cc_name',
				allowBlank:false,
				width:200,
				blankText:'Cardholder Name is Required',
				msgTarget:'side'
			}, {
				xtype:'combo',
				fieldLabel:'Card Type<font color="red">*</font>',
				name:'cc_type',
				allowBlank:false,
				width:200,
				blankText:'Card Type is Required',
				msgTarget:'side',
				editable:false,
				forceSelection:true,
				triggerAction:'all',
				store: __cctype,
				emptyText:'Choose your Credit Card type',
				listeners: {
					select: {
						fn: function(c, r, i) {
							__curentcctype = c.getValue();
							c.ownerCt.getComponent(2).validate();
						}
					}
				}
			}, {
				xtype:'textfield',
				fieldLabel:'Card Number<font color="red">*</font>',
				name:'cc_number',
				allowBlank:false,
				width:200,
				blankText:'Card Number is Required',
				msgTarget:'side',
				validator:isValidCreditCard
			}, {
				xtype:'textfield',
				fieldLabel:'Expiration Date (MM/YYYY)<font color="red">*</font>',
				name:'cc_expire',
				allowBlank:false,
				width:200,
				blankText:'Expiration Date is Required',
				msgTarget:'side',
				validator:isValidExpirationDate
			}, {
				xtype:'textfield',
				fieldLabel:'Security Code (CVV/CVV2)',
				name:'cc_cvv2',
				width:200
			}, {
				xtype:'textarea',
				width:200,
				height:100,
				fieldLabel:'Customer notes',
				name:'Customer_Notes'
			}]
		}],
		buttons:[{
			text:'Proceed with Checkout',
			minWidth:200,
			cls:'vdc-quote',
			handler: function() {
				if (app.userinfo.userid === "") {
					Ext.example.msg('<font color="red">Failure</font>', 'User must be signed in before checkout!', 5);
					return false;
				}
				else {
					app.CheckoutForm.getForm().submit({
						method:"POST",
						waitTitle:'Connecting...',
						waitMsg:'Checkout in progress',
						params: {
							setup: Ext.util.JSON.encode(app.setup),
							standard_setup: Ext.util.JSON.encode(app.standard_setup),
							hwoptions: Ext.util.JSON.encode(app.getCurrentOptions())
						},
						timeout:180000,
						success: function(){
							app.CheckoutWindow.hide();
							Ext.example.msg('<font color="green">Status</font>', 'Your order has been successfully completed.', 3);
						},
						failure: function(form, action){
							if (action.failureType == 'client') {
								Ext.example.msg('<font color="red">Failure</font>', 'Missing fields! Can\'t proceed with checkout.', 3);
							}
							else {
								if (action.failureType == 'server') {
									obj = Ext.util.JSON.decode(action.response.responseText);
									Ext.example.msg('<font color="red">Failure</font>', 'Order cannot be processed!<br/>' + action.result.errors.reason, 3);
								}
								else {
									Ext.example.msg('<font color="red">Failure</font>', 'Server is unreachable:' + action.response.responseText, 3);
								}
							}
						}
					});
				}
			}
		}, {
			text: 'Cancel',
			minWidth:90,
			handler: function() {
				app.CheckoutWindow.hide();
			}
		}]
	});
	
	this.CheckoutWindow = new Ext.Window({
		modal:true,
		width:885,
		closable:true,
		draggable:false,
		resizable:false,
		bodyStyle:'padding:5',
		closeAction:'hide',
		cls:'vdc-window',
		title:'Checkout',
		items:[this.CheckoutForm],
		listeners: {
			beforeshow:{
				fn: function() {
					app.keyLocked = true;
					__curentcctype = false;
					app.CheckoutForm.getForm().reset();
					app.CheckoutForm.getForm().load({
						url:'cdt_userinfo.php'
					});
				}
			},
			hide: {
				fn: function() {
					app.keyLocked = false;
				}
			},
			'show' : {
				fn: function() {
					setTimeout('app.CheckoutForm.getComponent(1).getComponent(0).focus();',250);
				}
			}
		}
	});
	
	this.EmailForm = new Ext.FormPanel({
		labelWidth:150,
		waitMsgTarget:true,
		cls:'vdc-panel',
		border:false,
		width:360,
		height:190,
		keys:{
			key: Ext.EventObject.ENTER,
			handler:function(){
				app.EmailForm.buttons[0].handler();
			}
		},
		buttonAlign:'right',
		items:[{
			xtype:'textfield',
			fieldLabel:'Recipient Email Address',
			labelSeparator:'',
			name:'email',
			allowBlank:false,
			width:200
		}, {
			xtype:'textfield',
			fieldLabel:'Subject',
			labelSeparator:'',
			name:'subject',
			allowBlank:false,
			width:200
		}, {
			xtype:'textfield',
			fieldLabel:'Your Island Name',
			labelSeparator:'',
			allowBlank:false,
			name:'islandname',
			width:200,
			value:''
		}, {
			xtype:'textarea',
			fieldLabel:'Your Comments',
			labelSeparator:'',
			name:'comments',
			width:200
		}],
		buttons:[{
			text:'Send',
			minWidth:200,
			cls:'vdc-add',
			handler: function() {
				app.EmailForm.getForm().submit({
					url:'cdt_sendmail.php',
					params: {
						islandid:app.island.pid,
						setup:Ext.util.JSON.encode(app.setup),
						hwoptions:Ext.util.JSON.encode(app.getCurrentOptions())
					},
					success: function() {
						Ext.example.msg('<font color="green">Status</font>', 'Your email was successfully sent.', 3);
						app.EmailWindow.hide();
					},
					failure: function(form, action) {
						if(action.failureType == 'client') {
							Ext.example.msg('<font color="red">Failure</font>', 'Missing Fields', 3);
							app.EmailForm.getComponent(0).focus();
						}
                        else if(action.failureType == 'server'){ 
                            obj = Ext.util.JSON.decode(action.response.responseText); 
							Ext.example.msg('<font color="red">Failure</font>', 'Email sending failed:<br/>' + obj.errors.reason, 3);
							app.EmailForm.getComponent(0).focus();
                        }else{ 
							Ext.example.msg('<font color="red">Failure</font>', 'Server is unreachable:<br/>' + action.response.responseText, 3);
							app.EmailForm.getComponent(0).focus();
                        }
//						Ext.example.msg('<font color="red">Alert</font>', 'Your email didn\'t went trough!', 3);									
					}
				});
			}
		}, {
			text: 'Cancel',
			minWidth:90,
			handler: function() {
				app.EmailWindow.hide();
			}
		}]
	});
	
	this.EmailWindow = new Ext.Window({
		modal:true,
		width:400,
		height:235,
		closable:true,
		draggable:false,
		resizable:false,
		bodyStyle:'padding:5',
		closeAction:'hide',
		cls:'vdc-window',
		title:'Email Setup to a Friend',
		items:[this.EmailForm],
		listeners: {
			beforeshow:{
				fn: function() {
					app.keyLocked = true;
				}
			},
			hide: {
				fn: function() {
					app.keyLocked = false;
				}
			},
			show: {
				fn : function() {
					app.EmailForm.getForm().reset();
					app.EmailForm.getComponent(2).setValue(app.CIsland.getComponent(1).getValue());
					setTimeout('app.EmailForm.getComponent(0).focus()', 250);
				}
			}
		}
	});

	this.SaveForm = new Ext.FormPanel({
		labelWidth:150,
		waitMsgTarget:true,
		cls:'vdc-panel',
		border:false,
		width:360,
		height:190,
		keys:{
			key: Ext.EventObject.ENTER,
			handler:function(){
				app.SaveForm.buttons[0].handler();
			}
		},
		buttonAlign:'right',
		items:[{
			xtype:'textfield',
			fieldLabel:'Your Island Name',
			labelSeparator:'',
			allowBlank:false,
			name:'islandname',
			width:200,
			value:''
		}, {
			xtype:'textarea',
			fieldLabel:'Your Comments',
			labelSeparator:'',
			name:'comments',
			width:200
		}],
		buttons:[{
			text:'Save',
			minWidth:200,
			cls:'vdc-add',
			handler: function() {
				app.SaveForm.getForm().submit({
					url:'cdt_save.php',
					params: {
						islandid:app.island.pid,
						setup:Ext.util.JSON.encode(app.setup),
						hwoptions:Ext.util.JSON.encode(app.getCurrentOptions())
					},
					success: function() {
						Ext.example.msg('<font color="green">Status</font>', 'Your setup was successfully saved.', 3);
						app.SetupManager.getComponent(0).getComponent(0).getLoader().load(app.SetupManager.getComponent(0).getComponent(0).getNodeById('root/save_island'));
						app.SetupManager.getComponent(0).getComponent(0).getNodeById('root/save_island').expand();
						app.SetupManager.getComponent(1).body.update('Preview Setup');
						app.SaveIsland.hide();
					},
					failure: function(form, action) {
						if(action.failureType == 'client') {
							Ext.example.msg('<font color="red">Failure</font>', 'Missing Fields', 3);
							app.SaveForm.getComponent(0).focus();
						}
                        else if(action.failureType == 'server'){ 
                            obj = Ext.util.JSON.decode(action.response.responseText); 
							Ext.example.msg('<font color="red">Failure</font>', 'Save failed:<br/>' + obj.errors.reason, 3);
							app.SaveForm.getComponent(0).focus();
                        }else{ 
							Ext.example.msg('<font color="red">Failure</font>', 'Server is unreachable:<br/>' + action.response.responseText, 3);
							app.SaveForm.getComponent(0).focus();
                        }
					}
				});
			}
		}, {
			text: 'Cancel',
			minWidth:90,
			handler: function() {
				app.SaveIsland.hide();
			}
		}]
	});
	
	this.SaveIsland = new Ext.Window({
		modal:true,
		width:400,
		height:235,
		closable:true,
		draggable:false,
		resizable:false,
		bodyStyle:'padding:5',
		closeAction:'hide',
		cls:'vdc-window',
		title:'Save Island Setup',
		items:[this.SaveForm],
		listeners: {
			beforeshow:{
				fn: function() {
					app.keyLocked = true;
				}
			},
			hide: {
				fn: function() {
					app.keyLocked = false;
				}
			},
			show: {
				fn : function() {
					app.SaveForm.getForm().reset();
					app.SaveForm.getComponent(0).setValue(app.CIsland.getComponent(1).getValue());
					setTimeout('app.SaveForm.getComponent(0).focus()', 250);
				}
			}
		}
	});

	this.SetupManager = new Ext.Window({
		modal:true,
		width:750,
		height:500,
		draggable:false,
		resizeable:false,
		closeAction:'hide',
		title:"My Setups Manager",
		layout:'border',
		items:[
			new Ext.Panel({
				region:'west',
				width:350,
				layout:'accordion',
				cls:'vdc-panel-fm',
				margins:'5 0 5 5',
				layoutConfig : {
					animate:false,
					fill:true,
					titleCollapse:true
//					hideCollapseTool:true
				},
				items:[
					new Ext.tree.TreePanel({
						width:350,
						loader: new Ext.tree.TreeLoader({dataUrl:'cdt_getsetups.php'}),
						title: 'Saved - My Saved Setups',
						lines:false,
						border:false,
						root: new Ext.tree.AsyncTreeNode({
							id:'root/save_island',
							draggable:'false'
						}),
						cls:'vdc-accordion',
						rootVisible:false,
						autoScroll:true,
						listeners: {
							click : {
								fn: function(node, e) {
									if (node.attributes.leaf == "true") {
										app.SetupManager.getComponent(2).getComponent(1).enable();
										app.SetupManager.getComponent(2).getComponent(2).enable();
										app.SetupManager.getComponent(1).load({
											url:'cdt_getsetup.php',
											params: {
												node: node.id
											},
											text:'Loading...',
											timeout:30,
											scripts:false,
											nocache:false
										});
									} else {
										app.SetupManager.getComponent(2).getComponent(1).disable();
										app.SetupManager.getComponent(2).getComponent(2).disable();
										app.SetupManager.getComponent(1).body.update('Preview Setup');
									}
								}
							}
						}
					}),
					new Ext.tree.TreePanel({
						width:350,
						loader: new Ext.tree.TreeLoader({dataUrl:'cdt_getsetups.php'}),
						title: 'Quotes - Setups I Have Requested Quotes For',
						lines:false,
						border:false,
						root: new Ext.tree.AsyncTreeNode({
							id:'root/save_quote',
							draggable:'false'
						}),
						rootVisible:false,
						cls:'vdc-accordion',
						autoScroll:true,
						listeners: {
							click : {
								fn: function(node, e) {
									if (node.attributes.leaf == "true") {
										app.SetupManager.getComponent(2).getComponent(1).enable();
										app.SetupManager.getComponent(2).getComponent(2).enable();
										app.SetupManager.getComponent(1).load({
											url:'cdt_getsetup.php',
											params: {
												node: node.id
											},
											text:'Loading...',
											timeout:30,
											scripts:false,
											nocache:false
										});
									} else {
										app.SetupManager.getComponent(2).getComponent(1).disable();
										app.SetupManager.getComponent(2).getComponent(2).disable();
										app.SetupManager.getComponent(1).body.update('Preview Setup');
									}
								}
							}
						}
					}),
					new Ext.tree.TreePanel({
						width:350,
						title: 'Emailed - Setups I Have Emailed',
						lines:false,
						border:false,
						loader: new Ext.tree.TreeLoader({dataUrl:'cdt_getsetups.php'}),
						root: new Ext.tree.AsyncTreeNode({
							id:'root/save_mail',
							draggable:'false'
						}),
						rootVisible:false,
						cls:'vdc-accordion',
						autoScroll:true,
						listeners: {
							click : {
								fn: function(node, e) {
									if (node.attributes.leaf == "true") {
										app.SetupManager.getComponent(2).getComponent(1).enable();
										app.SetupManager.getComponent(2).getComponent(2).enable();
										app.SetupManager.getComponent(1).load({
											url:'cdt_getsetup.php',
											params: {
												node: node.id
											},
											text:'Loading...',
											timeout:30,
											scripts:false,
											nocache:false
										});
									} else {
										app.SetupManager.getComponent(2).getComponent(1).disable();
										app.SetupManager.getComponent(2).getComponent(2).disable();
										app.SetupManager.getComponent(1).body.update('Preview Setup');
									}
								}
							}
						}
					})
				]
			}),
			new Ext.Panel({
				region:'center',
				bodyStyle:'background-color:transparent; padding:5px;',
				margins:'5 5 5 5'
			}),
			new Ext.Panel({
				region:'north',
				border: false,
				bodyStyle:'background-color:transparent',
				margins:'5 5 0 5',
				height:38,
				layout:'absolute',
				items:[{
					xtype:'button',
					cls:'vdc-fm-save',
					style:'top:0px;left:0px',
					handler: function() {
						app.doSave();
					}
				}, {
					xtype:'button',
					cls:'vdc-fm-load',
					style:'top:0px;left:135px',
					disabled:true,
					handler: function() {
						id = app.SetupManager.getComponent(0).layout.activeItem.getSelectionModel().getSelectedNode().id;
						Ext.Ajax.request({
							url:'cdt_smanager.php',
							params:{
								node: id,
								mode: 'load'
							},
							success: function(response) {
								getr = Ext.util.JSON.decode(response.responseText);

								var newr = app.Store.getById(getr.islandid).copy(getr.id);
								newr.set('extrasetup',getr.extrasetup);
								newr.set('island', '[Custom] ' + getr.island);
								newr.set('id',getr.id);
								app.Store.add(newr);
								app.CIsland.getComponent(0).setValue(getr.id);
								app.switchIsland(getr.id);
								app.SetupManager.hide();
							},
							failure: function() {
								
							}
						});
					}
				}, {
					xtype:'button',
					cls:'vdc-fm-delete',
					style:'top:0px;left:270px',
					disabled:true,
					handler: function() {
						node = app.SetupManager.getComponent(0).layout.activeItem.getSelectionModel().getSelectedNode();
						id = node.id;
						parentnode = node.parentNode;
						Ext.Ajax.request({
							url:'cdt_smanager.php',
							params:{
								node: id,
								mode: 'delete'
							},
							success: function(response) {
								app.SetupManager.getComponent(0).layout.activeItem.getLoader().load(parentnode);
								parentnode.expand();
								app.SetupManager.getComponent(0).layout.activeItem.getSelectionModel().select(parentnode);
								app.SetupManager.getComponent(1).body.update('Preview Setup');
							},
							failure: function() {
								
							}
						});
					}
				}]
			})
		],
		listeners:{
			show: {
				fn: function() {
					if (this.next) {
						this.getComponent(0).getComponent(0).getLoader().load(this.getComponent(0).getComponent(0).getRootNode());
						this.getComponent(0).getComponent(0).getRootNode().expand();
					}
					else {
						this.next = true;
						this.getComponent(0).getComponent(0).getRootNode().expand();
					}
					this.getComponent(2).getComponent(1).disable();
					this.getComponent(2).getComponent(2).disable();				
					this.getComponent(1).body.update('Preview Setup');
				}
			}
		}
	});

	this.CIsland = new Ext.Panel({
		x:578,
		y:2,
		width:360,
		height:90,
		bodyStyle:'padding:10px; z-index: 52000',
		cls:'vdc-panel',
		labelWidth:90,
		border:true,
		lines:true,
		layout: 'absolute',
		buttonAlign: 'right',
		items:[{
			xtype:'combo',
			name:'currentisland',
			bodyStyle:'z-index:52000',
			plugins:new Ext.ux.plugins.IconCombo(),
			mode:'local',
			x:-5,
			y:-5,
			fieldLabel:'Change Island',
			width:350,
			editable:false,
			forceSelection:false,
			emptyText:'Select your Island',
			triggerAction:'all',
			store: this.Store,
			app:this,
			displayField:'island',
			valueField:'id',
			iconClsField: 'icon',
			listeners: {
				select: {
					fn: function(c, r, i) {
						c.app.switchIsland(c.getValue());
					}
				},
				beforeshow: {
					fn: function(c) {
						console.log(c);
					}
				}
			}
		},{
			id:'island_name',
			xtype:'textfield',
			x:5,
			y:30,
			hideLabel:true,
			width:350,
			Disabled:true,
			cls:'gray',
			root:this,
			style:'text-align:right;font-weight:bold',
			listeners: {
				blur: {
					fn: function(obj) {
						this.Disabled = true;
						this.addClass('gray');
					}
				},
				render: {
					fn: function(obj) {
						Ext.EventManager.addListener(obj.el, "keydown", function(e){
							if (this.Disabled) {
								e.stopEvent();
							}
							else {
								e.stopPropagation();
							}
						}, this);
						Ext.EventManager.addListener(obj.el, "dblclick", function(e){
							this.Disabled = false;
							this.removeClass('gray');
							this.selectText();
						}, this);
					}
				}
			}
		},{
			xtype:'button',
			text:'My Saved Islands',
			minWidth:110,
			cls:'x-btn-text-icon vdc-ybutton',
			style:'position:absolute;top:58px;left:224px',
			icon:'cdt/storage.png',
			handler: function(){
				app.doManage();
			}
		},{
			xtype:'button',
			text:'Shipping Rates',
			minWidth:110,
			cls:'x-btn-text-icon vdc-checkout',
//			cls:'x-btn-text-icon vdc-checkout',
			style:'position:absolute;top:58px;left:103px',
			icon:'cdt/truck.png',
			handler: function() {
				app.doRates();
			}
		},{
			xtype:'button',
			text:'Checkout',
			minWidth:90,
			cls:'x-btn-text-icon vdc-quote',
			style:'position:absolute;top:58px;left:8px',
			icon:'cdt/cart.png',
			handler: function(){
				app.doCheckout();
			}
		}]
	});
	
	this.Instructions = new Ext.Window({
		width:300,
		height:400,
		modal:false,
		closable:true,
		draggable:true,
		resizable:false,
		closeAction:'hide',
		title:'Instructions',
		buttonAlign:'center',
		cls:'vdc-window',
		html:__instructions,
		layout:'fit',
		buttons:[{
			text:'Close',
			root:this,
			minWidth:150,
			handler:function(b) {
				b.root.CIsland.body.highlight();
				b.root.Instructions.hide();
			}
		}]
	});
	
	this.Disclaimer = new Ext.Window({
		width: 450,
		height: 300,
		modal: true,
		closable: true,
		resizable: false,
		closaAction:'hide',
		title:'Disclaimer',
		buttonAlign:'center',
		cls:'vdc-window',
//		html:__disclaimer,
//		layout:'fit',
		buttons:[{
			text:'Close',
			root:this,
			minWidth:150,
			handler:function(b) {
				b.root.CIsland.body.highlight();
				b.root.Disclaimer.hide();
			}
		}],
		items:[{
			xtype:'panel',
			html:__disclaimer,
			height:200,
			cls:'vdc-panel',
			border:false,
			style:'background-color:transparent'
		},{
			xtype:'checkbox',
			boxLabel:'Don\'t show this message anymore.',
			listeners:{
				'check': {
					fn: function(c,s) {
						app.showDisclaimer = !s;
					}
				}
			}
		}]
	});

	this.RegisterForm = new Ext.FormPanel({
		width:415,
		height:490,
		border:false,
		bodyStyle:'background-color:transparent',
		url:'secure/register.php',
		buttonAlign:'right',
		labelWidth:160,
		items:[{
			xtype:'fieldset',
			width:410,
			title:'Credentials',
			height:145,
			items:[{
				xtype:'textfield',
				width:200,
				fieldLabel:'Username<font color="red">*</font>',
				name:'uname',
				allowBlank:false,
				msgTarget:'side',
				blankText:'Username is Required'
			},{
				xtype:'textfield',
				inputType:'password',
				width:200,
				fieldLabel:'Password<font color="red">*</font>',
				name:'passwd1',
				allowBlank:false,
				msgTarget:'side',
				blankText:'Password is Required'
			},{
				xtype:'textfield',
				inputType:'password',
				width:200,
				fieldLabel:'Confirm Password<font color="red">*</font>',
				name:'passwd2',
				allowBlank:false,
				msgTarget:'side',
				blankText:'Password Confirmation is Required'			
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'E-Mail<font color="red">*</font>',
				name:'email',
				vtype:'email',
				allowBlank:false,
				msgTarget:'side',
				blankText:'E-Mail is Required'
			}]
		},{
			xtype:'fieldset',
			width:410,
			title:'Contact Information',
			height:295,
			items:[{
				xtype:'textfield',
				width:200,
				fieldLabel:'First Name',
				name:'firstname'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Last Name',
				name:'lastname'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Company',
				name:'company'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Address',
				name:'b_address'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Address 2',
				name:'b_address_2'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'City',
				name:'b_city'
			},{
				xtype:'combo',
				width:200,
				fieldLabel:'State',
				name:'b_state',
				editable:true,
				typeAhead:true,
				forceSelection:true,
				triggerAction:'all',
				emptyText:'Select State',
				store: __states
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Zip/Postal Code',
				name:'b_zipcode'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Phone',
				name:'phone'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Fax',
				name:'fax'
			}]
		}],
		buttons:[{
			text:'Sign Up',
			minWidth:200,
			cls:'vdc-add',
			formBind: true,
			handler: function() {
				app.RegisterForm.getForm().submit({
					method:'POST',
					waitTitle:'Connecting...',
					waitMsg:'Registration in progress',
					success: function(form, action){
						//app.userinfo = action.result.userinfo;
						//Ext.Msg.alert('Complete', 'Mail have been sent to complete the registration');
						Ext.example.msg('<font color="green">Status</font>', 'Your account have been successfully created! You can Sign In now with your credentials.', 5);
						app.RegWindow.hide();
/*						Ext.MessageBox.show({
							buttons:{
								'ok':'Sign In',
								'cancel':'Cancel'
							},
							fn:function(butonId, text) {
								if (butonId == 'ok') {
									app.doLogin();
								}
							},
							closable:true,
							//msg:'Your activation code was sent on the email used for registration. Please activate your account before proceed with Login'
							msg:'Your account have been successfully created! You can Sign In now with your credentials.'
						}) */
					},
					failure: function(form, action){
						if (action.failureType == 'client') {
							Ext.example.msg('<font color="red">Failure</font>', 'Missing fields! Can\'t proceed with registration.', 3);
//							Ext.Msg.alert('Form', 'Missing fields!');
						}
						else {
							if (action.failureType == 'server') {
								obj = Ext.util.JSON.decode(action.response.responseText);
								Ext.example.msg('<font color="red">Failure</font>', 'Registration Failed!<br/>' + obj.errors.reason, 3);
//								Ext.Msg.alert('Registration Failed!', obj.errors.reason);
							}
							else {
								Ext.example.msg('Failure', 'Authentication server is unreachable:<br/>' + action.response.responseText, 3);
//								Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText);
							}
						}
					}
				});
			}
		}, {
			text:'Cancel',
			width:90,
			handler: function() {
				this.ownerCt.ownerCt.hide();
			}
		}]
	});

	this.RegWindow = new Ext.Window({
		width: 445,
//		height: 535,
		modal:true,
		title:'Sign Up for Account Now',
		closable:true,
		draggable:false,
		resizable:false,
		bodyStyle:'padding:5',
		closeAction:'hide',
		cls:'vdc-window',
		items:[this.RegisterForm],
		listeners: {
			'beforeshow' : {
				fn: function() {
					app.RegisterForm.getForm().reset();
					app.keyLocked = true;
				}
			},
			'beforehide' : {
				fn: function() {
					app.keyLocked = false;
				}
			},
			'show' : {
				fn: function() {
					setTimeout('app.RegisterForm.getComponent(0).getComponent(0).focus();',250);
				}
			}
		}
	});

	this.ProfileForm = new Ext.FormPanel({
		width:407,
		height:525,
		border:false,
		bodyStyle:'background-color:transparent',
		url:'secure/profile_update.php',
        reader : new Ext.data.JsonReader({
			root: "contact"
        }, ['firstname','lastname','email','b_city','b_state','b_address','b_address_2','phone','b_zipcode','uname','company','fax']),
		labelWidth:160,
		buttonAlign:'right',
		items:[{
			xtype:'fieldset',
			width:407,
			title:'Credentials',
			height:165,
			items:[{
				xtype:'textfield',
				width:200,
				fieldLabel:'Username',
				name:'uname',
				readOnly:true,
				allowBlank:false
			},{
				xtype:'textfield',
				inputType:'password',
				width:200,
				fieldLabel:'Password',
				name:'passwd',
				msgTarget:'side',
				allowBlank:false,
				blankText:'You have to confirm with your current password',
				msgTarget:'side'
			},{
				xtype:'textfield',
				inputType:'password',
				width:200,
				fieldLabel:'New Password',
				name:'passwd1'
			},{
				xtype:'textfield',
				inputType:'password',
				width:200,
				fieldLabel:'Confirm New Password',
				name:'passwd2'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'E-Mail',
				name:'email',
				vtype:'email',
				allowBlank:false,
				msgTarget:'side',
				blankText:'E-Mail is Required'
			}]
		},{
			xtype:'fieldset',
			width:407,
			title:'Contact Information',
			height:295,
			items:[{
				xtype:'textfield',
				width:200,
				fieldLabel:'First Name',
				name:'firstname'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Last Name',
				name:'lastname'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Company',
				name:'company'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Address',
				name:'b_address'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Address 2',
				name:'b_address_2'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'City',
				name:'b_city'
			},{
				xtype:'combo',
				width:200,
				fieldLabel:'State',
				name:'b_state',
				editable:true,
				typeAhead:true,
				forceSelection:true,
				triggerAction:'all',
				emptyText:'Select State',
				store: __states
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Zip/Postal Code',
				name:'b_zipcode'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Phone',
				name:'phone'
			},{
				xtype:'textfield',
				width:200,
				fieldLabel:'Fax',
				name:'fax'
			}]
		}],
		buttons:[{
			text:'Update Profile',
			minWidth:200,
			cls:'vdc-add',
			formBind: true,
			handler: function() {
				app.ProfileForm.getForm().submit({
					method:'POST',
					waitTitle:'Connecting...',
					waitMsg:'Update in progress',
					success: function(form, action){
						app.ProfileWindow.hide();
						Ext.example.msg('<font color="green">Success</font>', 'Profile have been updated!', 3);
//						Ext.MessageBox.alert('Confirm','Profile have been updated!');
					},
					failure: function(form, action){
						if (action.failureType == 'client') {
							Ext.example.msg('<font color="red">Failure</font>', 'Missing fields! Can\'t proceed with profile update.', 3);
//							Ext.Msg.alert('Form', 'Missing fields!');
						}
						else {
							if (action.failureType == 'server') {
								obj = Ext.util.JSON.decode(action.response.responseText);
								Ext.example.msg('<font color="red">Failure</font>', 'Profile Update failed!<br/>' + obj.errors.reason, 3);
//								Ext.Msg.alert('Update Failed!', obj.errors.reason);
							}
							else {
								Ext.example.msg('<font color="red">Failure</font>', 'Server is unreachable:<br/>' + action.response.responseText, 3);
//								Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
							}
						}
					}
				});
			}
		}, {
			text:'Cancel',
			width:90,
			handler: function() {
				this.ownerCt.ownerCt.hide();
			}
		}]
	});
	
	this.ProfileWindow = new Ext.Window({
		width: 442,
//		height: 535,
		modal:true,
		title:'Profile Update',
		closable:true,
		draggable:false,
		resizable:false,
		bodyStyle:'padding:5',
		closeAction:'hide',
		cls:'vdc-window',
		items:[this.ProfileForm],
		listeners: {
			'beforeshow' : {
				fn: function() {
					app.keyLocked = true;
					app.ProfileForm.getForm().reset();
					app.ProfileForm.getForm().load({url:'secure/get_profile.php'});
				}
			},
			'beforehide' : {
				fn: function() {
					app.keyLocked = false;
				}
			}
		}
	});

	this.LoginForm = new Ext.FormPanel({
		width:325,
		border:false,
		url:'secure/login.php',
		bodyStyle:'background-color:transparent',
		labelWidth:100,
		keys:{
			key: Ext.EventObject.ENTER,
			handler:function(){
				app.LoginForm.buttons[0].handler();
			}
		},
		items:[{
			xtype:'hidden',
			name:'mode',
			value:'login'
		},{
			xtype:'textfield',
			width:300,
			hideLabel:true,
			name:'username',
			emptyText:'Enter Username',
			allowBlank:false,
			blankText:'Username Required',
			msgTarget:'side'
		},{
			xtype:'textfield',
			width:300,
			hideLabel:true,
			name:'password',
			inputType:'password',
			allowBlank:false,
			blankText:'Password Required',
			msgTarget:'side'
		}],
		buttons:[{
			text:'Sign In',
			minWidth:120,
			cls:'vdc-add',
			formBind: true,
			handler:function() {
				this.ownerCt.getForm().submit({
					method:'POST',
					waitTitle:'Connecting...',
					waitMsg:'Authentication in progress',
					success: function(form, action){
						app.userinfo = action.result.userinfo;
						app.LoginWindow.hide();
						app.LandingPage.findById('loginbutton').setText('Sign Out');
						app.LandingPage.findById('logoutbutton').hide();
						app.tools.login.addClass('logout');
						app.tools.login.dom.qtip = 'Sign Out from the application';
//						Ext.example.msg('<font color="red">Reminder!</font>', '<b>For better pricing on hardware quote it today!</b>', 10);
						Ext.example.msg('<font color="green">Success</font>', 'You have signed in successfully.', 2);
						if (app.onSuccess) {
							eval(app.onSuccess);
							//app.onSuccess = '';
						}
					},
					failure: function(form, action){
						if(action.failureType == 'client') {
//							Ext.example.msg('<font color="green">Success</font>', 'You have signed in successfully.', 2);
							Ext.example.msg('<font color="red">Failure</font>', 'Please enter your Username and Password', 3);
//							Ext.Msg.alert('Empty Fields!', 'Please enter your Username and Password');
							app.userinfo = {user: '', userid: ''};
							app.LoginForm.getComponent(1).focus();
						}
                        else if(action.failureType == 'server'){ 
                            obj = Ext.util.JSON.decode(action.response.responseText); 
							app.userinfo = {user: '', userid: ''};
							Ext.example.msg('<font color="red">Failure</font>', 'Login Failed:<br/>' + obj.errors.reason, 3);
							app.LoginForm.getComponent(1).focus();
//                            Ext.Msg.alert('Login Failed!', obj.errors.reason); 
                        }else{ 
//                            Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText); 
							Ext.example.msg('<font color="red">Failure</font>', 'Authentication server is unreachable:<br/>' + action.response.responseText, 3);
							app.userinfo = {user: '', userid: ''};
//	                        app.LoginForm.getForm().reset(); 
							app.LoginForm.getComponent(1).focus();
                        }
					}
				});
			}
		},{
			text:'Cancel',
			width:90,
			handler:function() {
				app.LoginWindow.hide();
			}
		},{
			text:'Sign Up',
			width:90,
			handler:function() {
				app.LoginWindow.hide();
				app.RegWindow.show();
			}
		}]
	});
	
	this.LoginWindow = new Ext.Window({
		width: 350,
		modal: true,
		title: 'Authentication',
		closable: false,
		draggable: false,
		resizable: false,
		closeAction: 'hide',
		cls: 'vdc-window',
		shadow: false,
		items:[
			new Ext.Panel({
				width:320,
				lines:false,
				border:false,
				bodyStyle:'font-size:11px;color:red;background-color:transparent;padding-bottom:5px'
			}),
			this.LoginForm
		],
		listeners: {
			'beforeshow' : {
				fn: function() {
					app.keyLocked = true;
				}
			},
			'beforehide' : {
				fn: function() {
					app.keyLocked = false;
					//app.onSuccess = '';
				}
			},
			'show' : {
				fn: function() {
					setTimeout('app.LoginForm.getComponent(1).focus();',250);
				}
			}
		}
	});
	
	this.LandingPage = new Ext.Window({
		width:952,
		height:600,
		x:10,
		y:10,
		modal:true,
		closable:false,
		draggable:false,
		resizable:false,
		closeAction:'hide',
		border:false,
		bodyBorder:false,
		hideBorders:true,
		frame:false,
		shadow:false,	
		buttonAlign:'center',
		cls:'vdc-window landing',
		layout:'absolute',
		root:this,
		items:[new Ext.FormPanel({
			x:596,
			y:117,
			width:330,
			height:50,
			lines:false,
			bodyStyle:'background-color:transparent',
			layout:'absolute',
			items:[{
				xtype:'button',
				id:'loginbutton',
				minWidth:150,
				style:'left: 170px',
				handler: function() {
					if (app.userinfo.user === '') {
						app.doLogin();
					} else {
						app.doLogout();
					}
				},
				text:'Sign in'
			},{
				xtype:'button',
				id:'logoutbutton',
				minWidth:150,
				handler: function() {
					app.doRegister();
				},
				text:'Sign up for account'				
			}]
		}),
		{
			x:602,
			y:548,
			width:300,
			xtype:'combo',
			name:'packageisland',
			bodyStyle:'z-index:52000',
			plugins:new Ext.ux.plugins.IconCombo(),
			mode:'local',
			fieldLabel:'Change Island',
//			width:350,
			editable:false,
			forceSelection:false,
			emptyText:'Select your Island',
			triggerAction:'all',
			store: this.StoreA,
			app:this,
			displayField:'island',
			valueField:'id',
			iconClsField: 'icon',
			listeners: {
				select: {
					fn: function(c, r, i) {
						c.app.switchIsland(c.getValue());
						app.CIsland.getComponent(0).setValue(c.getValue());
						c.app.LandingPage.hide();
					}
				}
			}
		},{
			xtype:'combo',
			x:125,
			y:525,
			width:320,
			xtype:'combo',
			name:'readyshipisland',
			bodyStyle:'z-index:52000',
			plugins:new Ext.ux.plugins.IconCombo(),
			mode:'local',
			fieldLabel:'Change Island',
//			width:350,
			editable:false,
			forceSelection:false,
			emptyText:'Select your Island',
			triggerAction:'all',
			store: this.StoreB,
			app:this,
			displayField:'island',
			valueField:'id',
			iconClsField: 'icon',
			listeners: {
				select: {
					fn: function(c, r, i) {
						c.app.switchIsland(c.getValue());
						app.CIsland.getComponent(0).setValue(c.getValue());
						c.app.LandingPage.hide();
					}
				}
			}
		},{
			xtype:'panel',
			x:22,
			y:222,
			width:440,
			height:40,
			html:'Click below to see our selection of complete ready-built islands that we can ship quickly.',
			bodyStyle:'background:none;font-size:11px;font-family:Tahoma,Verdana;line-height:13px;'
		},{
			xtype:'panel',
			x:489,
			y:222,
			width:440,
			height:55,
			html:'Are you having your new outdoor kitchen built locally? We can still help you! Design your new outdoor kitchen online, FREE! When you are done, place your order for the equipment and you\'ll receive free freight (orders over $399.00) and special prices as shown. Click the image below to get started!',
			bodyStyle:'background:none;font-size:11px;font-family:Tahoma,Verdana;line-height:13px;'
		}, {
			xtype:'box',
			x:616,
			y:24,
			width:87,
			height:77,
			xtype:'box',
			autoEl: {tag:'img', src:'cdt/videos.png'}
		}, {
			xtype:'box',
			x:721,
			y:24,
			width:87,
			height:77,
			xtype:'box',
			autoEl: {tag:'img', src:'cdt/pdfs.png'}
		}, {
			xtype:'panel',
			x:826,
			y:24,
			width:87,
			height:77,
			bodyStyle:'background:none',
			html:'<a href="http://www.cunninghamliving.com/" target="_blank" title="Cunningham Living"><img src="cdt/cunn.png" /></a>'
		}, {
			xtype:'panel',
			x:27,
			y:285,
			width:431,
			height:254,
			bodyStyle:'background:none',
			html:'<a href="#" onClick="return app.doSLandingLeft()" class="landing_rsh" title="Ready to Ship Islands Choice"></a>'
		}, {
			xtype:'panel',
			x:494,
			y:285,
			width:431,
			height:254,
			bodyStyle:'background:none',
			html:'<a href="#" onClick="return app.doSLandingRight()" class="landing_pck" title="Package Islands Choice"></a>'
		}, {
			xtype:'panel',
			x:260,
			y:250,
			items:[{
				xtype:'button',
				text:'Ready to Ship Islands Assembly Video',
				minWidth:160,
				cls:'vdc-checkout',
				handler:function() {
					app.VideoPlayer.show();
				}
			}]
		}],
		listeners: {
			show: {
				fn: function() {
					this.root.hide();
				}
			},
			hide: {
				fn: function() {
					this.root.show();
				}
			}
		}
	});
	
	this.VideoPlayer = new Ext.Window({
		width:654,
		height:534,
		modal:true,
		closable:true,
		draggable:false,
		resizable:false,
		closeAction:'hide',
		title:'Ready to Ship Island Assembly Video',
		items:[{
			width:640,
			height:505,
			border:false,
			bodyBorder:false,
			hideBorders:true,
			xtype: 'flashpanel'
			,mediaCfg: {
				mediaType: 'SWF'
				,url: 'player.swf'
				,id:'fmvideo'
				,params:{
					bgcolor:'#cfdbe7',
					name:'fmvideo',
					id:'fmvideo',
					allowfullscreen:'false',
					allowscriptaccess:'always',
					flashvars:'file=cdt/fm_video.flv&image=cdt/fm_video.jpg'
				}
			}
		}],
		listeners:{
			hide: {
				fn: function() {
					player = document.getElementById('fmvideo');
					player.sendEvent('STOP',true);
				}
			}
		}
	});
	
	this.SLandingLeft = new Ext.Window({
		width:655,
		height:240,
		modal:true,
		closable:true,
		draggable:false,
		resizable:false,
		closeAction:'hide',
		layout:'fit',
		root:this,
		buttonAlign:'center',
		title:'Ready to Ship Islands',
		items:[{
			xtype:'panel',
			height:160,
			layout:'absolute',
			cls:'vdc-panel'
		}],
		buttons:[{
			text:'Close',
			minWidth:150,
			handler: function() {
				app.SLandingLeft.hide();
			}
		}]
	});

	this.SLandingRight = new Ext.Window({
		width:655,
		height:560,
		modal:true,
		closable:true,
		draggable:false,
		resizable:false,
		closeAction:'hide',
		layout:'fit',
		root:this,
		buttonAlign:'center',
		title:'Hardware Package Island Examples',
		items:[{
			xtype:'panel',
			height:480,
			layout:'absolute',
			cls:'vdc-panel'
		}],
		buttons:[{
			text:'Close',
			minWidth:150,
			handler: function() {
				app.SLandingRight.hide();
			}
		}]
	});

	this.ShippingRates = new Ext.Window({
		width:350,
//		height:350,
		modal:false,
		closable:true,
		draggable:true,
		resizable:false,
		closeAction:'hide',
		layout:'table',
		defaults:{
			bodyStyle:'padding:5px'
		},
		layoutConfig:{
			columns:2
		},
		root:this,
		buttonAlign:'center',
		title:'Cunningham Living\'s Shipping Rates',
		items:[{
			html:'Cunningham Living\'s Shipping Rates are based on subtotal of the order',
			colspan: 2
			,style:'text-align:center;line-height:150%;font-size:115%'
		},{
			html:'<b>Price Range</b>'
			,style:'text-align:center'
		},{
			html:'<b>Shipping Rate</b>'
			,style:'text-align:center'
		},{
			html:'From $0.00 to $29.99'
		},{
			html:'$8.99'
			,style:'text-align:right'
		},{
			html:'From $30.00 to $49.99'
		},{
			html:'$12.00'
			,style:'text-align:right'
		},{
			html:'From $50.00 to $74.99'
		},{
			html:'$16.00'
			,style:'text-align:right'
		},{
			html:'From $75.00 to $149.99'
		},{
			html:'$25.00'
			,style:'text-align:right'
		},{
			html:'From $150.00 to $199.99'
		},{
			html:'$30.00'
			,style:'text-align:right'
		},{
			html:'From $200.00 to $249.99'
		},{
			html:'$35.00'
			,style:'text-align:right'
		},{
			html:'From $250.00 to $299.99'
		},{
			html:'$39.00'
			,style:'text-align:right'
		},{
			html:'Above $400.00'
		},{
			html:'<b>Free Shipping</b>'
			,style:'text-align:center'
		}]
	});
	
	this.IDetails = new VDC.IDetails({app:this});
	
	this.HidePanel = new Ext.Panel({
		x:742,
		y:542,
		items:[{
			xtype:'button',
			text:"Hide Panels",
			enableToggle:true,
			cls:'vdc-checkout',
			pressed:false,
			minWidth:90,
			tooltip:'Click to toggle Hide/Show of the navigation panels',
			listeners: {
				toggle : {
					fn: function (b,pressed) {
						app.PToggle();
					}
				}
			}

		}]
	});
		
	this.MainContent = new Ext.Panel({
		x:0,
		y:0,
		width:940,
		height:600,
		bodyStyle:'background-color: #f5f3ed',
		border:false,
		hideBorders:true,
		lines:false,
		layout:'absolute',
		items:[
			this.MPanel,
			this.Zones,
			this.PriceList,
			this.ProductsList,
			this.SlideBox,
			this.SlideScroll,
			this.Details,
			this.Busy,
			this.CIsland,
//			this.QDetails,
			this.IDetails,
			this.HidePanel
		]
	});
	
	
	this.items = [
		this.MainContent
	];
	
	this.cache = {};
	this.layer_cache = {};
	this.tsetup = {};
	this.setup = {};
	this.options = {};
	this.restrictions = {};
	this.restrictors = {};
	this.customIslands = 0;
	this.isSliding = false;
	this.keyLocked = false;
	this.userinfo = {
		user:'',
		userid:''
	};
	this.showDisclaimer = true;
	
	VDC.Application.superclass.constructor.call(this);
};
Ext.extend(VDC.Application, Ext.Window, {
    onRender: function(ct, position){
		VDC.Application.superclass.onRender.call(this, ct, position);
		if (this.PStore) {
			this.PStore.load();
		}
		this.MPanel.on('add', function(ct, cmp, idx){
			if (cmp.rendered) {
				this.remove(this.items.item(this.app.forDelete),true);
				this.app.forDelete = null;
				app.MPanel.enable();
			}
		});
		this.on('move',function(){
			setTimeout('app.realign();',1);
		});
		Ext.EventManager.addListener(document, "keydown", function(e){
			k = e.getKey();
			c = e.getCharCode();
			if (k == 72 && !this.keyLocked) {
				this.PToggle();
			}
			if (k == 80 && !this.keyLocked) {
				this.ProductsList.Toggle.toggle();
			}
			if(e.altKey && (c >= 48 && c <= 57) && !this.keyLocked) {
				z = c == 48 ? 10 : c-48;
				this.ProductsList.setZone(z+2);
				e.stopEvent();
			}
			if((e.browserEvent.charCode === undefined || e.browserEvent.charCode === 0) && e.browserEvent.keyCode == 113) {
				if (this.Instructions.hidden || !this.Instructions.rendered) {
					this.Instructions.show();
				}
				else {
					this.Instructions.hide();
				}
				e.stopEvent();	
			}
			if(e.ctrlKey && c == Ext.EventObject.HOME && !this.keyLocked) {
				if (this.LandingPage.hidden || !this.LandingPage.rendered) {
					this.LandingPage.show();
				}
				else {
					this.LandingPage.hide();
				}
				e.stopEvent();	
			}
			if(e.ctrlKey && c == Ext.EventObject.DELETE && !this.keyLocked) {
				app.doManage();
				e.stopEvent();	
			}
		}, this);
		if (!Ext.isIE6) {
			this.Busy.hide();
		}
	},
	
	realign: function() {
		for(i in app.cache) {
			if (app.cache[i] !== null) {
				try {
					app.cache[i].setLeftTop(0,0);
				} catch (e) {}
			}
		}
	},
	
	goHome: function() {
		this.LandingPage.show();
		return false;
	},
		
	doLogin: function(message, evcall) {
		evcall = evcall || '';
		message = message || '';
		this.LoginForm.getForm().reset();
		this.LoginWindow.show();
		this.LoginWindow.getComponent(0).body.update(message);
		this.LoginWindow.getEl().frame();
		app.onSuccess = evcall;
	},
	
	doLogout: function() {
		Ext.Ajax.request({
			url: 'secure/login.php',
			params: {
				mode:'logout'
			},
			success: function(response) {
				app.tools.login.removeClass('logout');
				app.tools.login.dom.qtip = 'Sign In into the application';
				app.LandingPage.findById('loginbutton').setText('Sign In');
				app.LandingPage.findById('logoutbutton').show();
				app.userinfo = {user:'', userid:''};
				Ext.example.msg('<font color="green">Success</font>','Signing out was successfull!');
			},
			failure: function() {
				Ext.example.msg('<font color="red">Warning</font>','Signing out was unsuccessfull!');
			}			
		});
	},
	
	doRegister: function() {
//		this.registerForm.getForm().reset();
		this.RegWindow.show();
		this.RegWindow.getEl().frame();
	},
	
	doProfile: function() {
		if (this.userinfo.userid === "") {
			this.doLogin('Modify of User Profile requrie user to be Signed In.<br/>If you don\'t have a user account you can create one for free.', 'app.doProfile();');
		}
		else {
			this.ProfileWindow.show();
			this.ProfileWindow.getEl().frame();
		}		
	},
	
	doEmail: function() {
		if (this.userinfo.userid === "") {
			this.doLogin('Sending Email functionality requries user the be Signed In.<br/>If you don\'t have a user account you can create one for free.', 'app.doEmail();');
		}
		else {
			this.EmailWindow.show();
			this.EmailWindow.getEl().frame();
		}
	},
	
	doQuote: function() {
		if (this.userinfo.userid === "") {
			this.doLogin('Request Quote functionality requries user the be Signed In.<br/>If you don\'t have a user account you can create one for free.','app.doQuote();');
		}
		else {
			this.QuoteWindow.show();
			this.QuoteWindow.getEl().frame();
		}
	},
	
	doPrint: function() {
		if (this.userinfo.userid === "") {
			this.doLogin('Print functionality requries user the be Signed In.<br/>If you don\'t have a user account you can create one for free.','app.doPrint();');
		}
		else {
			Ext.Ajax.request({
				url: 'cdt_pdf.php',
				params: {
					islandid:app.island.pid,
					setup:Ext.util.JSON.encode(app.setup),
					hwoptions: Ext.util.JSON.encode(app.getCurrentOptions())
				},
				success: function(response) {
					var printWin = new Ext.Window({
						width:700,
						height:580,
						modal:true,
						draggable:false,
						lines:false,
						resizable:false,
						title:'Print Preview',
						items:[
							new Ext.Panel({
								width:686,
								height:30,
								border:false,
								lines:false,
								bodyStyle:'background:url(cdt/close-return.gif) no-repeat; padding: 5px',
								html:'<a href="' + response.responseText + '">Download PDF File</a>'
							}),
							new Ext.ux.MediaPanel({
								width:686,
								height:520,
								mediaCfg: {
									mediaType: 'PDF',
									url:response.responseText								
								},
								bodyStyle:'background:url(cdt/pdf-loading.gif) no-repeat #f8f4f5'
							})
						]
					});
					printWin.show();
				},
				failure: function() {
					Ext.example.msg('<font color="red">Failure</font>', 'Error while trying to generate PDF preview!', 5);
				}
			});
		}		
	},

	doCheckout: function() {
		if (this.userinfo.userid === "") {
			this.doLogin('Checkout functionality requries user the be Signed In.<br/>If you don\'t have a user account you can create one for free.','app.doCheckout();');
		}
		else {
			this.CheckoutWindow.show();
			this.CheckoutWindow.getEl().frame();
		}
	},
	
	doManage: function() {
		if (this.userinfo.userid === "") {
			this.doLogin('Setup Manager functionality requries user the be Signed In.<br/>If you don\'t have a user account you can create one for free.', 'app.doManage();');
		}
		else {
			this.SetupManager.show();
			this.SetupManager.getEl().frame();
		}
	},
	
	doSave: function() {
		if (this.userinfo.userid === "") {
			this.doLogin('Saving island setup requries user the be Signed In.<br/>If you don\'t have a user account you can create one for free.', 'app.doSave();');
		}
		else {
			this.SaveIsland.show();
			this.SaveIsland.getEl().frame();
		}
	},
	
	doSLandingLeft: function() {
		this.SLandingLeft.show();
		return false;
	},
	
	doSLandingRight: function() {
		this.SLandingRight.show();
		return false;
	},

	doRates: function() {
		this.ShippingRates.show();
	},
	
	doCenter: function() {
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	  
	  cs = app.getSize();
	  
	  if (myWidth+20 < cs.width && myHeight+20 < cs.height) {
	  	app.setPosition(10,10);
		app.LandingPage.setPosition(10,10);
	  } else if (myWidth+20 >= cs.width && myHeight+20 >= cs.height) {
	  	app.center();
		app.LandingPage.center();
	  } else if (myWidth+20 >= cs.width && myHeight+20 < cs.height) {
	  	app.setPosition((myWidth - cs.width)/2,10);
		app.LandingPage.setPosition((myWidth - cs.width)/2,10);
	  } else if (myWidth+20 < cs.width && myHeight+20 >= cs.height) {
	  	app.setPosition(10,(myHeight - cs.height)/2);
		app.LandingPage.setPosition(10,(myHeight - cs.height)/2);
	  }
	  
	},
	
	callVideo: function() {
		var vivid = new Ext.Window({
			modal:true,
			width:654,
//			height:435,
			closeAction:'destroy',
			closable:true,
			resizable:false,
			items:[{
				width:640,
				height:430,
				border:false,
				bodyBorder:false,
				hideBorders:true,
				xtype: 'flashpanel'
				,mediaCfg: {
					mediaType: 'SWF'
					,url: 'video_Panels.swf'
					,params:{
						bgcolor:'#cfdbe7'
					}
				}				
			}]
		});
		vivid.show();
	},
	
	callDocs: function() {
		//alert('docs');
	},
	
	getCurrentOptions: function() {
		var co = [];
		for(cz in this.setup) {
			if (cz == "remove") {
				continue;
			}
			co[cz] = [cz];
			pid = this.setup[cz];
			if (this.options[pid]) {
				for(a in this.options[pid]) {
					ca = __getOption(this.PStore.getById(pid).data.options,a,this.options[pid][a]);
					if (ca !== undefined) {
						co[cz][a] = ca;
					}
				}
			}
		}
		return co;
	},
	
	setIsland: function(zone, pid, override, preload) {
		if (isNaN(parseInt(zone, 10)) || isNaN(parseInt(pid, 10))) {
			return false;
		}
		
		pid = parseInt(pid, 10);
		
		ai = this.ProductsList.MPanel.find('zoneId', zone)[0] || false;
		if ((ai && ai.multiSelect) || (!ai && Ext.type(this.setup[zone]) == "array")) {
			ix = this.setup[zone].indexOf(pid);
			if (ix == -1) {
				cz = zone + '-' + pid;
				if(this.cache[cz] === null) {
					this.cache[cz] = new Ext.Layer(this.layer_cache[cz]);
					this.MPanel.body.appendChild(this.cache[cz]);
				}
	
				this.cache[cz].anchorTo(this.MPanel.body,'tl');
				this.cache[cz].show();
				this.cache[cz].setLeftTop(0,0);

				this.setup[zone].push(pid);
				this.SlideBox.setProduct(pid, true);
			}
			else {
				//ix = this.setup[zone].indexOf(pid);
				cz = zone + '-' + pid;
				this.cache[cz].hide();
				tarray = [];
				for (ac = 0; ac < this.setup[zone].length; ac++) {
					if (this.setup[zone][ac] != pid) {
						tarray.push(this.setup[zone][ac]);
					}
				}
				this.setup[zone] = tarray;
				//this.setup[zone].pop(ix);
				this.SlideBox.setProduct(pid, false);
			}
			this.PriceList.recalculate();
			return false;
		}
		
		if (this.setup[zone] == pid) {
			this.PriceList.recalculate();
			return false;
		}
		pid = parseInt(pid, 10);
//		if (Ext.isGecko && __debug) console.log('setIsland (' + zone + ', ' + pid + ')');
		old_pid = this.setup[zone];
		override = override || false;
		preload = preload || false;
		
		try {
			pr = this.restrictions[zone].indexOf(pid) != -1;
		} catch(e) {
			pr  = false;
		}
		
		if (pr && !override) {
			Ext.Msg.confirm('Hardware Override Confirmation','This product cannot be combined with your existing hardware choices. '
			+'By confirming this selection you will be removing the conflicting hardware and replacing it with your '
			+'currently selected product. Would you like to confirm the change?',
			 function(choice) {
			 	var temp_zone = zone;
				var temp_pid = pid;
			 	if (choice == 'yes'){
					this.setIsland(temp_zone, temp_pid, true);
				}
			 }, this);
			return false;
		}
		
		if (pr && override) {
//			if (Ext.isGecko && __debug) console.log(this.restrictors[zone]);
/*			for (i = 0, c = this.restrictors[zone].length; i < c; i++) {
				this.clearZone(this.restrictors[zone][i]);
			};
*/
			while (this.restrictors[zone].length){
				this.clearZone(this.restrictors[zone][0]);
			}
			old_pid = this.setup[zone];
//			console.log(this.setup[zone]);
			this.SlideBox.MPanel.cascade(function() {
				this.removeClass('inactive');
			});
		}
			
//		ai = this.ProductsList.MPanel.layout.activeItem || false;
		ai = this.ProductsList.MPanel.find('zoneId', zone)[0] || false;
		if (ai && this.Zones.first) {
			this.ProductsList.Toggle.toggle(false);
		}
		this.forDelete = old_pid === 0 ? null : zone + '-' + old_pid;
//		console.log(this.forDelete)
		if (pid === 0) {
			this.cache[this.forDelete].hide();
			this.setup[zone] = 0;
			if (ai && ai.zonePrefix){
				ai.setTitle(ai.getSelectionModel().getSelected().data.name);
				this.PriceList.recalculate();
				//ai.setTitle(ai.initialConfig.originalName);
			}
			/*
			this.MPanel.remove(this.MPanel.items.item(app.forDelete), true);
			ai.setTitle(ai.originalName); */
		}
		else {
//			if (Ext.isGecko && __debug) console.log(this.forDelete);
			if (this.forDelete && this.cache[this.forDelete]) {
				this.cache[this.forDelete].hide();
			}
			this.forDelete = null;
			/*
			if (!Ext.isIE6) this.MPanel.disable();
			zi = this.MPanel.items.indexOfKey(this.forDelete);
			if (zi == -1) 
				zi = zone;
			this.MPanel.insert(zi, this.cache[zone + '-' + pid]);
			this.MPanel.doLayout();
			this.cache[zone + '-' + pid].el.on('load', function(){
				if (app.forDelete) 
					app.MPanel.remove(app.MPanel.items.item(app.forDelete), true);
				app.forDelete = null;
				app.MPanel.enable();
			});
			*/
			cz = zone + '-' + pid;
			if(this.cache[cz] === null) {
				this.cache[cz] = new Ext.Layer(this.layer_cache[cz]);
				this.MPanel.body.appendChild(this.cache[cz]);
			}

			this.cache[cz].anchorTo(this.MPanel.body,'tl');
			this.cache[cz].show();
			this.cache[cz].setLeftTop(0,0);
			this.setup[zone] = pid;
			this.PriceList.recalculate();
			if (ai.zonePrefix){
				ai.setTitle(ai.getSelectionModel().getSelected().data.name);
			}
		}
		
		/* Zone Restriction setup */
		try {
			ozr = this.island.restrict[zone][old_pid] || [];
		}
		catch(e) {
			ozr = [];
		}
//		if (Ext.isGecko && __debug) console.log(ozr);
		
		for(i in ozr) {
			if (!isNaN(parseInt(i, 10)) && ozr[i].length) {
				for (j = 0, k = ozr[i].length; j < k; j++) {
					this.restrictions[parseInt(i, 10)].remove(ozr[i][j]);
				}
				this.restrictors[parseInt(i, 10)].remove(zone);
			}
		}
			
		try {
			czr = this.island.restrict[zone][pid] || [];
		}
		catch(e) {
			czr = [];
		}
//		if (Ext.isGecko && __debug) console.log(czr);
		for(i in czr) {
			pi = parseInt(i, 10);
			if (!isNaN(pi) && czr[i].length) {
				for (j = 0, k = czr[i].length; j < k; j++) {
					this.restrictions[pi].push(czr[i][j]);
				}
				this.restrictors[pi].push(zone);
			}
		}
		
		/* Setting proper product type */
		for (i = 0, c = this.ProductsList.MPanel.items.getCount(); i < c; i++) {
			if (this.ProductsList.MPanel.getComponent(i).zoneId == zone) {
				grid = this.ProductsList.MPanel.getComponent(i);
				Ext.each(grid.getStore().getRange(), function(item, index, all){
					if (item.data.products.indexOf(pid) != -1) {
						if (preload) {
							this.getSelectionModel().selectRow(index);
						}
						if (this.zonePrefix) {
							this.setTitle(item.data.name);
						}
					}
				}, grid);
			}
		}
	},
	
	clearZone: function(zone) {
		try {
			this.ProductsList.MPanel.find('zoneId', zone)[0].getSelectionModel().selectLastRow();
		} catch(e) {}
//		if (Ext.isGecko && __debug) console.log('clearZone (' + zone + ')');
	},
	
	preload: function() {
		this.MPanel.add(this.cache.background);
		for (i in this.tsetup) {
			if (Ext.type(this.tsetup[i]) == "array") {
				for (j in this.tsetup[i]) {
					if (!isNaN(parseInt(i, 10)) && parseInt(this.tsetup[i][j], 10) > 0) {
						this.setIsland(i, this.tsetup[i][j], false, true);
					}
				}
			}
			if (!isNaN(parseInt(i, 10))) {
				if (parseInt(this.tsetup[i], 10) > 0) {
					this.setIsland(i, this.tsetup[i], false, true);
				}
				else {
					this.clearZone(i);
				}
			}
		}
	},
	
	PToggle: function() {
		if(!this.pToggled) {
			this.pState.ProductsList = !this.ProductsList.hidden;
			this.pState.PriceList = !this.PriceList.hidden;
			this.pState.SlideBox = !this.SlideBox.hidden;
			this.pState.CIsland = !this.CIsland.hidden;
			this.pState.Details = !this.Details.hidden;
			this.pState.IDetails = !this.IDetails.hidden;
			this.pState.Zones = !this.Zones.hidden;
			this.pState.SlideScroll = !this.SlideScroll.hidden;
			for (i in this.pState) {
				this[i].hide();
			}
		} else {					
			for (i in this.pState) {
				this[i].setVisible(this.pState[i]);
			}
		}
		this.pToggled = !this.pToggled;
		if (this.pToggled) {
			this.HidePanel.getComponent(0).setText('Show Panels');
		}
		else {
			this.HidePanel.getComponent(0).setText('Hide Panels');
		}
	},
	
	LToggle: function() {
		if (!this.LandingPage.hidden) {
			this.LandingPage.hide();
		}
		else {
			this.LandingPage.show();
		}
	},
	
	switchIsland: function(islandID) {
		this.show();
		app.Store.clearFilter();
		var record = this.Store.getById(islandID);
		if (!record) {
			alert('none');
			return false;
		}

		this.ProductsList.MPanel.collapse(false);
		this.SlideBox.MPanel.collapse(false);
		this.PriceList.MPanel.collapse(false);
		this.isSliding = false;
		
		data = record.data;
		this.island = data;

		baseprice = parseFloat(this.island.baseprice);
		if (baseprice > 0.0) {
			app.Store.filterBy(function(r){if (parseFloat(r.data.baseprice) > 0) return true; else return false});
		} else {
			app.Store.filterBy(function(r){if (parseFloat(r.data.baseprice) === 0) return true; else return false});
		}
		
		this.CIsland.getComponent(0).setValue(islandID);
		
		for (c in this.cache) {
			if (this.cache[c]) {
				this.cache[c].destroy();
			}
		}
		
		this.cache = {};
		this.layer_cache = {};
		this.setup = {};
		this.tsetup = {};
		this.standard_setup = {};
		this.options = {};
		this.restrictions = {};
		this.restrictors = {};
		
		Ext.each(this.PStore.getRange(), function(r) {
			if (r.data.options && r.data.options.length) {
				this.options[r.data.pid] = {};
			}
		}, this);	

		while (this.MPanel.remove(this.MPanel.items.get(0), true)) {}
		while (this.Zones.remove(this.Zones.items.get(0), true)) {}
		while (this.ProductsList.MPanel.remove(this.ProductsList.MPanel.items.get(0), true)) {}
		
		this.cache.background = new Ext.Component({
			xtype:'box',
			autoEl:{
				tag:'img',
				src:data.sets + data.background,
				x:0,
				y:0,
				'class':'vdc-sets-bg'
			}
		});
		
		for (i = 0, c = data.zones.length; i < c; i++) {
			//alert(data.zones[i].order);
			if (data.zones[i].types.length == 1 && data.zones[i].types[0].products.length == 1) {
				this.ProductsList.MPanel.add(new Ext.Panel({
					title: data.zones[i].name,
					border: false,
					collapsed: true,
					collapseFirst: true,
					app: this,
					cls: 'vdc-accordion vdc-radio',
					bodyStyle:'padding:4px',
					html:'<b>Standard Option</b><br/>' +
						app.PStore.getById(data.zones[i].types[0].products[0]).data.name
				}));
//				console.log(data.zones[i].order);
				this.standard_setup[parseInt(data.zones[i].order, 10)] = parseInt(data.zones[i].dprod,10) || 0;
				continue;
			}
			
			
			var sm = new Ext.grid.RadioSelectionModel({
				oneLeft:true,
				singleSelect:true,
				app:this,
				zoneId: data.zones[i].order,
				listeners: {
					rowselect: {
						fn: function(sm, rowIndex, rec){
							this.app.Details.MPanel.collapse(false);
							aic = this.app.ProductsList.MPanel.layout.activeItem || false;
							ai = this.app.ProductsList.MPanel.find('zoneId',this.zoneId)[0] || false;
//							if (aic && ai && aic.zoneId != ai.zoneId)
//								return false;
							ai.selectedProduct = this.app.setup[ai.zoneId];
							if (this.app.isSliding && rec && rec.data.products && rec.data.products.length) {
								this.app.SlideBox.MPanel.collapse(false);
								this.app.SlideBox.removeAll();
								for (j = 0, c = rec.data.products.length; j < c; j++) {
									this.app.SlideBox.addItem(
										this.app.PStore.getById(rec.data.products[j])
										,rec.data.dir
										,ai.zonePrefix || ''
										,ai.multiSelect ?
											(this.app.setup[ai.zoneId].indexOf(parseInt(rec.data.products[j],10)) != -1) :
											(this.app.setup[ai.zoneId] == rec.data.products[j])
									);
								}
								this.app.SlideBox.doLayout();
								this.app.SlideBox.MPanel.expand();
							} else {
								this.app.SlideBox.MPanel.collapse(false);
								this.app.SlideBox.removeAll();
							}
							if (rec.data.products.length === 0) {
								this.app.setIsland(ai.zoneId,0);
							} else {
								this.app.setIsland(ai.zoneId,app.setup[ai.zoneId]);
							}
						}
					}
				}
			});
			
			this.ProductsList.MPanel.add(new Ext.grid.GridPanel({
				title: data.zones[i].name,
				border: false,
				collapsed: true,
				collapseFirst: true,
				app: this,
				cls: 'vdc-accordion vdc-radio',
				listeners: {
					'collapse': {
						fn: function(p){
							this.app.SlideBox.MPanel.collapse(false);
							this.app.Details.MPanel.collapse(false);
							this.selectedProduct = this.app.setup[this.zoneId];
						}
					},
					'expand': {
						fn: function(p){
							ai = this.app.ProductsList.MPanel.layout.activeItem || false;
							if (this.app.Zones.first) {
								this.app.ProductsList.Toggle.toggle(false);
								if (this.zonePrefix) {
									this.app.Zones.items.get('zone' + this.zoneId).el.stopFx().show();
								}
							} else {
								if (this.zonePrefix) {
									this.app.Zones.items.get('zone' + this.zoneId).el.stopFx().fadeIn({
										duration: 1,
										useDisplay:true
									});
								}
							}
							this.app.SlideBox.removeAll();
							var rec = p.getSelectionModel().getSelected();
							if (rec !== undefined && rec.data.products.length) {
								for (j = 0, c = rec.data.products.length; j < c; j++) {
									this.app.SlideBox.addItem(
										this.app.PStore.getById(rec.data.products[j])
										,rec.data.dir
										,this.zonePrefix
										,ai.multiSelect ? 
											(this.app.setup[ai.zoneId].indexOf(parseInt(rec.data.products[j],10)) != -1) :
											(this.app.setup[this.zoneId] == rec.data.products[j])
									);
								}
								this.app.SlideBox.doLayout();
								this.app.SlideBox.MPanel.expand();
							}
							if (this.zonePrefix) {
								this.app.Zones.items.get('zone' + this.zoneId).el.fadeOut({
									useDisplay:true,
									duration:1
								});
							}
						}
					},
					render: {
						fn: function(cmp) {
							if(cmp.selectedRow) {
								cmp.getSelectionModel().selectRecords([cmp.getStore().getById(cmp.selectedRow)]);
							}
						}
					}
				},
				store: new Ext.data.SimpleStore({
					data: data.zones[i].types,
					id: 'id',
					fields: [{
						name: 'name',
						mapping: 'name'
					},{
						name: 'products',
						mapping: 'products'
					},{
						name: 'dir',
						mapping: 'dir'
					},{
						name: 'thumbs',
						mapping: 'tnimages'
					}]
				}),
				sm: sm,
				columns: [sm, {
					dataIndex: 'name',
					width: 176
				}],
//				selectedRow: data.extrasetup == '' ? data.zones[i].dtype : '',
//				selectedProduct: data.zones[i].dprod,
				zonePrefix: data.zones[i].prefix,
				zoneId: data.zones[i].order,
				id: data.zones[i].order,
				originalName: data.zones[i].name,
				multiSelect: data.zones[i].additional || false,
				viewConfig: {
					autoFill: false
				},
				autoWidth: true,
				width: 250,
				autoScroll: false
			}));
			
			for(j=0,jc=data.zones[i].types.length;j<jc;j++) {
				if (data.zones[i].types[j].products) {
					for (k = 0, kc = data.zones[i].types[j].products.length; k < kc; k++) {
						//					console.log(data.zones[i].types[j].products[k]);
						zi = data.zones[i].order + '-' + data.zones[i].types[j].products[k];
						this.cache[zi] = null;
						this.layer_cache[zi] = {
							id: zi,
							cls: 'vdc-sets',
							zindex: data.zones[i].zindex ? 
								parseInt(data.zones[i].zindex, 10) + k : 
								parseInt(data.zones[i].order, 10) * 100 + k,
							dh: {
								tag: 'img',
								src: data.sets +
								data.zones[i].types[j].dir +
								data.zones[i].prefix +
								this.PStore.getById(data.zones[i].types[j].products[k]).data.src +
								'.png'
							}
						};
					}
				}
				if (!data.extrasetup) {
					this.tsetup[parseInt(data.zones[i].order, 10)] = parseInt(data.zones[i].dprod) || 0;
				}
				this.setup[parseInt(data.zones[i].order, 10)] = (data.zones[i].additional || false) ? [] : 0;
			}
			if (data.extrasetup) {
				this.tsetup = data.extrasetup;
			}
				
			if (data.zones[i].prefix) {
				this.Zones.add(new Ext.Component({
					id: 'zone' + data.zones[i].order,
					xtype: 'box',
					autoEl: {
						tag: 'img',
						src: data.sets +
						'zones/' +
						data.zones[i].prefix +
						'zone' +
						'.png',
						x: 0,
						y: 0,
						'class': 'vdc-sets'
					}
				
				}));
			}
			this.restrictions[data.zones[i].order] = [];
			this.restrictors[data.zones[i].order] = [];
		}
		this.ProductsList.MPanel.doLayout();
		this.preload();
		this.Zones.first = true;

//		this.PriceList.base_price.setValue(parseFloat(data.baseprice));
//		this.PriceList.additional.setValue(parseFloat(data.additional));

		this.findById('island_name').setValue(this.island.island);
		this.setTitle(_application + ' :: ' + this.island.island);		
		this.doLayout();
		//this.ProductsList.MPanel.getComponent(0).expand();

		baseprice = parseFloat(this.island.baseprice);
		if (baseprice > 0.0) {
			this.PriceList.island_price.show();
			this.PriceList.island_price.setValue(baseprice);
			this.standard_setup[999] = this.island.pid;
		} else {
			this.PriceList.island_price.hide();
			this.PriceList.island_price.setValue(0.00);
		}
		this.PriceList.recalculate();
		this.CIsland.doLayout();

		this.ProductsList.MPanel.expand();
		this.ProductsList.Toggle.toggle(true);
		
		this.IDetails.MPanel.collapse(false);
		this.IDetails.load(this.island);
		
		this.enable();
		this.SlideBox.MPanel.collapse(false);
		this.isSliding = true;
		
		if (baseprice === 0.0 && this.showDisclaimer) {
			this.Disclaimer.show();
		} 
	}
});

Ext.override(Ext.layout.BorderLayout, { 
    southTitleAdded  : false, 
	northTitleAdded  : false,
        // private 
    onLayout : function(ct, target){ 

        var collapsed; 
        if(!this.rendered){ 
             
            target.position(); 
            target.addClass('x-border-layout-ct'); 
            var items = ct.items.items; 
            collapsed = []; 
            for(var i = 0, len = items.length; i < len; i++) { 
                var c = items[i]; 
                var pos = c.region; 
                if(c.collapsed){ 
                    collapsed.push(c); 
                } 
                c.collapsed = false; 
                if(!c.rendered){ 
                    c.cls = c.cls ? c.cls +' x-border-panel' : 'x-border-panel'; 
                    c.render(target, i); 
                } 
                this[pos] = pos != 'center' && c.split ? 
                    new Ext.layout.BorderLayout.SplitRegion(this, c.initialConfig, pos) : 
                    new Ext.layout.BorderLayout.Region(this, c.initialConfig, pos); 
                this[pos].render(target, c); 
            } 
            this.rendered = true; 
        } 
 
        var size = target.getViewSize(); 
        if(size.width < 20 || size.height < 20){ // display none? 
            if(collapsed){ 
                this.restoreCollapsed = collapsed; 
            } 
            return; 
        }else if(this.restoreCollapsed){ 
            collapsed = this.restoreCollapsed; 
            delete this.restoreCollapsed; 
        } 
 
        var w = size.width, h = size.height; 
        var centerW = w, centerH = h, centerY = 0, centerX = 0; 
 
        var n = this.north, s = this.south, west = this.west, e = this.east, c = this.center; 
        if(!c){ 
            throw 'No center region defined in BorderLayout ' + ct.id; 
        } 
 
        if(n && n.isVisible()){ 
            var b = n.getSize(); 
            var m = n.getMargins(); 
            b.width = w - (m.left+m.right); 
            b.x = m.left; 
            b.y = m.top; 
            centerY = b.height + b.y + m.bottom; 
            centerH -= centerY; 
            n.applyLayout(b); 

            if (typeof n.collapsedEl != 'undefined' && n.collapsedTitle && this.northTitleAdded === false) { 
                this.northTitleAdded = true; 
                var cDiv = n.collapsedEl; 
                var tpl  = new Ext.Template('<div style="float: left;">{txt}</div>'); 

                var insertedHtml = tpl.insertFirst(cDiv,{ txt : n.collapsedTitle },true); 
                if (n.collapsedTitleStyle) { 
                    insertedHtml.applyStyles(n.collapsedTitleStyle); 
                } 
                 
                if (n.collapsedTitleCls) { 
                    Ext.get(insertedHtml).addClass(n.collapsedTitleCls); 
                } 

            }                 
        } 
        if(s && s.isVisible()){ 
            var b = s.getSize(); 
            var m = s.getMargins(); 
            b.width = w - (m.left+m.right); 
            b.x = m.left; 
            var totalHeight = (b.height + m.top + m.bottom); 
            b.y = h - totalHeight + m.top; 
            centerH -= totalHeight; 
            s.applyLayout(b); 

            //TDGi custom title for south 
            //new config options for south region: 
            //  collapsedTitle        : 'string' 
            //  collapsedTitleCls    :  'string' 
            //  collapsedTitleStyle :  'string' 
            if (typeof s.collapsedEl != 'undefined' && s.collapsedTitle && this.southTitleAdded === false) { 
                this.southTitleAdded = true; 
                var cDiv = s.collapsedEl; 
                var tpl  = new Ext.Template('<div style="float: left;">{txt}</div>'); 

                var insertedHtml = tpl.insertFirst(cDiv,{ txt : s.collapsedTitle }); 
                if (s.collapsedTitleStyle) { 
                    insertedHtml.applyStyles(s.collapsedTitleStyle); 
                } 
                 
                if (s.collapsedTitleCls) { 
                    Ext.get(insertedHtml).addClass(s.collapsedTitleCls); 
                } 

            }                 
        } 
        if(west && west.isVisible()){ 
            var b = west.getSize(); 
            var m = west.getMargins(); 
            b.height = centerH - (m.top+m.bottom); 
            b.x = m.left; 
            b.y = centerY + m.top; 
            var totalWidth = (b.width + m.left + m.right); 
            centerX += totalWidth; 
            centerW -= totalWidth; 
            west.applyLayout(b); 
        } 
        if(e && e.isVisible()){ 
            var b = e.getSize(); 
            var m = e.getMargins(); 
            b.height = centerH - (m.top+m.bottom); 
            var totalWidth = (b.width + m.left + m.right); 
            b.x = w - totalWidth + m.left; 
            b.y = centerY + m.top; 
            centerW -= totalWidth; 
            e.applyLayout(b); 
        } 
 
        var m = c.getMargins(); 
        var centerBox = { 
            x: centerX + m.left, 
            y: centerY + m.top, 
            width: centerW - (m.left+m.right), 
            height: centerH - (m.top+m.bottom) 
        }; 
        c.applyLayout(centerBox); 
 
        if(collapsed){ 
            for(var i = 0, len = collapsed.length; i < len; i++){ 
                collapsed[i].collapse(false); 
            } 
        } 
 
        if(Ext.isIE && Ext.isStrict){ // workaround IE strict repainting issue 
            target.repaint(); 
        }
    } 
});

Ext.override(Ext.layout.FormLayout, {
    renderItem : function(c, position, target){
        if(c && !c.rendered && c.isFormField && c.inputType != 'hidden'){
            var args = [
                   c.id, c.fieldLabel,
                   c.labelStyle||this.labelStyle||'',
                   this.elementStyle||'',
                   typeof c.labelSeparator == 'undefined' ? this.labelSeparator : c.labelSeparator,
                   (c.itemCls||this.container.itemCls||'') + (c.hideLabel ? ' x-hide-label' : ''),
                   c.clearCls || 'x-form-clear-left' 
            ];
            if(typeof position == 'number'){
                position = target.dom.childNodes[position] || null;
            }
            if(position){
                c.formItem = this.fieldTpl.insertBefore(position, args, true);
            }else{
                c.formItem = this.fieldTpl.append(target, args, true);
            }
            c.render('x-form-el-'+c.id);
            c.container = c.formItem; // must set after render, because render sets it.
            c.actionMode = 'container';
        }else {
            Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
        }
    }
});


function playerReady() {
}
