/*
 * PureTrak Products Item Page Javascript File
 * Copyright(c) 2008-2009, Pure Voice Communictions, Inc.
 * http://www.puretrak.com
 * @author Patrick Hallinan
 *
 */

function loadPictureWindow(pid) {
	
	var product_count = Ext.StoreMgr.lookup('product_images_store').getAt(0).data.product_image_count;
	var product_company = Ext.StoreMgr.lookup('product_images_store').getAt(0).data.product_company;
	var product_name = Ext.StoreMgr.lookup('product_images_store').getAt(0).data.product_name;
	
	var counter = pid;
	
	if(Ext.getCmp('product_views_window')) {
		Ext.getCmp('product_views_window').setSrc("/assets/images/products/product_pages/product_ss/"+product_name+"/"+product_name+pid+"_large.jpg");
	} else {
		imageWindow = new ImageViewer({
			id		: 'product_views_window',
			title	: product_company+" "+product_name.capitalize()+" Image Viewer",
			src		: "/assets/images/products/product_pages/product_ss/"+product_name+"/"+product_name+pid+"_large.jpg",
			hideAction	: 'close',
			buttonAlign	: 'center',
			buttons	: [{
				text	: 'Previous Image',
				width	: 110,
				handler	: function() {
					if(counter == 1) {
						counter = product_count;
						Ext.getCmp('product_views_window').setSrc("/assets/images/products/product_pages/product_ss/"+product_name+"/"+product_name+counter+"_large.jpg");
					} else {
						counter--;
						Ext.getCmp('product_views_window').setSrc("/assets/images/products/product_pages/product_ss/"+product_name+"/"+product_name+counter+"_large.jpg");
					}
				}
			},{
				text	: 'Next Image',
				width	: 110,
				style	: {marginLeft: '15px'},
				handler	: function() {
					if(counter % product_count == 0) {
						counter = 1;
						Ext.getCmp('product_views_window').setSrc("/assets/images/products/product_pages/product_ss/"+product_name+"/"+product_name+counter+"_large.jpg");
					} else {
						counter++;
						Ext.getCmp('product_views_window').setSrc("/assets/images/products/product_pages/product_ss/"+product_name+"/"+product_name+counter+"_large.jpg");
					}
				}
			}]
		}).show();
	}
}

String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
 
Ext.onReady(function() {
	// -- Enable quick tips - feedback for any errors
	Ext.QuickTips.init();
	
	var base = location.pathname.lastIndexOf('/')+1;
	var product_id = location.pathname.substring(base);
	
	
	var product_images_store = new Ext.data.Store({
		storeId		: 'product_images_store',
		autoLoad	: true,
		remoteSort	: true,
		proxy: new Ext.data.HttpProxy({
			url		: '/products/retrieve_product_information_for_images',
			method	: 'POST'
		}),
		baseParams	: {
			product_id	: product_id
		},
		reader: new Ext.data.JsonReader({
			id				: 'product_id',
			root			: 'results',
			successProperty	: 'success'
			}, new Ext.data.Record.create([
				{name: 'product_id', type: 'int'},
				{name: 'product_company', type: 'string'},
				{name: 'product_name', type: 'string'},
				{name: 'product_image_count', type: 'int'},
				{name: 'product_current_price', type: 'float'},
				{name: 'product_quantity', type: 'int'},
				{name: 'product_message', type: 'string'}
			])
		)
	});
	
	var images_tpl = new Ext.XTemplate(
		'<tpl for=".">',
		'	<div class="product_images_container">',
		'	<table>',
		'		<tr>',
		'			<td colspan="3" style="padding-bottom:5px;"><img src="/assets/images/products/product_pages/product_ss/{product_name}/{product_name}1_small.png" onClick="loadPictureWindow(1)" style="cursor:pointer;"></td>',
		'		</tr>',
		'		<tr>',
		'			<td colspan="3" style="padding-bottom:5px;"><span style="font-family:Verdana;font-size:10px;color:white;">Click to Enlarge</span></td>',
		'		</tr>',
		'		<tr>',
		'			<tpl if="product_image_count &gt; 1"><td align="right"><img src="/assets/images/products/product_pages/product_ss/{product_name}/{product_name}2_small.gif" onClick="loadPictureWindow(2)" style="cursor:pointer;"></td></tpl>',
		'			<tpl if="product_image_count &gt; 2"><td align="center"><img src="/assets/images/products/product_pages/product_ss/{product_name}/{product_name}3_small.gif" onClick="loadPictureWindow(3)" style="cursor:pointer;"></td></tpl>',
		'			<tpl if="product_image_count &gt; 3"><td align="left"><img src="/assets/images/products/product_pages/product_ss/{product_name}/{product_name}4_small.gif" onClick="loadPictureWindow(4)" style="cursor:pointer;"></td></tpl>',
		'		</tr>',
		'	</table>',
		'	</div>',
		'</tpl>',
		'<div class="x-clear"></div>'
	);
	
	var product_images_panel = new Ext.Panel({
		id			: 'product_images_panel',
		autoWidth	: true,
		autoHeight	: true,
		frame		: false,
		border		: false,
		bodyStyle	: 'background:transparent;',
		renderTo	: 'product_images',
		items: new Ext.DataView({
			store	: product_images_store,
			tpl		: images_tpl,
			frame	: false,
			border	: false,
			itemSelector	:'div.product_images_container',
			emptyText		: 'No images available.'
		})
	});




	var qty_price_tpl = new Ext.XTemplate(
		'<tpl for=".">',
		'	<div class="qty_price_container">',
		'	<table>',
		'		<tr>',
		'			<td><div class="product_current_price">{[fm.usMoney(values.product_current_price)]}</div></td>',
		'			<td><div class="combo_button_container"></div></td>',
		'		</tr>',
		'	</table>',
		'	</div>',
		'</tpl>',
		'<div class="x-clear"></div>'
	);

	var product_qty_add_panel = new Ext.Panel({
		id			: 'product_qty_add_panel',
		autoWidth	: true,
		autoHeight	: true,
		frame		: false,
		border		: false,
		bodyStyle	: 'background:transparent;',
		renderTo	: 'product_price_qty_add',
		items: new Ext.DataView({
			store	: product_images_store,
			tpl		: qty_price_tpl,
			frame	: false,
			border	: false,
			itemSelector	:'div.qty_price_container',
			refresh: function() {
				this.constructor.prototype.refresh.call(this);
				Ext.select('.combo_button_container', this.el).each(function(el, index, items) {
					var store_info = product_images_store.getAt(0);
					// -- Check if item is in a pre-order state, if not, continue as normal.
					var preorder_flag = 0;
					if(parseInt(store_info.data.product_quantity) == 0) {
						preorder_flag = 1;
					}
					
					if(preorder_flag == 1) {
						
						var add_button = new Ext.Button({
							text	: 'Pre-order Now',
							iconCls	: 'icon_shopping_cart',
							width	: 100,
							handler	: function() {
								
								var cb_value = Ext.getCmp('quantity_cb').getValue();
								
								if(store_info.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_info.data.product_id, quantity: cb_value},
													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_info.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_info.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_info.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_info.data.product_id, quantity: cb_value},
										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_info.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() {
								
								var cb_value = Ext.getCmp('quantity_cb').getValue();
								
								if(store_info.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_info.data.product_id, quantity: cb_value},
													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_info.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_info.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_info.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_info.data.product_id, quantity: cb_value},
										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_info.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);
									}
									
								}
								
							}
						});
						
					}
					
					
					
					
					
					
					
		/* ------------------------------- */			
					// -- 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() {
								var cb_value = Ext.getCmp('quantity_cb').getValue();
								
								Ext.Ajax.request({
									url		: '/products/add_product_to_cart',
									params	: {product_id: store_info.data.product_id, quantity: cb_value},
									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_info.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() {
								var cb_value = Ext.getCmp('quantity_cb').getValue();
								
								Ext.Ajax.request({
									url		: '/products/add_product_to_cart',
									params	: {product_id: store_info.data.product_id, quantity: cb_value},
									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 qty_add_form_panel = new Ext.FormPanel({
						width		: 215,
						autoHeight	: true,
						labelWidth	: 25,
						frame		: false,
						border		: false,
						bodyStyle	: 'background:transparent;',
						renderTo	: el,
						items	: [{
							layout	: 'column',
							border	: false,
							bodyStyle	: 'background:transparent;',
							items	: [{
								columnWidth	: .48,
								layout		: 'form',
								frame		: false,
								border		: false,
								bodyStyle	: 'background:transparent;',
								items	: [{
									xtype			: 'combo',
									id				: 'quantity_cb',
									width			: 60,
									name			: 'quantity',
									fieldLabel		: 'Qty',
									hiddenName		: 'quantity',
									store			: new Ext.data.SimpleStore({
										fields	: ['qty', 'qty_name'],
										data	: [['1', '1'],['2','2'],['3','3'],['4','4'],['5','5'],['6','6'],['7','7'],['8','8'],['9','9'],['10','10']]
									}),
									mode			: 'local',
									valueField		: 'qty',
									displayField	: 'qty_name',
									//emptyText		: 'Qty...',
									typeAhead		: true,
									selectOnFocus	: true,
									forceSelection	: true,
									triggerAction	: 'all',
									value			: '1',
									readOnly		: true,
									allowBlank		: false
								}]
							},{
								columnWidth	: .52,
								frame	: false,
								border	: false,
								bodyStyle	: 'background:transparent;',
								items	: [add_button]
							}]
						}]
					});
				});
			}
		})
	});

	
	var product_reviews_store = new Ext.data.Store({
		storeId		: 'product_reviews_store',
		autoLoad	: true,
		remoteSort	: true,
		proxy: new Ext.data.HttpProxy({
			url		: '/products/get_product_reviews',
			method	: 'POST'
		}),
		baseParams	: {
			product_id	: product_id
		},
		reader: new Ext.data.JsonReader({
			id				: 'review_id',
			root			: 'results',
			successProperty	: 'success'
			}, new Ext.data.Record.create([
				{name: 'review_id', type: 'int'},
				{name: 'first_name', type: 'string'},
				{name: 'last_name', type: 'string'},
				{name: 'star_rating'},
				{name: 'ownership_period', type: 'int'},
				{name: 'recommend_product', type: 'int'},
				{name: 'pros_comments', type: 'string'},
				{name: 'cons_comments', type: 'string'},
				{name: 'other_comments', type: 'string'},
				{name: 'posted_on', type: 'date', dateFormat: 'Y-m-d H:i:s'}
			])
		)
	});	
	
	var review_tpl = new Ext.XTemplate(
		'<tpl for=".">',
		'	<div class="customer_review_container">',
		'		<div class="review_header">',
		'			<table id="table_customer_review">',
		'				<tr valign="middle">',
		'					<td class="col_name_stars">{first_name} {last_name} <span style="padding-left:10px;"><tpl for="star_rating"><img src="/assets/images/products/product_items/star_small.png" style="vertical-align:sub;" /></tpl></span></td>',
		'					<td class="col_posted_on">Posted on {[fm.date(values.posted_on, "n/j/Y g:ia T")]}</td>',
		'				</tr>',
		'				<tr valign="middle">',
		'					<td><div class="ownership_period_label">Ownership Period: <span style="color:white;">{ownership_period:this.formatOwnership}</span></div></td>',
		'					<td><div class="recommend_product_label">Recommend Product: <span style="color:white;">{[values.recommend_product === 1 ? "Yes" : "No"]}</span></div></td>',
		'				</tr>',
		'			</table>',
		'		</div>',
		'		<div class="review_body">',
		'			<div class="pros_comments"><span style="font-size:9pt;font-weight:bold;font-style:italic;">PROS:</span> {pros_comments}</div>',
		'			<div class="cons_comments"><span style="font-size:9pt;font-weight:bold;font-style:italic;">CONS:</span> {cons_comments}</div>',
		'			<div class="other_comments"><span style="font-size:9pt;font-weight:bold;font-style:italic;">OTHER:</span> {other_comments}</div>',
		'		</div>',
		'		<div class="review_footer"></div>',
		'	</div>',
		'</tpl>',
		'<div class="x-clear"></div>',
		{
			formatOwnership: function(value) {
				switch(value) {
					case 1:
						var str = '1 day to 1 week';
						break;
					case 2:
						var str = '1 week to 1 month';
						break;
					case 3:
						var str = '1 month to 6 months';
						break;
					case 4:
						var str = '6 months to 1 year';
						break;
					case 5:
						var str = 'More than 1 year';
						break;
				}
				return str;
			}
		}
	);
	
	var reviews_panel = new Ext.Panel({
		id			: 'product_reviews_panel',
		autoWidth	: true,
		autoHeight	: true,
		frame		: false,
		border		: false,
		bodyStyle	: 'background:transparent;',
		renderTo	: 'product_reviews_container',
		items: new Ext.DataView({
			store	: product_reviews_store,
			tpl		: review_tpl,
			frame	: false,
			border	: false,
			itemSelector	:'div.customer_review_container',
			emptyText		: '<div id="customer_review_no_results"><img src="/assets/images/products/product_pages/product_no_reviews.png"></div>'
		})
	});
	
	
	var write_review_button_panel = new Ext.Panel({
		autoWidth	: true,
		autoHeight	: true,
		frame		: false,
		border		: false,
		renderTo	: 'write_product_review_button',
		buttons		: [{
			text	: 'Write a review',
			width	: 175,
			handler	: function() {
				
				var el = Ext.get('write_product_review_container');
				el.animate(
					{
						height	: {to: 650, from: el.getHeight()},
						width	: {to: 510, from: el.getWidth()}
					},
					1,
					null,
					'easeIn',
					'run'
				);
				
				el.fadeIn();
			}
		}]
	});

	Ext.Ajax.request({
		url		: '/index/is_user_logged_in',
		method	: 'POST',
		success	: function(response,options) {
			var data = Ext.util.JSON.decode(response.responseText);
			if(data.logged_in) {
				var write_review_form_panel = new Ext.FormPanel({
					title	: 'Write a review for this product',
					labelWidth	: 120,
					autoWidth : true,
					autoHeight: true,
					border		: true,
					frame		: true,
					bodyStyle	: 'padding:10px;',
					renderTo: 'write_product_review_container',
					items	: [{
						xtype			: 'combo',
						width			: 150,
						name			: 'star_rating',
						hiddenName		: 'star_rating',
						fieldLabel		: 'Overall Rating',
						store			: new Ext.data.ArrayStore({
							fields	: ['value','option'],
							data	: [['1','1 Star'],['2','2 Stars'],['3','3 Stars'],['4','4 Stars'],['5','5 Stars']]
						}),
						mode			: 'local',
						valueField		: 'value',
						displayField	: 'option',
						emptyText		: 'Choose star rating...',
						typeAhead		: true,
						selectOnFocus	: true,
						forceSelection	: true,
						allowBlank		: false,
						triggerAction	: 'all'
					},{
						xtype			: 'combo',
						width			: 200,
						name			: 'recommend_product',
						hiddenName		: 'recommend_product',
						fieldLabel		: 'Recommend Product',
						store			: new Ext.data.ArrayStore({
							fields	: ['value','option'],
							data	: [['1','Yes'],['2','No']]
						}),
						mode			: 'local',
						valueField		: 'value',
						displayField	: 'option',
						emptyText		: 'Recommend product...',
						typeAhead		: true,
						selectOnFocus	: true,
						forceSelection	: true,
						allowBlank		: false,
						triggerAction	: 'all'
					},{
						xtype			: 'combo',
						width			: 200,
						name			: 'ownership_period',
						hiddenName		: 'ownership_period',
						fieldLabel		: 'Ownership Period',
						store			: new Ext.data.ArrayStore({
							fields	: ['value','option'],
							data	: [['1','1 day to 1 week'],['2','1 week to 1 month'],['3','1 month to 6 months'],['4','6 months to 1 year'],['5','More than 1 year']]
						}),
						mode			: 'local',
						valueField		: 'value',
						displayField	: 'option',
						emptyText		: 'Select ownership period...',
						typeAhead		: true,
						selectOnFocus	: true,
						forceSelection	: true,
						allowBlank		: false,
						triggerAction	: 'all'
					},{
						xtype		: 'textarea',
						name		: 'pros_comments',
						fieldLabel	: 'Pros',
						width		: 350,
						height		: 115,
						allowBlank	: false
					},{
						xtype		: 'textarea',
						name		: 'cons_comments',
						fieldLabel	: 'Cons',
						width		: 350,
						height		: 115,
						allowBlank	: false
					},{
						xtype		: 'textarea',
						name		: 'other_comments',
						fieldLabel	: 'Other',
						width		: 350,
						height		: 115,
						allowBlank	: true
					},{
						xtype		: 'checkbox',
						name		: 'accept_terms',
						allowBlank	: false,
						boxLabel	: 'I have read and agree to abide by the <span id="product_review_guidlines_qtip">Review Guidlines</span>.'
					}],
					buttons	: [{
						text	: 'Cancel / Close',
						style	: {
							marginRight	: '15px'
						},
						handler	: function() {
							write_review_form_panel.getForm().reset();
							var el = Ext.get('write_product_review_container');
							el.animate(
								{
									height	: {to: 0, from: el.getHeight()},
									width	: {to: 0, from: el.getWidth()}
								},
								1,
								null,
								'easeOut',
								'run'
							);
							
							el.fadeOut();
						}
					},{
						text	: 'Submit Review',
						width	: 150,
						handler	: function() {
							write_review_form_panel.getForm().submit({
								url		: '/products/submit_product_review',
								method	: 'POST',
								params	: {product_id: product_id},
								waitMsg	: 'Submitting your review...',
								success	: function(form, action) {
									Ext.Msg.show({
										title	: 'Review Submitted',
										msg		: 'Your review has been submitted and will be authorized within 48 hours.',
										buttons	: Ext.Msg.OK,
										icon	: Ext.MessageBox.INFO,
										minWidth: 400
									});
									
									write_review_form_panel.getForm().reset();
									var el = Ext.get('write_product_review_container');
									el.animate(
										{
											height	: {to: 0, from: el.getHeight()},
											width	: {to: 0, from: el.getWidth()}
										},
										1,
										null,
										'easeOut',
										'run'
									);
									
									el.fadeOut();
								},
								failure	: function(form, action) {
									if(action.failureType == 'server') {
										
										if(action.result.errors.accept_terms) {
											Ext.Msg.show({
												title	: 'Review Guidelines',
												msg		: action.result.errors.accept_terms,
												buttons	: Ext.Msg.OK,
												icon	: Ext.MessageBox.WARNING,
												minWidth: 400
											});
										}
									}
								}
							});
						}
					}]
				});
			} else {
				var write_review_form_panel = new Ext.FormPanel({
					title	: 'Write a review for this product',
					labelWidth	: 120,
					autoWidth : true,
					autoHeight: true,
					border		: true,
					frame		: true,
					bodyStyle	: 'padding:10px;',
					renderTo: 'write_product_review_container',
					items	: [{
						xtype		: 'textfield',
						name		: 'first_name',
						fieldLabel	: 'First Name',
						width		: 150,
						allowBlank	: false
					},{
						xtype		: 'textfield',
						name		: 'last_name',
						fieldLabel	: 'Last Name',
						width		: 150,
						allowBlank	: false
					},{
						xtype		: 'textfield',
						name		: 'contact_email',
						fieldLabel	: 'Email',
						width		: 200,
						allowBlank	: false,
						vtype		: 'email'
					},{
						xtype			: 'combo',
						width			: 150,
						name			: 'star_rating',
						hiddenName		: 'star_rating',
						fieldLabel		: 'Overall Rating',
						store			: new Ext.data.ArrayStore({
							fields	: ['value','option'],
							data	: [['1','1 Star'],['2','2 Stars'],['3','3 Stars'],['4','4 Stars'],['5','5 Stars']]
						}),
						mode			: 'local',
						valueField		: 'value',
						displayField	: 'option',
						emptyText		: 'Choose star rating...',
						typeAhead		: true,
						selectOnFocus	: true,
						forceSelection	: true,
						allowBlank		: false,
						triggerAction	: 'all'
					},{
						xtype			: 'combo',
						width			: 200,
						name			: 'recommend_product',
						hiddenName		: 'recommend_product',
						fieldLabel		: 'Recommend Product',
						store			: new Ext.data.ArrayStore({
							fields	: ['value','option'],
							data	: [['1','Yes'],['2','No']]
						}),
						mode			: 'local',
						valueField		: 'value',
						displayField	: 'option',
						emptyText		: 'Recommend product...',
						typeAhead		: true,
						selectOnFocus	: true,
						forceSelection	: true,
						allowBlank		: false,
						triggerAction	: 'all'
					},{
						xtype			: 'combo',
						width			: 200,
						name			: 'ownership_period',
						hiddenName		: 'ownership_period',
						fieldLabel		: 'Ownership Period',
						store			: new Ext.data.ArrayStore({
							fields	: ['value','option'],
							data	: [['1','1 day to 1 week'],['2','1 week to 1 month'],['3','1 month to 6 months'],['4','6 months to 1 year'],['5','More than 1 year']]
						}),
						mode			: 'local',
						valueField		: 'value',
						displayField	: 'option',
						emptyText		: 'Select ownership period...',
						typeAhead		: true,
						selectOnFocus	: true,
						forceSelection	: true,
						allowBlank		: false,
						triggerAction	: 'all'
					},{
						xtype		: 'textarea',
						name		: 'pros_comments',
						fieldLabel	: 'Pros',
						width		: 350,
						height		: 115,
						allowBlank	: false
					},{
						xtype		: 'textarea',
						name		: 'cons_comments',
						fieldLabel	: 'Cons',
						width		: 350,
						height		: 115,
						allowBlank	: false
					},{
						xtype		: 'textarea',
						name		: 'other_comments',
						fieldLabel	: 'Other',
						width		: 350,
						height		: 115,
						allowBlank	: true
					},{
						id			: 'accept_terms_checkbox',
						xtype		: 'checkbox',
						name		: 'accept_terms',
						value		: '1',
						boxLabel	: 'I have read and agree to abide by the <span id="product_review_guidlines_qtip">Review Guidlines</span>.'
					}],
					buttons	: [{
						text	: 'Cancel / Close',
						style	: {
							marginRight	: '15px'
						},
						handler	: function() {
							write_review_form_panel.getForm().reset();
							var el = Ext.get('write_product_review_container');
							el.animate(
								{
									height	: {to: 0, from: el.getHeight()},
									width	: {to: 0, from: el.getWidth()}
								},
								1,
								null,
								'easeOut',
								'run'
							);
							
							el.fadeOut();
						}
					},{
						text	: 'Submit Review',
						width	: 150,
						handler	: function() {
							
							write_review_form_panel.getForm().submit({
								url		: '/products/submit_product_review',
								method	: 'POST',
								params	: {product_id: product_id},
								waitMsg	: 'Submitting your review...',
								success	: function(form, action) {
									Ext.Msg.show({
										title	: 'Review Submitted',
										msg		: 'Your review has been submitted and will be authorized within 48 hours.',
										buttons	: Ext.Msg.OK,
										icon	: Ext.MessageBox.INFO,
										minWidth: 400
									});
									
									write_review_form_panel.getForm().reset();
									var el = Ext.get('write_product_review_container');
									el.animate(
										{
											height	: {to: 0, from: el.getHeight()},
											width	: {to: 0, from: el.getWidth()}
										},
										1,
										null,
										'easeOut',
										'run'
									);
									
									el.fadeOut();
								},
								failure	: function(form, action) {
									if(action.failureType == 'server') {
										
										if(action.result.errors.accept_terms) {
											Ext.Msg.show({
												title	: 'Review Guidelines',
												msg		: action.result.errors.accept_terms,
												buttons	: Ext.Msg.OK,
												icon	: Ext.MessageBox.WARNING,
												minWidth: 400
											});
										}
									}
								}
							});
						}
					}]
				});
			}
			new Ext.ToolTip({
				id			: 'product_review_guidlines_tip',
				target		: 'product_review_guidlines_qtip',
				title		: 'Product Review Guidelines',
				html		: null,
				width		: 300,
				autoHeight	: true,
				autoHide	: false,
				closable	: true,
				contentEl: 'review_guidlines_qtip_content'
			});
		}
	});
	
	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);

});

ImageViewer = Ext.extend(Ext.Window, {

	initComponent: function() {
		this.bodyCfg = {
			tag: 'img',
			src: this.src
		};
		ImageViewer.superclass.initComponent.apply(this, arguments);
	},

	onRender: function() {
		ImageViewer.superclass.onRender.apply(this, arguments);
		this.body.on('load', this.onImageLoad, this, {single: true});
	},

	onImageLoad: function() {
		var h = this.getFrameHeight(),
			w = this.getFrameWidth();
		this.setSize(this.body.dom.offsetWidth + w, this.body.dom.offsetHeight + h);
		if (Ext.isIE) {
			this.center();
		}
	},

	setSrc: function(src) {
		this.body.on('load', this.onImageLoad, this, {single: true});
		this.body.dom.style.width = this.body.dom.style.width = 'auto';
		this.body.dom.src = src;
	},

	initEvents: function() {
		ImageViewer.superclass.initEvents.apply(this, arguments);
		if (this.resizer) {
			this.resizer.preserveRatio = true;
		}
	}
});
