Ext.BLANK_IMAGE_URL = 'extjs/resources/images/default/s.gif';// reference local blank image
Ext.onReady(function(){
	pageRendered=false;
	try{
		var strat = new Ext.ux.form.Spinner.NumberStrategy({minValue: 0, maxValue: 20 });
		
		var quants = Ext.get('content').child('table.shop-products-table').query('input');
		Ext.each(quants,function(el){
			var quant=Ext.get(el);
			new Ext.ux.form.Spinner({ applyTo:quant.id, strategy: strat, validateOnBlur: false,  vtype:'numeric',
				listeners:{	
					valid: function(field){
						var val=parseInt(field.getValue());
						if (val>20) field.setValue(20); 
						recalculate(el.name, val);
					}
					,spin: function(){loading(true)}
				} // el.name = database product id
			});
		})
		pageRendered=true;
		recalculate();
	}catch(e){}	

	if (!Ext.isIE6) adjustHeight();
})

function loading(show){ 
	if (show){
		Ext.get('myBasketUpdate').setDisplayed(true);
		Ext.get('myBasket').mask('Updating...'); 
		Ext.get('myBasket').next('.order-panel-summary').mask(); 
	} 
	else{
		Ext.get('myBasket').unmask(); 
		Ext.get('myBasket').next('.order-panel-summary').unmask(); 
		Ext.get('myBasketUpdate').setDisplayed(false);
	} 
}

function removeItem(id){
	loading(true);
	Ext.get('basket-box-'+id).fadeOut({ duration:0.2, useDisplay:true, callback: function(){
		try{ 
			Ext.get('input'+id).dom.value='0'; 
			recalculate();
		}catch(e){ // removing from the checkout
			 checkoutRemove(id);
		}
	}});
}

function readValsToObj(){
	var dataObj=new Array();
	var quants = Ext.get('content').child('table.shop-products-table').query('input');
	Ext.each(quants,function(el){
		var name=Ext.get(el).parent('tr').child('.name').dom.innerHTML;
		var price=Ext.get(el).parent('tr').child('.price').dom.innerHTML;
		var sum=parseFloat(price.substr(1))*parseInt(el.value);
		var val=parseInt(el.value);
		if (val>0) dataObj.push({ id:el.name, name: name, price: sum, quantity: val });		
	})
	return dataObj;
}

function recalculate(id,val){
	if (!pageRendered) return;
	loading(true);
	var basket=Ext.get('myBasket');
	var itemTpl = new Ext.Template(
		'<div class="order-panel-item" id="basket-box-{id}"><a href="#" class="remove" title="Remove Item" onclick="removeItem({id});return false;"></a>',
		'<span class="name">{name}</span>',
		'<span class="description"><span class="price">{price}</span>Quantity: {quantity}</span></div>'
	);

	basket.update();
	var totalSum=0, sessionStr=''; // sessionStr="id2:quantity1,id2:quantity2..."; 
	var dataObj=readValsToObj();	
	
	for (var i=0; i<dataObj.length; i++){
		var itemObj=dataObj[i];
		totalSum+=itemObj.price;
		itemObj.price='&euro;'+numberFormat(itemObj.price,2)
		var item = itemTpl.apply(itemObj);
		var newItem=basket.insertHtml('beforeEnd', item, true);
		
		sessionStr+=','+itemObj.id+':'+itemObj.quantity;
	}
	
	if (Ext.get('basket-box-'+id)) Ext.get('basket-box-'+id).highlight();
	
	var totalPrice=basket.next('.order-panel-summary').child('div .price');
	var delivery=basket.next('.order-panel-summary').child('div .delivery-price');
	var total=basket.next('.order-panel-summary').child('.order-panel-summary-total').child('.price');
	
	var delPr=deliveryPrice(totalSum);
	
	totalPrice.update('&euro;'+numberFormat(totalSum,2));
	delivery.update('&euro;'+numberFormat(delPr,2));
	total.update('&euro;'+numberFormat(totalSum+delPr,2));
	
	if (totalSum>0){
		basket.next('.order-panel-summary').setDisplayed(true);
		basket.next('.btn-checkout').setDisplayed(true);
		basket.prev('h4').setDisplayed(false);
	} 
	else {
		basket.next('.order-panel-summary').setDisplayed(false);
		basket.next('.btn-checkout').setDisplayed(false);
		basket.prev('h4').setDisplayed(true);
	}
	
	Ext.Ajax.request({ url:'requests/shop.php', params: { action: 'update', basket: sessionStr.substr(1) },
		callback: function(o,s,r){ loading(false) }
	})
}



function checkoutRemove(id){
	loading(true)
	Ext.Ajax.request({ url:'requests/shop.php', params: { action: 'remove', id: id },
		callback: function(o,s,r){
			var totalSum=parseFloat(r.responseText);
			var basket=Ext.get('myBasket');
		 	var totalPrice=basket.next('.order-panel-summary').child('div .price');
			var total=basket.next('.order-panel-summary').child('.order-panel-summary-total').child('.price');
			var delivery=basket.next('.order-panel-summary').child('div .delivery-price');
			
			var delPr=deliveryPrice(totalSum);
			
			totalPrice.update('&euro;'+numberFormat(totalSum,2));
			delivery.update('&euro;'+numberFormat(delPr,2));
			total.update('&euro;'+numberFormat(totalSum+delPr,2));
			loading(false)
			
			if (!totalSum) {
				basket.prev('h4').setDisplayed(true);
				basket.next('.order-panel-summary').setDisplayed(false);
				Ext.Msg.show({ title:'Alert', msg: 'Your Basket is empty. Click OK to go back to the shop.',
					animEl: 'myBasket', buttons: Ext.Msg.OK, icon: Ext.MessageBox.INFO,
				   fn: function(){ location.href="http://www.wellwomancentre.ie/index.php?p=shop" }
				});
			}	
		}
	})
}



function deliveryPrice(price){
	if (price>1 && price<=50) return 3;
	else if (price>50 && price<=100) return 6;
	else if (price>100 && price<=200) return 10;
	else if (price>200 && price<=500) return 25;
	else if (price>500) return 50;
	return 0;
}



// some fx + firebug error fix
Ext.lib.Event.resolveTextNode = Ext.isGecko ? function(node){
if(!node) return; var s = HTMLElement.prototype.toString.call(node);
if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') return;
return node.nodeType == 3 ? node.parentNode : node;
}:function(node){return node && node.nodeType==3?node.parentNode:node;};
