/*
 * PureTrak View Cart Contents Page Javascript File
 * Copyright(c) 2008-2009, Pure Voice Communictions, Inc.
 * http://www.puretrak.com
 * @author Patrick Hallinan
 *
 */

Ext.onReady(function() {
	// -- Enable quick tips - feedback for any errors
	Ext.QuickTips.init();
	
	var cart_items_store = new Ext.data.GroupingStore({
		storeId		: 'cart_items_store',
		proxy: new Ext.data.HttpProxy({
			url		: '/checkout/get_cart_contents_for_view_cart',
			method	: 'POST'
		}),
		reader: new Ext.data.JsonReader({
			idProperty		: 'product_id',
			root			: 'results',
			successProperty	: 'success',
			remoteGroup		: true,
			remoteSort		: true
			}, new Ext.data.Record.create([
				{name: 'product_id', type: 'int'},
				{name: 'product_group_type', type: 'string'},
				{name: 'product_description', type: 'string'},
				{name: 'product_type', type: 'int'},
				{name: 'product_model_number', type: 'string'},
				{name: 'product_set', type: 'int'},
				{name: 'product_quantity', type: 'int'},
				{name: 'product_current_price', type: 'float'},
				{name: 'product_image_name', type: 'string'},
				{name: 'product_height', type: 'string'},
				{name: 'product_width', type: 'string'},
				{name: 'product_depth', type: 'string'},
				{name: 'product_surface', type: 'string'}
			])
		),
		sortInfo: {field: 'product_current_price', direction: 'ASC'},
		groupField	: 'product_group_type'
	});
	
    // define a custom summary function
    Ext.ux.grid.GroupSummary.Calculations['total_cost'] = function(v, record, field){
        return v + (record.data.product_current_price * record.data.product_quantity);
    };
	
	// utilize custom extension for Group Summary
    var summary = new Ext.ux.grid.GroupSummary();
	
    var expander = new Ext.ux.grid.RowExpander({
		collapsed	: false,
        tpl : new Ext.XTemplate(
            '<table>',
			'	<tr>',
			'		<td><img src="/assets/images/checkout/view_cart/{product_image_name}.png" /></td>',
			'		<td valign="top"><tpl if="product_type < 3">{product_width}" x {product_height}" x {product_depth}th"</tpl><tpl if="product_type == 2">Set Quantity: {product_set}</tpl><tpl if="product_type == 4">Model: {product_model_number}</tpl><br />',
			'			{product_surface}<br />',
			'			<tpl if="product_id < 32">(90) Day Limited Warranty</tpl><tpl if="product_type == 4">(3) Year Limited Warranty</tpl>',
			'		</td>',
			'	</tr>',
			'</table>'
        )
    });
	
	var quantity_array = [];
	for(q=0;q<16;q++) {
		quantity_array[q] = [q,q];
	}

	var store_cb_quantity = new Ext.data.ArrayStore({
		fields	: ['value','option'],
		data	: quantity_array
	});
	
	var qty_combo = new Ext.form.ComboBox({
		width			: 50,
		store			: store_cb_quantity,
		typeAhead		: true,
		forceSelection	: true,
		allowBlank		: false,
		triggerAction	: 'all',
		selectOnFocus	: true,
		mode			: 'local',
		valueField		: 'value',
		displayField	: 'option'
	});
	
	var grid_panel = new Ext.grid.EditorGridPanel({
		renderTo	: 'checkout_cart_items_container',
		autoWidth	: true,
		autoHeight	: true,
		frame		: true,
		border		: true,
		title		: 'Shopping Cart Contents - Click on quantity to edit',
		store		: cart_items_store,
		clicksToEdit: 1,
		plugins		: [expander, summary],
		colModel: new Ext.grid.ColumnModel({
			columns: [expander, {
				dataIndex	: 'product_description',
				header		: 'Product Description',
				width		: 300,
				align		: 'left'
			},{
				dataIndex	: 'product_group_type',
				header		: 'Pad Type',
				width		: 20
			},{
				dataIndex	: 'product_current_price',
				header		: 'Unit Price',
				renderer	: Ext.util.Format.usMoney,
				width		: 80,
				align		: 'center'
			},{
				id			: 'product_quantity',
				dataIndex	: 'product_quantity',
				header		: 'Quantity',
				width		: 100,
				align		: 'center',
				editor		: qty_combo,
				summaryType	: 'sum',
				summaryRenderer: function(v, params, data){
                    return ((v === 0 || v > 1) ? + v +' Items' : '1 Item');
                }

			},{
				id			: 'product_total',
				header		: 'Product Total',
				dataIndex	: '',
				width		: 100,
				align		: 'center',
				renderer	: function(value, params, record) {
					return Ext.util.Format.usMoney(record.data.product_current_price * record.data.product_quantity);
				},
				summaryType	: 'total_cost',
				summaryRenderer: Ext.util.Format.usMoney
			}],
			defaults: {
				sortable	: false,
				menuDisabled: true,
				resizable	: false
			}
		}),
		view: new Ext.grid.GroupingView({
			forceFit			: true,
			showGroupName		: false,
			enableNoGroups		: false,
			hideGroupedColumn	: true,
			enableGroupingMenu	: false,
			emptyText 			: 'There are no items in your shopping cart.',
			groupTextTpl		: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
		})
	});
	
	grid_panel.on('afteredit', update_item_quantity);
	
	function update_item_quantity(obj) {

		//submit to server
		Ext.Ajax.request({
			waitMsg: 'Saving changes...',
			url: '/checkout/update_cart_contents_item_quantity',
			method: 'POST',
			params: {
				product_id	: obj.record.data.product_id,
				quantity	: obj.value //the updated value
			},
			failure:function(response,options){
				Ext.MessageBox.alert('Warning','Error connecting to server...');
			},
			success:function(response,options){
				cart_items_store.reload();
				update_top_info_cart_items();

				// -- Reload order totals store
				var country = Ext.getCmp('shipping_calc_country_cb').getValue();
				var postal_code = Ext.getCmp('shipping_calc_postal_code').getValue();
				order_totals_store.reload({params:{destination_country: country, destination_postal_code: postal_code}});
				
				// -- Run the shipping costs again
				shipping_calculation_form_panel.getForm().submit({
					url		: '/checkout/retrieve_shipping_methods_quote',
					method	: 'POST',
					waitMsg	: 'Calculating shipping costs...',
					success	: function(form, action) {
						shipping_methods_store.loadData(action.result);
						// -- Update shipping_amount back to 0.00
						update_shipping_information(0);
						// -- Reload order totals store
						var country = Ext.getCmp('shipping_calc_country_cb').getValue();
						var postal_code = Ext.getCmp('shipping_calc_postal_code').getValue();
						order_totals_store.reload({params:{destination_country: country, destination_postal_code: postal_code}});
					},
					failure	: function(form, action) {

						if(action.failureType == 'server') {
							if(action.result.errors.invalid_quantity) {
								Ext.Msg.show({
									title	: 'Invalid Product Quantity',
									msg		: 'ERROR: '+action.result.errors.invalid_quantity,
									buttons	: Ext.Msg.OK,
									icon	: Ext.MessageBox.WARNING,
									minWidth: 400
								});
							}
							if(action.result.errors.request_error) {
								Ext.Msg.show({
									title	: 'Shipping Request Error',
									msg		: 'ERROR: '+action.result.errors.request_error,
									buttons	: Ext.Msg.OK,
									icon	: Ext.MessageBox.WARNING,
									minWidth: 400
								});
							}
						}
					}
				});
			}   
		});
	}
	
	// -- Load the store and auto expand row information once store loads --
	cart_items_store.load();
	cart_items_store.on('load', function() {
			rows=cart_items_store.getCount();
			for(i=0;i<rows;i++) {
				expander.expandRow(grid_panel.view.getRow(i));
			}
		}
	);
	
	/* TOTAL AND SHIPPING */
	
	var countries_store = new Ext.data.Store({
		autoLoad	: true,
		proxy: new Ext.data.HttpProxy({
			url		: '/checkout/get_countries_list',
			method	: 'POST'
		}),
		reader: new Ext.data.JsonReader({
			idProperty		: 'value',
			root			: 'data',
			successProperty	: 'success',
			fields	: [
				{name: 'value', type: 'string'},
				{name: 'option', type: 'string'}
			]
		})
	});
	
	countries_store.on('load', function() {
			Ext.getCmp('shipping_calc_country_cb').setValue('US');
		}
	);
	
	var shipping_methods_store = new Ext.data.Store({
		storeId	: 'shipping_methods_store',
        listeners: {
            load: {
                fn: function(){
					toggle_shipping_method(shipping_methods_store);
                }
            }
        },
		reader: new Ext.data.JsonReader({
			idProperty		: 'value',
			root			: 'data'
			}, new Ext.data.Record.create([
				{name: 'value', type: 'int'},
				{name: 'service_name', type: 'string'},
				{name: 'rate', type: 'float'},
				{name: 'transit_time', type: 'string'},
				{name: 'has_tracking', type: 'string'}
			])
		)
	});
	
	countryTpl = new Ext.XTemplate(
		'<tpl for=".">',
		'<div class="x-combo-list-item"><img src="/assets/images/flags/{[fm.lowercase(values.value)]}.gif"> {option}</div>',
		'</tpl>'
	);
	
	var shipping_calculation_form_panel = new Ext.FormPanel({
		id		: 'shipping_calculation_form_panel',
		title	: 'Calculate Shipping',
		width	: 375,
		autoHeight	: true,
		border	: true,
		frame	: true,
		style	: {marginBottom: '10px'},
		bodyStyle: 'padding:5px',
		labelWidth	: 99,
		items	: [{
			xtype		: 'textfield',
			id			: 'shipping_calc_city',
			name		: 'shipping_city',
			fieldLabel	: 'City',
			width		: 250,
			allowBlank	: false,
			emptyText	: 'Enter city...'
		},{
			xtype			: 'combo',
			width			: 250,
			id				: 'shipping_calc_country_cb',
			name			: 'shipping_country',
			hiddenName		: 'shipping_country',
			fieldLabel		: 'Country',
			store			: countries_store,
			mode			: 'local',
			valueField		: 'value',
			displayField	: 'option',
			tpl				: countryTpl,
			emptyText		: 'Select a country...',
			typeAhead		: true,
			selectOnFocus	: true,
			forceSelection	: true,
			allowBlank		: false,
			triggerAction	: 'all'
		},{
			xtype		: 'textfield',
			id			: 'shipping_calc_postal_code',
			name		: 'shipping_postal_code',
			fieldLabel	: 'Postal Code',
			width		: 75,
			allowBlank	: false,
			vtype		: 'alphanum'
		}],
		buttons : [{
			text	: 'Calculate Shipping Quote',
			handler	: function() {
				shipping_calculation_form_panel.getForm().submit({
					url		: '/checkout/retrieve_shipping_methods_quote',
					method	: 'POST',
					waitMsg	: 'Calculating shipping costs...',
					success	: function(form, action) {
						shipping_methods_store.loadData(action.result);
						// -- Update shipping_amount back to 0.00
						update_shipping_information(0);
						// -- Reload order totals store
						var country = Ext.getCmp('shipping_calc_country_cb').getValue();
						var postal_code = Ext.getCmp('shipping_calc_postal_code').getValue();
						order_totals_store.reload({params:{destination_country: country, destination_postal_code: postal_code}});
					},
					failure	: function(form, action) {

						if(action.failureType == 'server') {

							if(action.result.errors.invalid_quantity) {
								Ext.Msg.show({
									title	: 'Invalid Product Quantity',
									msg		: 'ERROR: '+action.result.errors.invalid_quantity,
									buttons	: Ext.Msg.OK,
									icon	: Ext.MessageBox.WARNING,
									minWidth: 400
								});
							}
							if(action.result.errors.request_error) {
								Ext.Msg.show({
									title	: 'Shipping Request Error',
									msg		: 'ERROR: '+action.result.errors.request_error,
									buttons	: Ext.Msg.OK,
									icon	: Ext.MessageBox.WARNING,
									minWidth: 400
								});
							}
						}
					}
				});
			}
		}]
	});
	
	toggle_shipping_method = function(shipping_methods_store) {

		var form_cmp = Ext.getCmp('shipping_calculation_form_panel');
		// -- Remove the form item
		form_cmp.remove(Ext.getCmp('shipping_method_cb'), true);
		
		resultTpl = new Ext.XTemplate(
			'<tpl for=".">',
			'<div ext:qtip="Package will be delivered on or before {transit_time}.<br>',
			'- {has_tracking}" ',
			'class="x-combo-list-item">{service_name} - (<b>{[fm.usMoney(values.rate)]}</b>)</div>',
			'</tpl>'
		);
		
		var shipping_method_cb = new Ext.form.ComboBox({
			xtype			: 'combo',
			width			: 250,
			id				: 'shipping_method_cb',
			name			: 'shipping_method',
			fieldLabel		: 'Shipping Method',
			store			: shipping_methods_store,
			mode			: 'local',
			valueField		: 'value',
			displayField	: 'service_name',
			tpl				: resultTpl,
			itemSelector	: 'div.x-combo-list-item',
			emptyText		: 'Select shipping method...',
			typeAhead		: true,
			selectOnFocus	: true,
			forceSelection	: true,
			allowBlank		: true,
			triggerAction	: 'all',
			listeners		: {
				select	: {
					fn	: function(combo, value) {
						update_shipping_information(value.data.value);
					}
				}
			}
		});
		
		shipping_calculation_form_panel.insert(3, shipping_method_cb);
		shipping_calculation_form_panel.doLayout();
	}
	
	var discount_code_panel = new Ext.FormPanel({
		title	: 'Discount Code - Gift Card',
		width	: 375,
		autoHeight	: true,
		border	: true,
		frame	: true,
		labelWidth	: 115,
		bodyStyle: 'padding:5px',
		items	: [{
			xtype		: 'textfield',
			name		: 'discount_code',
			fieldLabel	: 'Discount/Gift Code',
			width		: 175,
			allowBlank	: false
		}],
		buttons : [{
			text	: 'Apply Discount Code',
			handler	: function() {
				discount_code_panel.getForm().submit({
					url		: '/checkout/check_apply_discount_code',
					method	: 'POST',
					waitMsg	: 'Checking discount code...',
					success	: function(form, action) {

						Ext.Msg.show({
							title	: 'Discount Code Applied',
							msg		: 'Your discount code has been applied!',
							buttons	: Ext.Msg.OK,
							icon	: Ext.MessageBox.WARNING,
							minWidth: 350
						});

						// -- Reload order totals store
						var country = Ext.getCmp('shipping_calc_country_cb').getValue();
						var postal_code = Ext.getCmp('shipping_calc_postal_code').getValue();
						order_totals_store.reload({params:{destination_country: country, destination_postal_code: postal_code}});
					},
					failure	: function(form, action) {
						if(action.failureType == 'server') {
							if(action.result.errors.invalid_code) {
								Ext.Msg.show({
									title	: 'Invalid Discount Code',
									msg		: 'ERROR: The supplied code does not exist!',
									buttons	: Ext.Msg.OK,
									icon	: Ext.MessageBox.WARNING,
									minWidth: 350
								});
							}
							if(action.result.errors.no_use) {
								Ext.Msg.show({
									title	: 'Discount Code - Max Use',
									msg		: 'ERROR: The supplied code has reached its maximum usage count, please try another!',
									buttons	: Ext.Msg.OK,
									icon	: Ext.MessageBox.WARNING,
									minWidth: 350
								});
							}
							if(action.result.errors.invalid_product) {
								Ext.Msg.show({
									title	: 'Discount Code - Invalid Product',
									msg		: 'ERROR: The supplied code cannot be used with the current product(s), please try another!',
									buttons	: Ext.Msg.OK,
									icon	: Ext.MessageBox.WARNING,
									minWidth: 350
								});
							}
							if(action.result.errors.invalid_qty) {
								Ext.Msg.show({
									title	: 'Discount Code - Invalid Quantity',
									msg		: 'ERROR: '+action.result.errors.invalid_qty,
									buttons	: Ext.Msg.OK,
									icon	: Ext.MessageBox.WARNING,
									minWidth: 350
								});
							}
						}
					}
				});
			}
		}]
	});
	
	var order_totals_store = new Ext.data.Store({
		autoLoad	: true,
		storeId		: 'order_totals_store',
		proxy: new Ext.data.HttpProxy({
			url		: '/checkout/get_session_order_totals',
			method	: 'POST'
		}),
		reader: new Ext.data.JsonReader({
			root			: 'data',
			successProperty	: 'success',
			fields	: [
				{name: 'sub_total'},
				{name: 'discount_amount'},
				{name: 'shipping_amount'},
				{name: 'sales_tax_amount'},
				{name: 'total_order_amount'},
				{name: 'total_items_in_cart'}
			]
		})
	});
	
	var totals_tpl = new Ext.XTemplate(
		'<tpl for=".">',
		'<div class="view_cart_totals_container">',
		'<table id="table_cart_totals_box">',
		'	<tr>',
		'		<td width="65%" style="font-family:Verdana;font-size:13px;color:#EEEEF0;padding-bottom:10px;">Subtotal ({total_items_in_cart}):</td>',
		'		<td width="35%" style="text-align:right;font-family:Verdana;font-size:13px;color:#EEEEF0;padding-bottom:10px;">{[fm.usMoney(values.sub_total)]}</td>',
		'	</tr>',
		'	<tr>',
		'		<td width="65%" style="font-family:Verdana;font-size:13px;color:#EEEEF0;padding-bottom:10px;">TAX (CA 9.25%):</td>',
		'		<td width="35%" style="text-align:right;font-family:Verdana;font-size:13px;color:#EEEEF0;padding-bottom:10px;">{[fm.usMoney(values.sales_tax_amount)]}</td>',
		'	</tr>',
		'	<tr>',
		'		<td width="65%" style="font-family:Verdana;font-size:13px;color:#EEEEF0;padding-bottom:10px;">Shipping:</td>',
		'		<td width="35%" style="text-align:right;font-family:Verdana;font-size:13px;color:#EEEEF0;padding-bottom:10px;">{[fm.usMoney(values.shipping_amount)]}</td>',
		'	</tr>',
		'	<tr>',
		'		<td width="65%" style="font-family:Verdana;font-size:13px;font-weight:bold;color:#FF0000;padding-bottom:35px;">DISCOUNT:</td>',
		'		<td width="35%" style="text-align:right;font-family:Verdana;font-size:13px;font-weight:bold;color:#FF0000;padding-bottom:35px;">-{[fm.usMoney(values.discount_amount)]}</td>',
		'	</tr>',
		'	<tr>',
		'		<td colspan="2" style="font-family:Verdana;font-size:30px;color:#EEEEF0;text-align:center;">{[fm.usMoney(values.total_order_amount)]}</td>',
		'	</tr>',
		'</table>',
		'</div>',
		'</tpl>'
	);
	
	var totals_panel = new Ext.Panel({
		title	: 'Order Total',
		autoWidth	: true,
		autoHeight	: true,
		border	: true,
		frame	: true,
		//style	: {marginBottom: '10px'},
		items	: new Ext.DataView({
			store	: order_totals_store,
			tpl		: totals_tpl,
			itemSelector	:'div.view_cart_totals_container',
			frame	: false,
			border	: false
		})
	});
	
	var continue_panel = new Ext.Panel({
		layout		: 'hbox',
		autoWidth	: true,
		autoHeight	: true,
		border	: true,
		frame	: true,
		bodyStyle	: 'padding:8px;',
		items	: [{
			xtype	: 'button',
			text	: 'Continue Shopping',
			handler	: function() {
				window.location = '/products';
			}
		},{
			xtype	: 'spacer',
			flex	: 1
		},{
			xtype	: 'button',
			text	: 'Proceed to Checkout',
			handler	: function() {
				if(shipping_calculation_form_panel.getForm().isValid()) {
					if(Ext.getCmp('shipping_method_cb')) {
						if(Ext.getCmp('shipping_method_cb').getValue() === 0) {
							Ext.Msg.show({
								title	: 'Invalid Shipping Method',
								msg		: 'Please select a shipping method!',
								buttons	: Ext.Msg.OK,
								icon	: Ext.MessageBox.WARNING,
								minWidth: 300
							});
						} else {
							window.location = '/login/checkout_login_routine';
						}
					} else {
						Ext.Msg.show({
							title	: 'Calculate Shipping',
							msg		: 'You must calculate your shipping before you can checkout!',
							buttons	: Ext.Msg.OK,
							icon	: Ext.MessageBox.WARNING,
							minWidth: 300
						});
					}
				} else {
					// -- Please request a ship quote
					Ext.Msg.show({
						title	: 'Calculate Shipping',
						msg		: 'You must calculate your shipping before you can checkout!',
						buttons	: Ext.Msg.OK,
						icon	: Ext.MessageBox.WARNING,
						minWidth: 300
					});
				}
			}
		}]
	});
		
	var ship_panel = new Ext.Panel({
		renderTo	: 'checkout_cart_shipping_container',
		layout		: 'column',
		autoWidth	: true,
		autoHeight	: true,
		bodyStyle	: 'background:transparent;',
		border		: false,
		items		: [{
			columnWidth	: .59,
			border		: false,
			bodyStyle	: 'background:transparent;',
			items	: [shipping_calculation_form_panel, discount_code_panel]
		},{
			columnWidth	: .41,
			border		: false,
			bodyStyle	: 'background:transparent;',
			items	: [totals_panel, continue_panel]
		}]
	});
	
	var mail_list_form_panel = new Ext.FormPanel({
		renderTo	: 'mailing_list_left_col',
		autoWidth	: true,
		autoHeight	: true,
		hideLabel	: true,
		border		: false,
		labelWidth	: 1,
		buttonAlign	: 'center',
		bodyStyle	: 'background:transparent;',
		style	: {
			paddingTop	: '100px',
			paddingLeft	: '5px'
		},
		items	: [{
			xtype		: 'textfield',
			name		: 'email_address',
			emptyText	: 'Enter Email Address...',
			width		: 160,
			allowBlank	: false,
			vtype		: 'email'
		}],
		buttons	: [{
			text	: 'Sign Up',
			width	: 70,
			height	: 10,
			handler	: function() {
				mail_list_form_panel.getForm().submit({
					url		: '/index/add_customer_to_general_mailing_list',
					method	: 'POST',
					waitMsg	: 'Adding to mailing list...',
					success	: function(form, action) {
						Ext.Msg.show({
							title	: 'Email Added',
							msg		: 'You have been added to the PureTrak mailing list.',
							buttons	: Ext.Msg.OK,
							icon	: Ext.MessageBox.INFO,
							minWidth: 400
						});
						mail_list_form_panel.getForm().reset();
					},
					failure	: function(form, action) {
						Ext.Msg.show({
							title	: 'Invalid Email Address',
							msg		: 'ERROR: That Email address is already on the list!',
							buttons	: Ext.Msg.OK,
							icon	: Ext.MessageBox.INFO,
							minWidth: 400
						});
						mail_list_form_panel.getForm().reset();
					}
				});
			}
		}]
	});
	
	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);

});
