	
function registerUser(UserInfo, Username){
	
	Ext.Ajax.request({
		url : 'php/insertUser.php',
		params: {
        UserInfo: UserInfo
    	},
		method: 'POST',
		success: function (result, request ) { 
			if (result.responseText == "No"){
				Ext.MessageBox.alert('', 'The Username exists, please select another');
			} else {
				Ext.MessageBox.alert('Success', 'Thank you for registering with us.');
				FinalizeDlg.hide();
				UserName = Username;
				UserType = "Customer";
				UserID = Number(result.responseText);
				var x = '<div align="right">' + UserName + ' | <span id="logoutid" onClick="logout()"> <i><u><font color="blue" size="2" face="Verdana">logout </font></u></i> </span></div>';
				Ext.fly('Login').update(x);
				showPrice();	
				RegisterFlag = false;		
				if (SaveWishFlag == true){
					saveWishList();
					SaveWishFlag = false;
				}
									
			}				
			
		},
		failure: function ( result, request) { 
			Ext.MessageBox.alert('Failed', result.responseText); 
		} 
	});
	
}

   LoginForm = new Ext.FormPanel({   	  
        labelWidth:80,
        frame:true, 
        defaultType:'textfield',
		  width: 300,
        items:[{ 
                fieldLabel: 'Username', 
                id:'loginUsername', 
                allowBlank:false 
            },{ 
                fieldLabel: 'Password', 
                id:'loginPassword', 
                inputType:'password', 
                allowBlank:false 
            }
            ],
         buttons:[
	     			 { 
                	text: 'Forgot your password',
                	handler:function(){ 
							Username = document.getElementById("loginUsername").value;
							UsernameLength = Username.length;
							if (UsernameLength >= 6){
								sendPassword(Username);
							} else {
								Ext.MessageBox.alert('', 'This is not a valid Username');
							} 							
                	} 
            	 },
        			 { 
                	text: 'Login',
                	formBind: true,	 
                	handler:function(){ 
                		checkLogin();        
                	} 
            	 },
            	 {
            	 	text: 'Cancel',
						handler:function(){ 
							LoginFlag = false;
							LoginFormDlg.hide();
            		}
            	 }
            	] 

    });

    LoginFormDlg = new Ext.Window({
           width: 350,
           height: 150,
           closable: true,
           closeAction : 'hide', 
           modal: true,
           title: 'Finalize the Order',
           layout: 'fit',
           items:  LoginForm
	});


function sendPassword(Username){
	Ext.Ajax.request({
		url : 'php/sendPassword.php',
		params: {
   		Username: Username
    		},
		method: 'POST',
		success: function (result, request) {
			Ext.MessageBox.alert('Success', 'A new password has been set to you.');
		},
		failure: function (result, request) { 
			Ext.MessageBox.alert('Failed', result.responseText); 
		} 								
	});
}

function showLogin(){
	 if (LoginFlag == false){
	 	// createForm(); 
 		LoginFormDlg.show();
	 } else {
	 	alert ("Please Login");
	 }
}

function showRegister(){
	RegisterFlag = true;
	FinalizeDlg.show();
	FinalizeDlg.setTitle('Register'); 
}


function logout(){

		Ext.Ajax.request({
   		url: 'php/logout.php',
    		method: 'POST',
			success: function(){
				window.location.reload();
			},
			failure: function(){
		  		Ext.MessageBox.alert('', 'Did not logout properly.');
			}
		});
	 
}

function logoutEdit(){

		Ext.Ajax.request({
   		url: 'php/logout.php',
    		method: 'POST',
			success: function(){
				window.location.href = 'dncSelectProducts.php';
			},
			failure: function(){
		  		Ext.MessageBox.alert('', 'Did not logout properly.');
			}
		});
	 
}

function goToEditProducts(){
	window.location.href = 'dncEditProducts.php';
}

function goToSelectProducts(){
	window.location.href = 'products.php';
}

function checkLogin(){
	UserName = document.getElementById("loginUsername").value;
	PassWord = document.getElementById("loginPassword").value;

	Ext.Ajax.request({
   	url: 'php/checkLogin.php',
    	method: 'POST',
    	params: {
        UserName: UserName,
        PassWord: PassWord
    	},
    	success: function(ObjResponse) {    	 
        var ReturnedText = ObjResponse.responseText;
        var ArrReturnedText = new Array();
        ArrReturnedText = ReturnedText.split(",", 4);
        
		  if (ArrReturnedText[0] == "Valid"){
				UserName = ArrReturnedText[1];
				UserType = ArrReturnedText[2]; 				
				UserType = UserType.trim();
				UserID = ArrReturnedText[3];
				UserID = UserID.trim();
				loadWishListItems();
				
				if (UserType == "Admin"){
					var x = '<div align="right"><font color="purple" size="3" face="Verdana">' + UserName + '</font> | <span id="logoutid" onClick="logout()"> <i><u><font color="blue" size="3" face="Verdana">logout </font></u></i> </span> | <span id="" onClick="goToEditProducts()"> <i><u><font color="blue" size="3" face="Verdana">Edit Products</font></u></i> </span></div>';
		  		} else {
		  			var x = '<div align="right"><font color="purple" size="3" face="Verdana">' + UserName + '</font> | <span id="logoutid" onClick="logout()"> <i><u><font color="blue" size="3" face="Verdana">logout </font></u></i> </span></div>';
		  		} 
		  		
		  		Ext.fly('Login').update(x);
		  		showPrice();		  		
		  		LoginFormDlg.close();
		  } else if (ArrReturnedText[0] == "NotValid"){
		  		Ext.MessageBox.alert('', 'Username or Password is not valid');
		  		LoginFlag = false;
		  }
		  			 
    	},
    	failfure: function(xhr,params) {
        alert('There is an error in processing your request, please email the admin' + ObjResponse.responseText);
    	}
	});
}

function showPrice(){
	ProductsColumnModel.setHidden(4, false);
	TotalsCartColumnModel.setHidden(3, false);
	TotalsCartColumnModel.setHidden(6, false);
	GrandTotalField.show();
	GrandTotal_Label.show();
}

function hidePrice(){
	ProductsColumnModel.setHidden(4, true);
	TotalsCartColumnModel.setHidden(3, true);
	TotalsCartColumnModel.setHidden(6, true);
	GrandTotalField.hide();
	GrandTotal_Label.hide();
}

ProductTypesDataStore = new Ext.data.Store({
	id: 'ProductTypesDataStore',
	proxy: new Ext.data.HttpProxy({
			url: 'php/selectProductTypes.php',
			method: 'POST'
			}),
	
	reader: new Ext.data.JsonReader({  
		root: 'types',
		id: 'ProductTypeID'		
	}, [
		{name: 'ProductTypeID', type: 'string', mapping: 'ProductTypeID'},
		{name: 'ProductTypeName', type: 'string', mapping: 'ProductTypeName'}
	])
});


ProductTypesColumnModel = new Ext.grid.ColumnModel([
	{
   	header: 'ID',
      readOnly: true,
      dataIndex: 'ProductTypeID', // this is where the mapped name is important!
      width: 90,
      hidden: true
   },
   {
      header: 'ProductType',
      dataIndex: 'ProductTypeName',
      width: 100,
	   hidden: false,
  	   sortable: true
   }
]);
     

ProductTypesEditorGrid =  new Ext.grid.EditorGridPanel({
   viewConfig: {
      templates: {
         cell: new Ext.Template(
            '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',
            '<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',
            '</td>'
         )
      }
   },
      id: 'ProductTypesEditorGrid',
      store: ProductTypesDataStore,     // the datastore is defined here
      cm: ProductTypesColumnModel,      // the columnmodel is defined here
      enableColLock:false,
      clicksToEdit:1,
      selModel: new Ext.grid.RowSelectionModel({singleSelect:true})
});

ProductTypesWindow = new Ext.Window({
      id: 'ProductTypesWindow',
      title: 'Categories',
      closable:false,
      collapsible: true,
      width:140,
      height:350,
      x: 80,
      y: 140,
		plain:true,
      layout: 'fit',
      items: ProductTypesEditorGrid  // We'll just put the grid in for now...
});


ProductsDataStore = new Ext.data.Store({
	id: 'ProductsDataStore',
	proxy: new Ext.data.HttpProxy({
			url: 'php/selectProducts.php',
			method: 'POST'
			}),
	baseParams: {ProductTypeID: "0"},
	
	reader: new Ext.data.JsonReader({  
		root: 'Products',
		totalProperty:'total',
		id: 'ProductID'		
	}, [
		{name: 'ProductID', type: 'string', mapping: 'ProductID'},
		{name: 'Description', type: 'string', mapping: 'Description'},
		{name: 'Model', type: 'string', mapping: 'Model'},
		{name: 'PartNumber', type: 'string', mapping: 'PartNumber'},
		{name: 'PriceEconomic', type: 'string', mapping: 'PriceEconomic'},
		{name: 'Quantity', type: 'string', mapping: 'Quantity'},
		{name: 'ProductCondition', type: 'string', mapping: 'ProductCondition'},
		{name: 'Warranty', type: 'string', mapping: 'Warranty'},
		{name: 'UPC', type: 'string', mapping: 'UPC'}
	]),
	remoteSort:true
	
});


ProductsColumnModel = new Ext.grid.ColumnModel([
	{
   	header: 'ProductID',
      readOnly: true,
      dataIndex: 'ProductID', // this is where the mapped name is important!
      width: 90,
      hidden: true,
      hideable: false
   },
   {
      header: 'Description',
      dataIndex: 'Description',
      width: 260,  
	   hidden: false,
	   sortable: true,
	   renderer:function(val, cell, record) {	 
      	return '<div qtip="' + '<span>'+ record.data.Description +'</span>' +'">'+ val +'</div>';
      	}
   },
   {
      header: 'Model',
      dataIndex: 'Model',
      width: 80,
      align : 'center',
      sortable: true,
	   hidden: false
   },
   {
      header: 'Part#',
      dataIndex: 'PartNumber',
      width: 70,
      align : 'center',
      sortable: true,
	   hidden: false
   },
   {
      header: 'Price',
      dataIndex: 'PriceEconomic',
      width: 60,
      align : 'right',
      sortable: true,
	   hidden: false,
	   hideable: false
   },
   {
      header: 'Quantity',
      dataIndex: 'Quantity',
      width: 60,
      align : 'center',
      sortable: true,
	   hidden: false
   },
   {
      header: 'Condition',
      dataIndex: 'ProductCondition',
      width: 80,
      align : 'center',
      sortable: true,
	   hidden: false
   },
   {
      header: 'Warranty',
      dataIndex: 'Warranty',
      width: 80,
      align : 'center',
      sortable: true,
	   hidden: false
   },
   {
      header: 'UPC',
      dataIndex: 'UPC',
      width: 80,
      align : 'center',
      sortable: true,
	   hidden: true
   }
]);

var ArrItemsObject = Ext.util.JSON.decode('{"Items": []}');

var Item = Ext.data.Record.create([
									{name: 'ProductTypeName'},
									{name: 'ProductName'},
									{name: 'Model'},
									{name: 'PartNumber'},
									{name: 'PriceEconomic'},
									{name: 'Quantity'},	
									{name: 'ItemTotal'},
									{name: 'UPC'}							
									]);
			
var ItemsReader = new Ext.data.JsonReader(
									{ root: 'Items'},
									[ 
									 Item							
									]);

var aNumberField_QuantityToAddProducts = new Ext.form.NumberField(
																		{
																			id: 'ItemQuantityProducts',
																			width     : 30,
																			emptyText : '',
																			value: '1',
																			readOnly: true 
																		}
																	);

ProductsGridMessage = "No Records Found - Please Select a category";

ProductsEditorGrid =  new Ext.grid.EditorGridPanel({
      id: 'ProductsEditorGrid',
      store: ProductsDataStore,     // the datastore is defined here
      cm: ProductsColumnModel,      // the columnmodel is defined here
      enableColLock:false,
      clicksToEdit:1,
      selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
      tbar:[],
      plugins:[new Ext.ux.grid.Search({
			iconCls:'icon-zoom',
			position:'tbar',
			mode:'remote',
			width:200,
			shortcutEl:document,
			minChars:1
     })],
     bbar: new Ext.PagingToolbar({
     		pageSize: 10,
			store: ProductsDataStore,
			displayInfo:true,
			displayMessage: "Displaying Products {0} - {1} of {2}"
     }),
     	buttons: [
     	   		{
							id: 'SubtractOne',
						   text: '-',
							minWidth: 50,
							handler: function() {
														OldQuantity = aNumberField_QuantityToAddProducts.getRawValue();
														if (OldQuantity > 1){														
															NewQuantity = Number(OldQuantity) - 1;
															aNumberField_QuantityToAddProducts.setRawValue(NewQuantity);
														}	
																				
														}
					},
					aNumberField_QuantityToAddProducts,
					{
							id: 'AddOne',
						   text: '+',
							minWidth: 50,
							handler: function() {
														
														OldQuantity = aNumberField_QuantityToAddProducts.getRawValue();
														NewQuantity = Number(OldQuantity) + 1;
														aNumberField_QuantityToAddProducts.setRawValue(NewQuantity);																			
														}
					},
				  	{
							id: 'AddItemToCart',
						   text: 'Add Item To Cart',
							minWidth: 50,
							handler: function() {
							 							var rec = ProductsEditorGrid.getSelectionModel().getSelected();
														ProductTypeName = ProductTypeName;															
														ProductName = rec.get('Description');
														PriceEconomic = rec.get('PriceEconomic');
														Model = rec.get('Model');
														PartNumber = rec.get('PartNumber');
														Quantity = aNumberField_QuantityToAddProducts.getRawValue();
														var TotalItem = Number(PriceEconomic) * Number(Quantity);
														TotalItem = TotalItem.toFixed(2);
										
										
														FoundMatchingRecord = checkForDuplicate(ProductTypeName, ProductName, PriceEconomic);
														if (FoundMatchingRecord == false){
															TotalsCartDataStore .add(new Item({
	 															ProductTypeName: ProductTypeName,
    															ProductName: ProductName,
    															Model: Model,
    															PartNumber: PartNumber,
    															PriceEconomic: PriceEconomic,
    															Quantity: Quantity,
    															ItemTotal: TotalItem
															}));
															
															GrandTotalAmount = Number(GrandTotalAmount) + Number(TotalItem);														
															GrandTotalAmount = GrandTotalAmount.toFixed(2);
															GrandTotalField.setRawValue(GrandTotalAmount);															
														
														} else {
															Ext.MessageBox.alert('', 'This item is in the cart.  Please remove if you want to re-add');											
														}																											
							}
					}

					],
	 view: new Ext.grid.GridView({
    		forceFit: true,
    		emptyText: ProductsGridMessage,
    		      	templates: {
         	cell: new Ext.Template(
            	'<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',
           		'<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',
            	'</td>'
        		)
        	}
	 })


});

 



ProductsEditorGrid.on("rowclick", function (theGrid, theRowIndex, e) { 
																				aNumberField_QuantityToAddProducts.setRawValue(1);
																			});


ProductsWindow = new Ext.Window({
      id: 'ProductsWindow',
      title: 'Inventory',
      closable:false,
      collapsible: true,
      width:760,
      height:350,
      x: 225,
      y: 140,
		plain:true,
      layout: 'fit',
      items: ProductsEditorGrid  // We'll just put the grid in for now...
});


function checkForDuplicate(ProductTypeNameAdd, ProductNameAdd, PriceEconomicAdd){

	var FoundMatchingRecord = false;
	var MaxItems = TotalsCartDataStore.getCount();	

   for (i = 0; i<MaxItems; i++){
		var row = TotalsCartEditorGrid.getView().getRow(i);
   	var record = TotalsCartDataStore.getAt(i);
   	var ProductName = record.get('ProductName');
   	var ProductTypeName = record.get('ProductTypeName');
   	var Price = record.get('PriceEconomic');
   	
   	if (ProductTypeNameAdd == ProductTypeName && ProductNameAdd == ProductName && PriceEconomicAdd == PriceEconomic){
			FoundMatchingRecord = true;
			return FoundMatchingRecord; 
			break;
		}
   }	
   
	return FoundMatchingRecord;	
}


TotalsCartColumnModel = new Ext.grid.ColumnModel([
   {
      header: 'Category',
      dataIndex: 'ProductTypeName',
      width: 100,
	   hidden: false
   },
   {
      header: 'Description',
      dataIndex: 'ProductName',
      width: 175,
      sortable: false,
	   hidden: false
   },
   {
      header: 'Model',
      dataIndex: 'Model',
      width: 75,
	   hidden: false
   },
   {
      header: 'Price',
      dataIndex: 'PriceEconomic',
      width: 75,
	   hidden: false,
	   hideable: false
   },
   {
      header: 'Quantity',
      dataIndex: 'Quantity',
      width: 75,
	   hidden: false
   },
   {
      header: 'Part#',
      dataIndex: 'PartNumber',
      width: 75,
	   hidden: false
   },   
   {
      header: 'Total for item',
      dataIndex: 'ItemTotal',
      width: 75,
	   hidden: false,
	   hideable: false
   }
   
]);

var ArrItemsObject2 = Ext.util.JSON.decode('{"Items": []}');

var TotalsCartItem = Ext.data.Record.create([
									{name: 'ProductTypeName'},			
									{name: 'ProductName'},
									{name: 'Model'},
									{name: 'PartNumber'},
									{name: 'PriceEconomic'},
									{name: 'Quantity'},
									{name: 'ItemTotal'}		
									]);
			
var TotalsCartItemsReader = new Ext.data.JsonReader(
									{ root: 'Items'},
									[ 	
										TotalsCartItem
									]);
									
									TotalsCartDataStore = new Ext.data.Store({reader: TotalsCartItemsReader});


GrandTotalField = new Ext.form.NumberField(
																		{
																			id: 'GrandTotal',
																			width     : 50,
																			emptyText : '',
																			value: '0.00',
																			readOnly: true
																		}
																	);

var GrandTotal_Label = new Ext.form.Label({
															html: '<span class="GridFooterText">Grand Total:&nbsp; </span>'
															
														});


TotalsCartEditorGrid =  new Ext.grid.EditorGridPanel({
	  viewConfig: {
      	templates: {
         	cell: new Ext.Template(
            	'<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',
           		'<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',
            	'</td>'
        		)
        	}
      },
      id: 'TotalsCartEditorGrid',
      store: TotalsCartDataStore,
      cm: TotalsCartColumnModel,      // the columnmodel is defined here
      enableColLock:false,
      clicksToEdit:1,
      selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
     	buttons: [
     				GrandTotal_Label,
     				GrandTotalField,
    				{
						id: 'Finalize',
					   text: 'Finalize',
						minWidth: 50,
						handler: function() {
							if (TotalsCartDataStore.getCount() > 0 ){
								FinalizeDlg.show();
								if (UserName != "None"){								
									loadUserInfo();
								}
							} else {
								Ext.MessageBox.alert('', 'Please select atleast one item to process.');
								

							}
						}
					},
					{
						id: 'RemoveItem',
					   text: 'Remove Item',
						minWidth: 50,
						handler: function() {
							Selected = TotalsCartEditorGrid.getSelectionModel().getSelected();
							ItemTotal = Selected.data.ItemTotal;
							GrandTotalAmount = Number(GrandTotalAmount) - Number(ItemTotal);		
							GrandTotalAmount = GrandTotalAmount.toFixed(2);
							GrandTotalField.setRawValue(GrandTotalAmount);	
														
							TotalsCartEditorGrid.getStore().remove(Selected);
						}
					}
					]		
});


TotalsCartWindow = new Ext.Window({
      id: 'TotalsCartWindow',
      title: 'Totals Cart',
      closable:false,
      collapsible: true,
      width:520,
      height:230,
      x: 80,
      y: 500,
		plain:true,
      layout: 'fit',
      items: TotalsCartEditorGrid  // We'll just put the grid in for now...
});

function processOrder(UserInfo){
	
	var OrderItemsJson = {"OrderItems": []
						};
	var MaxItems = TotalsCartDataStore.getCount();	

   for (i = 0; i<MaxItems; i++){
		var row = TotalsCartEditorGrid.getView().getRow(i);
   	var record = TotalsCartDataStore.getAt(i);
   	var ProductName = record.get('ProductName');
   	var ProductTypeName = record.get('ProductTypeName');
   	var Quantity = record.get('Quantity');
   	var Price = record.get('PriceEconomic');
   	var Model = record.get('Model');
   	var PartNumber = record.get('PartNumber');
   	   	  		
		OrderItemsJson = addToJson(OrderItemsJson, i, ProductTypeName, ProductName, Price, Quantity, Model, PartNumber);
   }
   
	var OrderItemsString = JSON.stringify(OrderItemsJson);  
   
	Ext.Ajax.request({
		url : 'php/process.php',
		params: {
        UserInfo: UserInfo,
        OrderInfo: OrderItemsString
    	},
		method: 'POST',
		success: function (result, request ) { 
			if (result.responseText == "No"){
					Ext.MessageBox.alert('', "This Username exists, please chose another or login"); 
			} else {
				Ext.MessageBox.alert('Success', ''+ result.responseText);
				FinalizeDlg.close();
				window.location.reload(); 
			}			
		},
		failure: function ( result, request) { 
			Ext.MessageBox.alert('Failed', result.responseText); 
		} 
	});
   
}	

function addToJson(OrderItemsJson, i, ProductTypeName, ProductName, Price, Quantity, Model, PartNumber){    			
	var AddItem = new Object();
	AddItem.ProductTypeName = ProductTypeName;
	AddItem.ProductName = ProductName;
	AddItem.Price = Price;
	AddItem.Quantity = Quantity;
	AddItem.Model = Model;
	AddItem.PartNumber = PartNumber;
	OrderItemsJson.OrderItems[i] = AddItem; 
	return OrderItemsJson;
}

WishListColumnModel = new Ext.grid.ColumnModel([
   {
      header: 'Description',
      dataIndex: 'Description',
      width: 240,
	   hidden: false
   },
   {
      header: 'Model#',
      dataIndex: 'ModelNumber',
      width: 70,
	   hidden: false
   },   
   {
      header: 'Quantity',
      dataIndex: 'Quantity',
      width: 50,
	   hidden: false
   },
   {
      header: 'Type',
      dataIndex: 'Type',
      width: 50,
	   hidden: true
   },
   {
      header: 'WishListItemID',
      dataIndex: 'WishListItemID',
      width: 50,
	   hidden: true  
   }
   
]);

ArrItemsObject3 = Ext.util.JSON.decode('{"WishListItems": []}');

var WishListItem = Ext.data.Record.create([
									{name: 'Description'},
									{name: 'ModelNumber'},
									{name: 'Quantity'},
									{name: 'Type'},
									{name: 'WishListItemID'}
									]);
			
var WishListItemsReader = new Ext.data.JsonReader(
									{ root: 'WishListItems'},
									[ 
									 WishListItem
									]);		

WishListDataStore = new Ext.data.Store({reader: WishListItemsReader});

WishListEditorGrid =  new Ext.grid.EditorGridPanel({
      id: 'WishListEditorGrid',
      store: WishListDataStore,
      cm: WishListColumnModel,      // the columnmodel is defined here
      enableColLock:false,
      clicksToEdit:1,
      selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
      emptyText: 'No Record found'
		});

WishListWindow = new Ext.Window({
      id: 'WishListWindow',
      title: 'WishList Items',
      closable:false,
      collapsible: true,
      width:380,
      height:230,
      x: 605,
      y: 500,
		plain:true,
      layout: 'fit',
      items: WishListEditorGrid,
      bbar: [
      		{
           		text: 'Add',
            	iconCls: 'silk-add',
						handler: function() {
									createWishForm();								
									WishListDlg.show();		
						}            	
        		}, '-', 
        		{
            	text: 'Delete',
            	iconCls: 'silk-delete',
        			handler: function() {
							record = WishListEditorGrid.getSelectionModel().getSelected();
							Type = record.get('Type');
							if (Type == "Db"){
								WishListItemID = record.get('WishListItemID');
								removeItemFromWishList(WishListItemID);
							}
							
							WishListEditorGrid.getStore().remove(
									WishListEditorGrid.getSelectionModel().getSelected()
							);
					}
				
				}, '-', 
        		{
            	text: 'Save and Send',
            	iconCls: 'icon-save',
        			handler: function() {
        				if (WishListDataStore.getCount() > 0 ){
        					if (UserName != "None"){
        						saveWishList();
        					} else {
 								showRegister();
 								SaveWishFlag = true;
        					}
        				} else {
        					Ext.MessageBox.alert('', 'Please add atleast one item to process.');
        				}
					}
        		} 
        		]
});		


function removeItemFromWishList(WishListItemID){
	Ext.Ajax.request({
		loadMask: true,
		url : 'php/deleteWishListItems.php',
		params: {
        WishListItemID: WishListItemID
    	},
    	method: 'POST',
    	success: function (resp) {		
		}    
	});
}


function loadWishListItems(){

	var WishListItemsJsonDb; 	

	Ext.Ajax.request({
		loadMask: true,
		url : 'php/selectWishListItems.php',
		params: {
        UserID: UserID
    	},
		method: 'POST',
		success: function (resp) {
			var WishListItemsDb = Ext.decode(resp.responseText).WishListItemsDb;
    		Ext.each(WishListItemsDb, function(op) {
      		Description = op.Description;
      		Model = op.Model;
      		Quantity = op.Quantity;
      		WishListItemID = op.WishListItemID;
				addWishItemDb(WishListItemID, Description, Model, Quantity);
      		
    		})
		}
	});
		
}


function addWishItemDb(WishListItemID, Description, Model, Quantity){

		WishListDataStore .add(new WishListItem({
			WishListItemID: WishListItemID,
	 		Description: Description,
    		ModelNumber: Model,
    		PriceEconomic: "00.00",    		
    		Quantity: Quantity,
    		Type: "Db"    		
		}));		
}

function createWishForm(){

WishListForm = new Ext.FormPanel({
	labelWidth: 100,
   width: 500,
   frame: true,
   items: [
   		 {	xtype: 'textfield',
            fieldLabel: 'Description',
            id: 'WishListDescription',
            width: 290,
            allowBlank:false
          },
          {
          	xtype: 'textfield',
            fieldLabel: 'ModelNumber',
          	id: 'WishListModelNumber',
           	width: 50,
           	allowBlank: false
          },
          {
           	xtype: 'textfield',
            fieldLabel: 'Quantity',
           	id: 'WishListQuantity',
           	width: 50,
          	allowBlank: false
          }
          ],
	buttons: [
				{
					text: 'Add',
               minWidth: 75,
               handler: function() {
						addToWishList();             	
               	WishListDlg.close();
            	}
            },
            {
            	text: 'Cancel',
               minWidth: 75,
               handler: function() {
               	WishListDlg.close();
               }                   			
             }
             ]
       	});

WishListDlg = new Ext.Window({
           width: 500,
           height: 170,
           closable: false,
           closeAction : 'hide', 
           modal: true,
           title: 'Please add a wish list item:',
           layout: 'fit',
           items: WishListForm
});


}        


function addToWishList(){
		WishListDescription = document.getElementById("WishListDescription").value;
		WishListModelNumber = document.getElementById("WishListModelNumber").value;
		WishListQuantity = document.getElementById("WishListQuantity").value;
		// alert ("add to wish list cart" + WishListDescription + WishListModalNumber + WishListQuantity);
		
		WishListDataStore .add(new Item({
				Description: WishListDescription,
				ModelNumber: WishListModelNumber,
				Quantity: WishListQuantity,
				Type: "New",
				WishListItemID: "xx"
		}));
}  



UserRegistrationForm = new Ext.FormPanel({
	labelWidth: 150,
	url: 'php/loadUserInfo.php',
   width: 500,
   frame: true,
   items: [
   		 {	
   		 	xtype: 'textfield',
            fieldLabel: 'Full Name',
            id: 'UserFullName',
            width: 150,
            allowBlank:false,
            minLength: 2
          },
          {	
          	xtype: 'textfield',
            fieldLabel: 'Username (min 6 chars)',
            id: 'Username',
            allowBlank:false,
            width: 150,
            minLength: 6
          }, 
          {
          	xtype: 'textfield',
            fieldLabel: 'Password (min 6 chars)',
        		id: 'Password',
        		allowBlank:false,
        		minLength: 6,
        		width: 150,
        		inputType: 'password'
        	
      	 },  
      	 {
      	 	xtype: 'textfield',
            fieldLabel: 'Email',
            id: 'Email',
            vtype:'email',
        		width: 150,
            allowBlank:false
          }, 
          {
          	xtype: 'textfield',
 				fieldLabel: 'Phone',
            id: 'Phone',
        		width: 150,
        		allowBlank:false
          },
          {
				xtype: 'combo',
				fieldLabel:'Customer Type',
				id: 'CustomerIndustry',
				triggerAction: 'all',
				mode: 'local',
				width: 150,
				editable: false,
				store:new Ext.data.SimpleStore({
					fields:['CustomerTypeValue', 'CustomerTypeLabel'],
					data:[
							['IT', 'IT'], 
							['Retail', 'Retail'],
							['Wholesale', 'Wholesale']
							]
				}),				
				displayField:'CustomerTypeLabel',
				valueField:'CustomerTypeValue'
			 },
          {
            xtype: 'label',
				text: 'Any pricing on your shopping list are APPROXIMATE only. Please bear this in mind when looking at the total.',
				width: 300
			 }
          
          ],
    buttons: [
				{
					text: 'Submit',
               minWidth: 75,
               buttonAlign: 'center',
               handler: function() {
               	ValidationFlag = UserRegistrationForm.getForm().isValid();
						if (ValidationFlag == true){
			
						   UserFullName = document.getElementById("UserFullName").value;
						   Username = document.getElementById("Username").value;
						   Password = document.getElementById("Password").value;						   
               		Email = document.getElementById("Email").value;
               		Phone = document.getElementById("Phone").value;
               		CustomerType = document.getElementById("CustomerIndustry").value;
               		UserInfo = UserID + " Info: " + UserFullName + " Info: " + Username + " Info: " + Password + " Info: " + Email + " Info: " + Phone + " Info: " + CustomerType;

							if (RegisterFlag == false){               		               		
               			processOrder(UserInfo);               			
               		} else {
               			registerUser(UserInfo, Username);
               		}
               		                 		
						} else {
							Ext.MessageBox.alert('', 'Please provide all the required informaiton'); 
						}
            	}
            }
            ]

   });
   
   FinalizeDlg = new Ext.Window({
           width: 500,
           height: 240,
           closable: true,
           closeAction : 'hide', 
           modal: true,
           title: 'Finalize the Order',
           layout: 'fit',
           items: UserRegistrationForm
	});


function loadUserInfo(){
	UserRegistrationForm.load({
			url: UserRegistrationForm.url,
			params: {User:  UserID}
	});
}


  
    
		






