/// <reference path="Ext.Dummy.js" />
/// <reference path="common.js" />
/// <reference path="logon.js" />

var orderForm = null;
var largePopup = null;
var imgPopup = null;
var orderPopup = null;
var styleStore = null;
var pnlSizeSwatch =  null;
var pnlColorSwatch = null;
var pnlAddToCart = null;
var pnlGemColor = null;
var pnlMain = null;
var colorStore = null;
var gemColorStore = null;
var frmPaypal = null;
var gfOrderItem = function(){
		
}
gfOrderItem.prototype = {
	gemPattern: null,
	shoeColor:	null,
	gemColor: null,
	shoeSize: null
}
var orderItem = new gfOrderItem();

function submitForm(){
	frmPaypal = document.getElementById("frmPaypal");
	var item_number = document.getElementById("item_number");
	var amount = document.getElementById("amount");
	var weight = document.getElementById("weight");
	var item_name = document.getElementById('item_name');
	var quantity = document.getElementById('quantity');
	item_name.value = String.format(
		"{0} :: {1} Gems :: Womens Size {2} {3}",
		orderItem.gemPattern.data.name,
		orderItem.gemColor.data.name,
		orderItem.shoeSize,
		orderItem.shoeColor.data.name
	);
	item_number.value = String.format(
		"{0}{1}{2}{3}",
		orderItem.gemPattern.data.id,
		orderItem.gemColor.data.id,
		orderItem.shoeSize,
		orderItem.shoeColor.data.id
	);
	amount.value = orderItem.gemPattern.data.price;
	quantity.value = orderForm.findById("txtQuantity").getValue();
	frmPaypal.submit();
}
function hidePopup(){
	imgPopup.close();
}
var firstTime = true;
var gemSelectedColor = null;
function selectGemColor(img, colorId){
	var currentColor = gemColorStore.getById(colorId);
	orderItem.gemColor = currentColor;
	orderForm.findById('txtGemColor').setValue(currentColor.data.name);
	if(gemSelectedColor != null){
		gemSelectedColor.style.borderColor = '#BBBBBB';	
	}
	img.style.borderColor = 'black';	
	gemSelectedColor = img;
}

var selectedColor = null;
function selectColor(img, colorId){
	var currentColor = colorStore.getById(colorId);
	orderItem.shoeColor = currentColor;
	orderForm.findById('txtShoeColor').setValue(currentColor.data.name);
	if(selectedColor != null){
		selectedColor.style.borderColor = '#BBBBBB';	
	}
	img.style.borderColor = 'black';	
	selectedColor = img;
}
var selectedSize = null;
function setSize(button, size){
	orderItem.shoeSize = size;
	orderForm.findById('txtShoeSize').setValue('Womens ' + size);
	if(selectedSize != null){
		selectedSize.style.borderColor = '#808080';	
	}
	button.style.borderColor = 'black';	
	selectedSize = button;
}

function order(ordinal){
	var currentStyle = styleStore.getAt(ordinal);
	orderItem.gemPattern = currentStyle;
	if(orderPopup == null){
		orderPopup = new Ext.Window({
			draggable: false,
			pageY: 200,
			pageX: 180,
			closeAction: 'hide',
			margins: '0 0 0 0',
			title: "Order " + currentStyle.data.name,
			layout:'border',
			items:[
				new Ext.Panel({
					//cls:'productDiv',
					region: 'west',
					bodyBorder: false,
					borderStyle: 'none',
					frame: true,
					html: String.format(
						'<div align="center"><img id="orderImage" src="{0}" border="0" /></div>',
						currentStyle.data.image
					)
				}),
				orderForm
			],
			width: 600,
			height: 400,
			modal: true,
			closable: true,
			constrain: true,
			container: pnlMain.getEl(),
			listeners:{
				startMove : function(){
			        if(this.proxyDrag){
			            this.proxy.show();
			        }
			        if(this.constraintoviewport !== false){
			            this.dd.constrainTo(this.container || document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
			        }
			    }
			} 
		});	
	}
	orderForm.findById('txtGemPattern').setValue(currentStyle.data.name);
	orderForm.findById('txtPrice').setValue(currentStyle.data.price);
	if(firstTime){
		orderPopup.show();
		pnlColorSwatch.setWidth(300);
		pnlSizeSwatch.setWidth(400);
		pnlAddToCart.setWidth(300);
		pnlGemColor.setWidth(400);
		firstTime = false;
	}else{
		orderPopup.setTitle("Order " + currentStyle.data.name);
		document.getElementById('orderImage').src = currentStyle.data.image;
		orderPopup.show();
	}
	setSize(document.getElementById('shoeSize9'), 9);
	selectColor(document.getElementById('imgShoeColor' + currentStyle.data.defaultShoeColor), currentStyle.data.defaultShoeColor);
	selectGemColor(document.getElementById('imgGemColor' + currentStyle.data.defaultGemColor), currentStyle.data.defaultGemColor);
}


Ext.onReady(function(){
	var loader = new Ext.LoadMask('loadmask', {msg: 'Loading GemFlops.com'});
	loader.show();
	var styleReader = new Ext.data.JsonReader({
        root: 'styles',
        totalProperty: 'total',
        id: "id",
        fields: [
            'id',                 
            'name',
            'image',
            'price',
            'largeImage',
            'defaultGemColor', 
            'defaultShoeColor'
        ]
    });
   	var styleTree = new Ext.tree.TreePanel({
   		region: 'west',
		title: 'Styles',
   		useArrows:true,
   		width: 150,
   		rootVisible: false,
        autoScroll:true,
        animate:true,
        enableDD:false,
        containerScroll: true, 
        loader: new Ext.tree.TreeLoader({
            dataUrl:'get-nodes.php'
        }),
		root: new Ext.tree.TreeNode({
			text: 'Styles',
			draggable: false,
			leaf: false	
		})
	});
	styleStore = new Ext.data.Store({
        proxy: new Ext.data.MemoryProxy({
			"total": 8,
			"styles": [
				{"id": "GFDS", "name":"Daisy Single", "image":"products/styles/Daisy_Single_Gallery.jpg", "price": "15.00", largeImage: "products/styles/Daisy_Single_Detail_Lge2.jpg", defaultGemColor: "SPHR", defaultShoeColor: "WHTE" },
				{"id": "GFDT", "name":"Daisy Trails", "image":"products/styles/Daisy_Trails_Gallery2.jpg", "price": "20.00", largeImage: "products/styles/Daisy_Trails_Detail_Lge.jpg", defaultGemColor: "SPHR", defaultShoeColor: "RPNK" },
				{"id": "GFDB!", "name":"Daisy Bling!", "image":"products/styles/Daisy_Bling_Gallery.jpg", "price": "25.00", largeImage: "products/styles/Daisy_Bling_Detail_Lge.jpg", defaultGemColor: "LSIAM", defaultShoeColor: "DSBL" },
				{"id": "GFDB", "name":"Daisy Bouquet", "image":"products/styles/Daisy_Bouquet_Detail_List.jpg", "price": "23.00", largeImage: "products/styles/Daisy_Bouquet_Detail_Lge.jpg", defaultGemColor: "SPHR", defaultShoeColor: "WHTE" },
				{"id": "GFST", "name":"Sunflower Trio", "image":"products/styles/Sunflower_Trio_Gallery.jpg", "price": "18.00", largeImage: "products/styles/Sunflower_Trio_Detail_Lge.jpg", defaultGemColor: "LTPZ", defaultShoeColor: "BRNE" },
				{"id": "GFSB", "name":"Sunflower Bouquet", "image":"products/styles/Sunflower_Bouquet_Gallery.jpg", "price": "23.00", largeImage: "products/styles/Sunflower_Bouquet_Detail_Lge.jpg", defaultGemColor: "LTPZ", defaultShoeColor: "BRNE" },
				{"id": "GFSB!", "name":"Simple Bling!", "image":"products/styles/Simple_Bling_Gallery.jpg", "price": "20.00", largeImage: "products/styles/Simple_Bling_Detail_Lge.jpg", defaultGemColor: "RSE", defaultShoeColor: "NBLK" },
				{"id": "GFB!", "name":"Bling!", "image":"products/styles/Bling_Gallery.jpg", "price": "25.00", largeImage: "products/styles/Bling_Detail_Lge.jpg", defaultGemColor: "CLR", defaultShoeColor: "RPNK" },
				{"id": "GFSQB!", "name":"Square Bling!", "image":"products/styles/Square_Bling_Gallery.jpg", "price": "25.00", largeImage: "products/styles/Square_Bling_Detail_Lge.jpg", defaultGemColor: "SPHR", defaultShoeColor: "RPNK" }
			]
		}),
        listeners:{
            loadexception : function(store){
                Ext.MessageBox.show({
                    msg: String.format('Error loading {0} store', 'STYLE'),
                    icon: Ext.MessageBox.ERROR
                });
            }
        },
        reader: styleReader,
        remoteSort: false
    });
    styleStore.load();
    function selectNode(node, e){
    	var prodDivEl = Ext.get(node.attributes.productId);
    	prodDivEl.scrollIntoView('ext-gen126');
    	/*
    	var divTop = prodDivEl.getTop();
    	var prodDivContainerEl = Ext.get('ext-gen126');
    	var scroll = prodDivContainerEl.getScroll() ;
    	if(scroll.top < divTop){
    		prodDivContainerEl.scroll('down', divTop - scroll.top, true);	
		}else{
			prodDivContainerEl.scroll('up', scroll.top - divTop, true);	
		}*/
    }
	for(var l=0;l<styleStore.getCount();l++){
		var styleRecord = styleStore.getAt(l);
		styleTree.getRootNode().appendChild( 
			new Ext.tree.TreeNode({
				id: 'nod_' + l,
				productId: 'product' + l,
				text: styleRecord.data.name,
				iconCls: 'product-node',
				leaf: true,
				draggable: false,
				listeners:{click: selectNode}
			})
		);
	}
    var colorReader = new Ext.data.JsonReader({
        root: 'colors',
        totalProperty: 'total',
        id: "id",
        fields: [
            'id',     
            'name',
            'image'
        ]
    });
    
    
    colorStore = new Ext.data.Store({
        proxy: new Ext.data.MemoryProxy({
			"total": 12,
			"colors": [
				{"id": "BRNE", "name": "Brown", "image":"products/colorswatch/onBrownEarth.gif"},            
				{"id": "DSBL", "name": "Dark Blue", "image":"products/colorswatch/onDarkSeaBlue.gif"},      
				{"id": "MGRY", "name": "Dark Grey", "image":"products/colorswatch/onMagnumGray.gif"},      
				{"id": "NBLK", "name": "Black", "image":"products/colorswatch/onNewBlack.gif"},      
				{"id": "RPNK", "name": "Pink", "image":"products/colorswatch/onRoseBayPink.gif"},      
				{"id": "WHTE", "name": "White", "image":"products/colorswatch/onWhite.gif"} 
			]   
		}),     
        listeners:{
            loadexception : function(store){
                Ext.MessageBox.show({
                    msg: String.format('Error loading {0} store', 'COLOR'),
                    icon: Ext.MessageBox.ERROR
                });
            }   
        },      
        reader: colorReader,
        remoteSort: false
    });
    
    
    gemColorStore = new Ext.data.Store({
        proxy: new Ext.data.MemoryProxy({
			"total": 12,
			"colors": [
				{"id": "CLR", name: "Crystal", "image": "images/gems/swatches/clear.jpg"},
				{"id": "LSPHR", name: "Light Blue", "image": "images/gems/swatches/Light_Sapphire.jpg"},
				{"id": "SPHR", name: "Blue", "image": "images/gems/swatches/Sapphire.jpg"},
				{"id": "EMRLD", name: "Green", "image": "images/gems/swatches/Emerald.jpg"},
				{"id": "LTPZ", name: "Gold", "image": "images/gems/swatches/Light_Topaz.jpg"},
				{"id": "CTRN", name: "Yellow", "image": "images/gems/swatches/citrine.jpg"},
				{"id": "LRSE", name: "Light Pink", "image": "images/gems/swatches/Light_Rose.jpg"},
				{"id": "RSE", name: "Pink", "image": "images/gems/swatches/Rose.jpg"},
				{"id": "LSIAM", name: "Red", "image": "images/gems/swatches/Light_Siam.jpg"},
				{"id": "LAMYTS", name: "Light Purple", "image": "images/gems/swatches/Light_Amethyst.jpg"},
				{"id": "AMYTS", name: "Purple", "image": "images/gems/swatches/Amethyst.jpg"}
			]   
		}),     
        listeners:{
            loadexception : function(store){
                Ext.MessageBox.show({
                    msg: String.format('Error loading {0} store', 'COLOR'),
                    icon: Ext.MessageBox.ERROR
                });
            }   
        },      
        reader: colorReader,
        remoteSort: false
    });
    colorStore.load();
   	gemColorStore.load();
   
    Ext.QuickTips.init();

    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';

	var s = "";
	for(var i=0;i<colorStore.getCount();i++){
		var currentColor = colorStore.getAt(i);
		s += String.format(
			'<img id="imgShoeColor{1}" src="{0}" onclick="selectColor(this, \'{1}\');" ext:qtitle="{2}" ext:qwidth="100" ext:qtip="Click to choose Shoe Color."/>',
			currentColor.data.image,
			currentColor.data.id,
			currentColor.data.name
		);
		if(i == 5){
			s += "<BR/>";
		}
	} 
	pnlColorSwatch = new Ext.Panel({
		fieldlabel: '(Click&nbsp;to&nbsp;Choose)',
    	id: 'colorSwatch',
    	width: 340,
    	style: 'padding-left: 90px;',
    	html: s
    });
    var sizeString = "";
    for(i=6;i<12;i++){
    	sizeString += String.format(
	    	 '<button id="shoeSize{0}" class="sizeSwatch" ext:qtitle="Womens Size {0}" ext:qtip="Click to choose Shoe Size." onclick="setSize(this, {0});">{0}</button>',
	    	 i
		);
	}
	pnlSizeSwatch = new Ext.Panel({
    	bodyBorder : true,
    	id: 'sizeSwatch',
    	style: 'padding-left: 90px;',
    	html: sizeString
    });
	pnlAddToCart = new Ext.Panel({
    	frame: false,
    	width: 330,
    	style: 'padding-left: 90px;',
    	html: '<BR><input onclick="submitForm();" type="image" src="https://www.paypal.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">'
    });
    var gemColorString = "";
    for(var i=0;i<gemColorStore.getCount();i++){
		var currentColor = gemColorStore.getAt(i);
		gemColorString += String.format(
			'<img id="imgGemColor{1}" src="{0}" onclick="selectGemColor(this, \'{1}\');" ext:qtitle="{2}" ext:qwidth="140" ext:qtip="Click to choose Gem Color."/>',
			currentColor.data.image,
			currentColor.data.id,
			currentColor.data.name
		);
		if(i == 7){
			gemColorString += "<BR/>";
		}
	}
    pnlGemColor = new Ext.Panel({
    	bodyBorder : true,
    	id: 'gemColorSwatch',
    	style: 'padding-left: 90px;',
    	html: gemColorString
    });
    
    var bd = Ext.getBody();
	largePopup = function(ordinal){
		var currentStyle = styleStore.getAt(ordinal);
		imgPopup = new Ext.Window({
			title: currentStyle.data.name,
			html: String.format(
				'<img onclick="hidePopup()" src="{0}" ext:qtitle="{1}" ext:qtip="Click to close." />',
				currentStyle.data.largeImage,
				currentStyle.data.name
				),
			width: 815,
			height: 615,
			modal: true,
			closable: true
		});	
		imgPopup.show();
	}
	
	for(i=0;i<styleStore.getCount();i++){
		var currentStyle = styleStore.getAt(i);
		var pnl = new Ext.Panel({
			cls: 'productDiv',
			title: currentStyle.data.name,
			style: 'padding: 10px;',
			bodyStyle: 'padding: 10px;background-color:#FBFBff;',
			html: String.format(
				'<img onclick="largePopup({3});" src="{0}" ext:qtitle="{1}" qtip="Click to view detail."/><BR><div class="detail"><span>{1}</span>&nbsp;<span class="price">${2}</span><BR><BR><input type="button" onclick="order({3});" name="order{3}" value="View Options"/></div>',
				currentStyle.data.image,
				currentStyle.data.name,
				currentStyle.data.price,
				i
				),
			width: 300
		});
		pnl.render("product" + i);	
	}
	
    orderForm = new Ext.FormPanel({
        region: 'center',
        labelWidth: 85, // label settings here cascade unless overridden
        url:'https://www.paypal.com/cgi-bin/webscr',
        frame: true,
        border: false,
        width: 330,
        //title: 'GemFlops Order Form',
        defaults: {width: 200},
        bodyStyle:'padding:10px 10px 0;',
        defaultType: 'textfield',
        margins: '0 0 0 0',
        items: [
			new Ext.form.TextField({
				fieldClass: 'x-panel-body',
				style: 'font-weight: bold;font-size: 12px;color: #505050;',
				id: 'txtGemPattern',
				fieldLabel: 'Gem Pattern',
				readOnly: true
			}),
			new Ext.form.TextField({
				fieldClass: 'x-panel-body',
				style: 'font-weight: bold;font-size: 12px;color: #505050;',
				id: 'txtGemColor',
				fieldLabel: 'Gem Color',
				value: 'Blue',
				readOnly: true
			}),
			pnlGemColor,
			/*
        	new Ext.form.ComboBox({
        		store: styleStore,
                fieldLabel: 'Gem Pattern',
                name: 'uid',
                displayField: "name",
                value: 'Daisy Fields',
            }),
            new Ext.form.ComboBox({
            	store: colorStore,
                fieldLabel: 'Flip Flop Color',
                name: 'color',
                displayField: 'name',
                valueField: 'id',
                value: 'Black',
                mode: 'local',
                typeAhead: true,
                triggerAction: 'all'
            }),*/
            new Ext.form.TextField({
				fieldClass: 'x-panel-body',
				style: 'font-weight: bold;font-size: 12px;color: #505050;',
				id: 'txtShoeColor',
				fieldLabel: 'Flip Flop Color',
				value: 'Rose Pink',
				readOnly: true
			}),
            pnlColorSwatch,
            /*
            new Ext.form.ComboBox({
                fieldLabel: 'Shoe Size',
                name: 'uid',
                value: 'Womens 9',
            }),*/
            new Ext.form.TextField({
				fieldClass: 'x-panel-body',
				style: 'font-weight: bold;font-size: 12px;color: #505050;',
				id: 'txtShoeSize',
				fieldLabel: 'Shoe Size',
				value: 'Womens 9',
				readOnly: true
			}),
            pnlSizeSwatch,
            new Ext.form.NumberField({
				//fieldClass: 'x-panel-body',
				//style: 'font-weight: bold;font-size: 12px;color: #505050;',
				id: 'txtQuantity',
				fieldLabel: 'Quantity',
				listeners: {
					valid : function(field){
						//var formatedCurrency = field.getValue() * 15;
						//orderForm.findById('txtPrice').setValue("$" + formatedCurrency + ".00"); 
					}
				},
				value: 1
			}),
			new Ext.form.TextField({
				fieldClass: 'x-panel-body',
				style: 'font-weight: bold;font-size: 12px;color: #303030;',
				id: 'txtPrice',
				fieldLabel: 'Price',
				readOnly: true,
				value: '$15.00'
			}),
            pnlAddToCart
		]
    });        
    pnlMain = new Ext.Panel({
    	region: 'center',
    	bodyBorder: false,
    	//border: false,
    	layout:'card',
		activeItem: 0, 
		tbar: new Ext.Toolbar({
    		items: [
    			{xtype: 'tbspacer'},
    			{
        			cls: 'x-btn-text-icon',
		        	icon: 'images/house.png',
			        text: 'Home',
			        tooltip: {text: 'Click to view gemflops.com home and welcome page', title:'GemFlops Home'},
			        handler: function(){
						pnlMain.getLayout().setActiveItem(0);			        
					}
		        },{
		        	cls: 'x-btn-text-icon',
		        	icon: 'images/products.gif',
			        text: 'Products',
			        tooltip: {text: 'Click to view our complete line of crystal flip flops.', title:'Products'},
			        handler: function(){
			        	pnlMain.getLayout().setActiveItem(1);
			        }
		        },{
		        	cls: 'x-btn-text-icon',
		        	icon: 'images/script.png',
			        text: 'Policies',
			        tooltip: {text: 'View our policies.', title:'Policies'},
			        handler: function(){
			        	pnlMain.getLayout().setActiveItem(2);
			        }
		        },
		        {xtype: 'tbfill'},
		        {
					cls: 'x-btn-text-icon',
		        	icon: 'images/cart.png',
			        text: 'View Shopping Cart',
			        tooltip: {text: 'Click to view your shopping cart\'s contents.', title:'View Shopping Cart'},
			        handler: function(){
						var frmViewCart = document.getElementById("frmViewCart");
						frmViewCart.submit();
			        }
		        },
    			{xtype: 'tbspacer'}
    		]	
    	}),
    	items:[
    		new Ext.Panel({
    			border: false,
    			contentEl: 'welcome',
				bodyStyle: 'padding-left: 50px;overflow-y: scroll;background-color: #F5F5FF;'
    		}),
    		new Ext.Panel({
				layout:'border',
				items:[
	        		styleTree,
		    		new Ext.Panel({
		    			region: 'center',
		    			border: false,
		    			contentEl: 'main',
						bodyStyle: 'overflow-y: scroll;background-color: #F5F5FF;'
		    		})
				]
			}),
    		new Ext.Panel({
    			border: false,
    			contentEl: 'policies',
				bodyStyle: 'padding-left: 50px;overflow-y: scroll;background-color: #F5F5FF;'
    		})
    	]
		/*,
		footer: */
    });
    viewport = new Ext.Viewport({
        layout:'border',
        items:[
            new Ext.Panel({
            	cls: 'topHeader',
            	bodyStyle: 'background-color: #ededff;',
            	bodyBorder: false,
            	border: false,
            	region: 'north',
            	height: 155,
            	html: '<table><tr><td><img src="images/gf_logo.jpg" height="155" border="0" alt="Custom Jeweled Flip flops" title="Custom Jeweled Flip flops" /></td><td valign="top"><div style="z-index:-1;position:relative;padding-top:5px;width: 1600px;height: 135px;overflow:hidden;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="1600" height="140" id="flashheader" align="middle"><param name="wmode" value="transparent"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="flashheader.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#F5F5FF" /><embed src="flashheader.swf" quality="high" bgcolor="#F5F5FF" width="1600" height="140" name="flashheader" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wwmode="transparent"/></object></div></td></tr></table>'
            }),
            pnlMain,
            new Ext.Panel({
	      		region: 'south',
	            bodyBorder: false,
	            border: false,
	            bodyStyle: 'border-bottom: solid 1px #99BBE8;padding-top: 5px;background-color: #F6D9F0;',
	            style: 'font-family:tahoma,verdana,helvetica;font-size:11px;text-align:center;',
	            html: 'Copyright 2008 GemFlops.com',
	            height:24
	        })
         ]
    });
    loader.hide();
});
