/*
 * PureTrak Products Page Javascript File
 * Copyright(c) 2008-2009, Pure Voice Communictions, Inc.
 * http://www.puretrak.com
 * @author Patrick Hallinan
 *
 */

FilterOptionsFormPanel = function(config) {
	
	// -- Apply any dynamic config options
	Ext.apply(this, config);
	
	FilterOptionsFormPanel.superclass.constructor.call(this, {
		width		: 185,
		autoHeight	: true,
		labelAlign	: 'top',
		frame		: false,
		border		: false,
		bodyStyle	: 'background:transparent;margin-left:10px;',
		renderTo	: 'products_filter_options_container'
	});
};

Ext.extend(FilterOptionsFormPanel, Ext.FormPanel, {});

RadioGroupCmp = function(config) {
	
	// -- Apply any dynamic config options
	Ext.apply(this, config);
	
	RadioGroupCmp.superclass.constructor.call(this, {
		xtype	: 'radiogroup',
		cls		: 'radio_group',
		labelSeparator: '',
		labelStyle	: 'font-weight:bold;color:#CCC;padding-bottom:3px;',
		columns	: 1,
		style	: {
			paddingBottom: '2px'
		}
	});
	
	this.on('change', function(cb, checked) {
			update_content();
		}
	);
};

Ext.extend(RadioGroupCmp, Ext.form.RadioGroup, {});

Ext.onReady(function() {
	// -- Enable quick tips - feedback for any errors
	Ext.QuickTips.init();
	
	var products_store = new Ext.data.Store({
		storeId		: 'product_items_store',
		remoteSort	: true,
		proxy: new Ext.data.HttpProxy({
			url		: '/products/update_product_list',
			method	: 'POST'
		}),
		reader: new Ext.data.JsonReader({
			id				: 'product_id',
			root			: 'results',
			successProperty	: 'success'
			}, new Ext.data.Record.create([
				{name: 'product_id', type: 'int'},
				{name: 'product_name', type: 'string'},
				{name: 'product_type', type: 'int'},
				{name: 'product_set', type: 'int'},
				{name: 'product_width', type: 'string'},
				{name: 'product_height', type: 'string'},
				{name: 'product_depth', type: 'string'},
				{name: 'product_quantity', type: 'int'},
				{name: 'product_current_price', type: 'float'},
				{name: 'product_message', type: 'string'},
				{name: 'product_total_reviews', type: 'int'},
				{name: 'product_average_stars'}
			])
		)
	});

	var rg_products = new Ext.form.RadioGroup({
		xtype	: 'radiogroup',
		cls		: 'radio_group',
		fieldLabel	: 'Product Type',
		labelSeparator: '',
		labelStyle	: 'font-weight:bold;color:#CCC;padding-bottom:3px;',
		columns	: 1,
		style	: {
			paddingBottom: '2px'
		},
		items: [
			{boxLabel: 'All Products', name: 'rb-product', inputValue: 1,  checked: true},
			{boxLabel: 'Gaming Surfaces', name: 'rb-product', inputValue: 2},
			{boxLabel: 'Mouse Feet', name: 'rb-product', inputValue: 3},
			{boxLabel: 'Mice', name: 'rb-product', inputValue: 4}
		]
	});
	
	rg_products.on('change', function(cb, checked) {
			
			if(! Ext.getCmp('filter_options_panel')) {
				var optionspanel = new FilterOptionsFormPanel({id:'filter_options_panel'});
			} else {
				var optionspanel = Ext.getCmp('filter_options_panel');
				optionspanel.items.each(function(item, index, fullarray){
					optionspanel.remove(item, true);
					return true;
				});
			}
			
			switch(checked.inputValue) {
				case 2:
					rgsurface = new RadioGroupCmp({fieldLabel:'Surface Type',items: [{boxLabel: 'All Surfaces',name: 'rb-surface',inputValue: 1,checked: true},{boxLabel: 'Cloth', name: 'rb-surface', inputValue: 2},{boxLabel: 'Soft Plastic', name: 'rb-surface', inputValue: 3}]});
					rgsize = new RadioGroupCmp({fieldLabel:'Surface Size',items: [{boxLabel: 'All Sizes', name: 'rb-size', inputValue: 1, checked: true},{boxLabel: 'Large (19x14in+)', name: 'rb-size', inputValue: 2},{boxLabel: 'Medium (13x10in-12x9in)', name: 'rb-size', inputValue: 3},{boxLabel: 'Small (11x8.5in-12x9in)', name: 'rb-size', inputValue: 4}]});
					rgprice = new RadioGroupCmp({fieldLabel:'Price Range',items: [{boxLabel: 'All Price Ranges', name: 'rb-price', inputValue: 1, checked: true},{boxLabel: '$24.99+', name: 'rb-price', inputValue: 2},{boxLabel: '$18.99-$23.99', name: 'rb-price', inputValue: 3},{boxLabel: '$14.99-$18.99', name: 'rb-price', inputValue: 4},{boxLabel: '$9.99-$13.99', name: 'rb-price', inputValue: 5}]});
					rgcondition = new RadioGroupCmp({fieldLabel:'Condition',items: [{boxLabel: 'All Conditions', name: 'rb-condition', inputValue: 1},{boxLabel: 'New', name: 'rb-condition', inputValue: 2, checked: true},{boxLabel: 'Refurbished', name: 'rb-condition', inputValue: 3}]});
					optionspanel.add(rgsurface);
					optionspanel.add(rgsize);
					optionspanel.add(rgprice);
					optionspanel.add(rgcondition);
					optionspanel.doLayout();
					break;
				case 3:
					rgprice = new RadioGroupCmp({fieldLabel:'Price Range',items: [{boxLabel: 'All Price Ranges', name: 'rb-price', inputValue: 1, checked: true},{boxLabel: '$14.99+', name: 'rb-price', inputValue: 2},{boxLabel: '$9.99-$13.99', name: 'rb-price', inputValue: 3},{boxLabel: '$3.99-$8.99', name: 'rb-price', inputValue: 4}]});
					rgset = new RadioGroupCmp({fieldLabel:'Set Amount',items: [{boxLabel: 'All Sets',name: 'rb-set',inputValue: 1,checked: true},{boxLabel: '1 Set', name: 'rb-set', inputValue: 2},{boxLabel: '3 Sets', name: 'rb-set', inputValue: 3},{boxLabel: '5 Sets', name: 'rb-set', inputValue: 4}]});
					optionspanel.add(rgprice);
					optionspanel.add(rgset);
					optionspanel.doLayout();
					break;
				case 4:
					rgprice = new RadioGroupCmp({fieldLabel:'Price Range',items: [{boxLabel: 'All Price Ranges', name: 'rb-price', inputValue: 1, checked: true}]});
					optionspanel.add(rgprice);
					optionspanel.doLayout();
					break;
			}

			update_content();
		}
	);
	
	var products_form_panel = new Ext.FormPanel({
		id		: 'products_form_panel',
		width	: 185,
		autoHeight	: true,
		labelAlign	: 'top',
		frame	: false,
		border	: false,
		bodyStyle: 'background:transparent;margin-left:10px;',
		renderTo: 'products_filter_products_container',
		items: [rg_products]
	});
	
	var tpl = new Ext.XTemplate(
		'<table>',
		'	<tr>',
		'		<tpl for=".">',
		'		<td>',
		'			<div class="products_item_container">',
		'				<table id="table_grid_item">',
		'					<tr>',
		'						<td colspan="2"><div class="item_title"><a href="/products/item/{product_id}"><img src="/assets/images/products/product_items/{product_id}_product_title.png" /></a></div></td>',
		'					</tr>',
		'					<tr>',
		'						<td colspan="2"><div class="item_ss"><a href="/products/item/{product_id}"><img src="/assets/images/products/product_items/{product_id}_product_ss.png" /></a></div></td>',
		'					</tr>',
		'					<tr>',
		'						<td colspan="2"><div class="item_size"><tpl if="product_type < 3">{product_width}" x {product_height}" x {product_depth}"</tpl><tpl if="product_type == 3">Set Quantity: {product_set}</tpl><tpl if="product_type == 4">Model: {product_name}</tpl></div></td>',
		'					</tr>',
		'					<tr>',
		'						<td colspan="2">',
		'							<table align="center">',
		'								<tr>',
		'									<td><div class="review_stars"><tpl for="product_average_stars"><img src="/assets/images/products/product_items/star.png" /></tpl></div></td>',
		'									<td><div class="review_total">({product_total_reviews} reviews)</div></td>',
		'								</tr>',
		'							</table>',
		'						</td>',
		'					</tr>',
		'					<tr>',
		'						<td><div class="item_price">{[fm.usMoney(values.product_current_price)]}</div></td>',
		'						<td><div class="combo_here"></div></td>',
		'					</tr>',
		'				</table>',
		'			</div>',
		'		</td>',
		'		{[xindex % 3 === 0 ? "</tr><tr>" : ""]}',
		'		</tpl>',
		'</table>',
		'<div class="x-clear"></div>'
	);
	
	var test_item_panel = new Ext.Panel({
		id			: 'products_view',
		autoWidth	: true,
		autoHeight	: true,
		frame		: false,
		border		: false,
		bodyStyle	: 'background:transparent;',
		renderTo	: 'products_selected_list_container',
		items	: new Ext.DataView({
			id		: 'product_listing_dataview',
			store	: products_store,
			tpl		: tpl,
			frame	: false,
			border	: false,
			itemSelector	:'div.products_item_container',
			emptyText		: '<div id="products_filter_no_results">Sorry, no products found that match your request!</div>',
			refresh	: function() {
				this.constructor.prototype.refresh.call(this);
				Ext.select('.combo_here', this.el).each(function(el, index, items) {
					var store_items = products_store.getAt(items);

					// -- Check if item is in a pre-order state, if not, continue as normal.
					var preorder_flag = 0;
					if(parseInt(store_items.data.product_quantity) === 0) {
						preorder_flag = 1;
					}
					
					// -- Add Pre Order Information
					if(preorder_flag == 1) {
						
						var add_button = new Ext.Button({
							text	: 'Pre-order Now',
							iconCls	: 'icon_shopping_cart',
							width	: 100,
							handler	: function() {
							
								if(store_items.data.product_id == 32) {
							
								 	var warranty_win = new Ext.Window({
								 		title		: 'Optional 2 Year Extended Warranty',
								 		width		: 710,
								 		closable	: false,
								 		resizable	: false,
								 		html		: '<img src="/assets/images/products/product_pages/misc/32_extended_warranty_splash.jpg">',
								 		buttons		: [{
								 			text 	: 'View Details',
								 			handler	: function() {
								 				window.open('/assets/docs/Valor2YearExtendedWarranty.pdf','_newtab');
								 			}
								 		},{
								 			xtype	: 'spacer',
								 			width	: 405
								 		},{
								 			text	: 'No Thanks',
								 			handler	: function() {
								 				this.ownerCt.ownerCt.close();
												
								 				Ext.Ajax.request({
													url: '/products/add_product_to_cart',
													params: {
														product_id: store_items.data.product_id
													},
													success: function(){
														// -- Update top of page cart total
														update_top_info_cart_items();
													}
												});
												
												Ext.MessageBox.show({
													title: 'Please wait',
													msg: 'Adding item(s) to cart...',
													progressText: 'Initializing...',
													width: 250,
													progress: true,
													closable: false
												});
												
												var f = function(v){
													return function(){
														if (v == 4) {
															Ext.MessageBox.hide();
															
															var win = new Ext.Window({
																title: 'Checkout',
																closable: true,
																width: 400,
																height: 200,
																bodyStyle: 'padding:5px;',
																html: store_items.data.product_message,
																buttons: [{
																	text: 'Continue Shopping',
																	handler: function(){
																		win.close();
																	}
																}, {
																	text: 'Checkout',
																	handler: function(){
																		document.location = "/checkout/view_cart";
																	}
																}]
															});
															win.show();
														}
														else {
															var i = v / 3;
															Ext.MessageBox.updateProgress(i, Math.round(100 * i) + '% completed');
														}
													};
												};
												for (var i = 1; i < 5; i++) {
													setTimeout(f(i), i * 500);
												}
								 			}
								 		},{
								 			text	: 'Yes, Add to Cart',
								 			iconCls	: 'icon_shopping_cart',
								 			handler	: function() {
								 			
								 				this.ownerCt.ownerCt.close();
												Ext.Ajax.request({
													url: '/products/add_product_to_cart',
													params: {
														product_id: 33
													},
													success: function(){
														Ext.Ajax.request({
															url: '/products/add_product_to_cart',
															params: {
																product_id: store_items.data.product_id
															},
															success: function(){
																// -- Update top of page cart total
																update_top_info_cart_items();
															}
														});
														
														Ext.MessageBox.show({
															title: 'Please wait',
															msg: 'Adding item(s) to cart...',
															progressText: 'Initializing...',
															width: 250,
															progress: true,
															closable: false
														});
														
														var f = function(v){
															return function(){
																if (v == 4) {
																	Ext.MessageBox.hide();
																	
																	var win = new Ext.Window({
																		title: 'Checkout',
																		closable: true,
																		width: 400,
																		height: 200,
																		bodyStyle: 'padding:5px;',
																		html: store_items.data.product_message,
																		buttons: [{
																			text: 'Continue Shopping',
																			handler: function(){
																				win.close();
																			}
																		}, {
																			text: 'Checkout',
																			handler: function(){
																				document.location = "/checkout/view_cart";
																			}
																		}]
																	});
																	win.show();
																}
																else {
																	var i = v / 3;
																	Ext.MessageBox.updateProgress(i, Math.round(100 * i) + '% completed');
																}
															};
														};
														for (var i = 1; i < 5; i++) {
															setTimeout(f(i), i * 500);
														}
													}
												});
								 			
								 			}
								 		}]
								 	}).show();
								 	
								} else {
									
					 				Ext.Ajax.request({
										url: '/products/add_product_to_cart',
										params: {
											product_id: store_items.data.product_id
										},
										success: function(){
											// -- Update top of page cart total
											update_top_info_cart_items();
										}
									});
									
									Ext.MessageBox.show({
										title: 'Please wait',
										msg: 'Adding item(s) to cart...',
										progressText: 'Initializing...',
										width: 250,
										progress: true,
										closable: false
									});
									
									var f = function(v){
										return function(){
											if (v == 4) {
												Ext.MessageBox.hide();
												
												var win = new Ext.Window({
													title: 'Checkout',
													closable: true,
													width: 400,
													height: 200,
													bodyStyle: 'padding:5px;',
													html: store_items.data.product_message,
													buttons: [{
														text: 'Continue Shopping',
														handler: function(){
															win.close();
														}
													}, {
														text: 'Checkout',
														handler: function(){
															document.location = "/checkout/view_cart";
														}
													}]
												});
												win.show();
											}
											else {
												var i = v / 3;
												Ext.MessageBox.updateProgress(i, Math.round(100 * i) + '% completed');
											}
										};
									};
									for (var i = 1; i < 5; i++) {
										setTimeout(f(i), i * 500);
									}
									
								}
							}
						});
						
					} else {
						
						var add_button = new Ext.Button({
							text	: 'Add to Cart',
							iconCls	: 'icon_shopping_cart',
							width	: 90,
							handler	: function() {
							
								if(store_items.data.product_id == 32) {
								
								 	var warranty_win = new Ext.Window({
								 		title		: 'Optional 2 Year Extended Warranty',
								 		width		: 710,
								 		closable	: false,
								 		resizable	: false,
								 		html		: '<img src="/assets/images/products/product_pages/misc/32_extended_warranty_splash.jpg">',
								 		buttons		: [{
								 			text 	: 'View Details',
								 			handler	: function() {
								 				window.open('/assets/docs/Valor2YearExtendedWarranty.pdf','_newtab');
								 			}
								 		},{
								 			xtype	: 'spacer',
								 			width	: 405
								 		},{
								 			text	: 'No Thanks',
								 			handler	: function() {
								 				this.ownerCt.ownerCt.close();
												
								 				Ext.Ajax.request({
													url: '/products/add_product_to_cart',
													params: {
														product_id: store_items.data.product_id
													},
													success: function(){
														// -- Update top of page cart total
														update_top_info_cart_items();
													}
												});
												
												Ext.MessageBox.show({
													title: 'Please wait',
													msg: 'Adding item(s) to cart...',
													progressText: 'Initializing...',
													width: 250,
													progress: true,
													closable: false
												});
												
												var f = function(v){
													return function(){
														if (v == 4) {
															Ext.MessageBox.hide();
															
															var win = new Ext.Window({
																title	: 'Checkout',
																closable: true,
																width	: 400,
																height	: 200,
																bodyStyle	: 'padding:5px;',
																html	: 'Please either continue shopping or proceed to checkout to complete your order, thank you!',
																buttons	: [{
																	text	: 'Continue Shopping',
																	handler	: function() {
																		win.close();
																	}
																},{
																	text	: 'Checkout',
																	handler	: function() {
																		document.location = "/checkout/view_cart";
																	}
																}]
															});
															win.show();
														}
														else {
															var i = v / 3;
															Ext.MessageBox.updateProgress(i, Math.round(100 * i) + '% completed');
														}
													};
												};
												for (var i = 1; i < 5; i++) {
													setTimeout(f(i), i * 500);
												}
								 			}
								 		},{
								 			text	: 'Yes, Add to Cart',
								 			iconCls	: 'icon_shopping_cart',
								 			handler	: function() {
								 			
								 				this.ownerCt.ownerCt.close();
												Ext.Ajax.request({
													url: '/products/add_product_to_cart',
													params: {
														product_id: 33
													},
													success: function(){
														Ext.Ajax.request({
															url: '/products/add_product_to_cart',
															params: {
																product_id: store_items.data.product_id
															},
															success: function(){
																// -- Update top of page cart total
																update_top_info_cart_items();
															}
														});
														
														Ext.MessageBox.show({
															title: 'Please wait',
															msg: 'Adding item(s) to cart...',
															progressText: 'Initializing...',
															width: 250,
															progress: true,
															closable: false
														});
														
														var f = function(v){
															return function(){
																if (v == 4) {
																	Ext.MessageBox.hide();
																	
																	var win = new Ext.Window({
																		title: 'Checkout',
																		closable: true,
																		width: 400,
																		height: 200,
																		bodyStyle: 'padding:5px;',
																		html	: 'Please either continue shopping or proceed to checkout to complete your order, thank you!',
																		buttons: [{
																			text: 'Continue Shopping',
																			handler: function(){
																				win.close();
																			}
																		}, {
																			text: 'Checkout',
																			handler: function(){
																				document.location = "/checkout/view_cart";
																			}
																		}]
																	});
																	win.show();
																}
																else {
																	var i = v / 3;
																	Ext.MessageBox.updateProgress(i, Math.round(100 * i) + '% completed');
																}
															};
														};
														for (var i = 1; i < 5; i++) {
															setTimeout(f(i), i * 500);
														}
													}
												});
								 			
								 			}
								 		}]
								 	}).show();
								 	
								} else {
								
									Ext.Ajax.request({
										url		: '/products/add_product_to_cart',
										params	: {product_id: store_items.data.product_id},
										success	: function() {
											// -- Update top of page cart total
											update_top_info_cart_items();
										}
									});
									
									Ext.MessageBox.show({
										title	: 'Please wait',
										msg		: 'Adding item(s) to cart...',
										progressText	: 'Initializing...',
										width	: 250,
										progress: true,
										closable: false
									});
									
									var f = function(v) {
										return function() {
											if(v == 4){
												Ext.MessageBox.hide();
												
												var win = new Ext.Window({
													title	: 'Checkout',
													closable: true,
													width	: 400,
													height	: 200,
													bodyStyle	: 'padding:5px;',
													html	: 'Please either continue shopping or proceed to checkout to complete your order, thank you!',
													buttons	: [{
														text	: 'Continue Shopping',
														handler	: function() {
															win.close();
														}
													},{
														text	: 'Checkout',
														handler	: function() {
															document.location = "/checkout/view_cart";
														}
													}]
												});
												win.show();
											} else {
												var i = v/3;
												Ext.MessageBox.updateProgress(i, Math.round(100*i)+'% completed');
											}
										};
									};
									for(var i=1;i<5;i++) {
										setTimeout(f(i), i*500);
									}
								}
							}
						});
					}
					
					var add_button_panel = new Ext.Panel({
						autoWidth	: true,
						autoHeight	: true,
						frame		: false,
						border		: false,
						bodyStyle	: 'background:transparent;',
						renderTo	: el,
						items	: [add_button]
					});
				});
			}
		})
	});
		
	update_content = function() {
		products_store = Ext.StoreMgr.lookup('product_items_store');
		var product_value = Ext.getCmp('products_form_panel').getForm().getValues();
		if(Ext.getCmp('filter_options_panel')) {
			var options_values = Ext.getCmp('filter_options_panel').getForm().getValues();
			Ext.applyIf(product_value, options_values);
		}
		products_store.reload({
			params : product_value
		});
		Ext.getCmp('product_listing_dataview').refresh();
	}
	
	var product_value = Ext.getCmp('products_form_panel').getForm().getValues();
	products_store.load({
		params : product_value
	});
	
	var task = {
		run: function() {
			
			var img_array = new Array(
				'products_ad_usps.gif',
				'products_ad_free_vent.gif'
			);
			
			var len = img_array.length;
			var random_number = Math.floor(len*Math.random());
			
			var el = Ext.get('products_ad_container');
				el.sequenceFx().fadeOut({
					easing:'easeOut',
					duration:1.5,
					remove:false,
					callback: function() {
						el.update('<img src="/assets/images/products/ads/'+img_array[random_number]+'" />')
					}
				}).fadeIn({duration: 1.5});
		},
		interval: 10000 // -- 10 seconds
	}
	
	Ext.TaskMgr.start(task);

});
