Event.observe(window,'load',
	function(){
		var as = document.getElementsByTagName('a')
		for(var i=0; i<as.length;i++){
			as[i].onfocus = function(){ this.blur(); }
		}
		
		var signinInputs = [document.getElementById('password-signin'),document.getElementById('email-signin'),document.getElementById('commentstext')];
		for(var i=0;i<signinInputs.length;i++){
			if(!signinInputs[i]) continue;
			
			signinInputs[i].originalValue = signinInputs[i].value;
			signinInputs[i].onclick = function(){
				if( this.value == this.originalValue ) this.value = "";
			}
			signinInputs[i].onblur = function(){
				if( this.value == "" ) this.value = this.originalValue;
			}
		}
	}
);

window.App = { baseURL : '' };

App.Global = {
	number_format : function( number, decimals, dec_point, thousands_sep ) {
		var n = number, prec = decimals;
	 
		var toFixedFix = function (n,prec) {
			var k = Math.pow(10,prec);
			return (Math.round(n*k)/k).toString();
		};
	 
		n = !isFinite(+n) ? 0 : +n;
		prec = !isFinite(+prec) ? 0 : Math.abs(prec);
		var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
		var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
	 
		var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
	 
		var abs = toFixedFix(Math.abs(n), prec);
		var _, i;
	 
		if (abs >= 1000) {
			_ = abs.split(/\D/);
			i = _[0].length % 3 || 3;
	 
			_[0] = s.slice(0,i + (n < 0)) +
				  _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
			s = _.join(dec);
		} else {
			s = s.replace('.', dec);
		}
	 
		var decPos = s.indexOf(dec);
		if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
			s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
		}
		else if (prec >= 1 && decPos === -1) {
			s += dec+new Array(prec).join(0)+'0';
		}
		return s;
	},
	
	updateCartItemsCount : function(){
		new Ajax.Request(
			App.baseURL + '/store/carts/get_items_count.json',
			{
				onComplete: function(o){
					$('cart-items-count').innerHTML = eval(o.responseText);
				}
			}
		)
	},
	
	toggle: function(e){
		if(e.style.display == 'none')
			e.style.display = '';
		else
			e.style.display = 'none';
			
		return e.style.display == 'none';
			
	}
}

App.InitMenu = function(productName){

	var menu = document.getElementById('prods');
	var items = menu.getElementsByTagName('li');

	for(var i=0;i<items.length;i++){
		var item = items[i];
		var subitems = item.getElementsByTagName('ul');
		
		var tmpA = item.getElementsByTagName('a')[0];
		item.getElementsByTagName('a')[0].onfocus = function(){ this.blur(); }
		
		if(subitems.length){
			subitems[0].style.display = 'none';
			item.getElementsByTagName('a')[0].subitems = subitems[0];
			
			item.getElementsByTagName('a')[0].onclick = function(){
				this.subitems.style.display = (this.open) ? 'none' : '';
				this.open = !this.open
				return false;
			}
			
			var itemName = item.getElementsByTagName('a')[0].innerHTML.toLowerCase().replace(/ /gi,'');
			if(productName.toLowerCase().indexOf(itemName) != -1){
				item.getElementsByTagName('a')[0].onclick();
			}
		}
		
		tmpProductName = item.getElementsByTagName('a')[0].getAttribute('href');
		tmpProductName = tmpProductName.split('/');
		tmpProductName = tmpProductName[tmpProductName.length-1];
		
		var pathName = window.location.pathname.split('/');
		pathName = pathName[pathName.length-1];
		
		if(pathName == tmpProductName){
			var tmpSpan = document.createElement('span');
			tmpSpan.innerHTML = (item.parentNode.id == 'prods') ? '►' : '◄';
			
			if(item.parentNode.id == 'prods')
				tmpA.insertBefore(tmpSpan,tmpA.childNodes[0]);
			else
				tmpA.appendChild(tmpSpan);
		}
	}

	var nav = document.getElementById('nav');
	var navItems = nav.getElementsByTagName('a');

	for(var i=0;i<navItems.length;i++){
		navItems[i].onfocus = function(){
			this.blur();
		};
	}
};

App.InitSponsoring = function(){

	var ranking = document.getElementById('ranking');
	var tt = document.getElementById('tt');
	var type = document.getElementById('type');

	ranking.style.display = 'none';
	tt.style.display = 'none';

	type.Fieldsets = { 'ranking' : ranking, 'tt' : tt};
	type.onchange = function(){
		switch(this.selectedIndex){
			case 0:
				this.Fieldsets.ranking.style.display = 'none';
				this.Fieldsets.tt.style.display = 'none';
			break;
			case 1: case 2:
				this.Fieldsets.ranking.style.display = '';
				this.Fieldsets.tt.style.display = 'none';
			break;
			case 3: case 4:
				var item = this.item(this.selectedIndex);
				this.Fieldsets.tt.getElementsByTagName('legend')[0].innerHTML = (item.innerHTML + ' Information');
				this.Fieldsets.ranking.style.display = 'none';
				this.Fieldsets.tt.style.display = '';
			break;
		}
	}

	type.onchange();

}


App.InitOffers = function(){
	
	var products = $('cont').childNodes;
	for( var i=0; i<products.length;i++){
		var product = products[i];
		if(product.nodeName.toLowerCase() != 'div' ) continue;
		
		var aAdd = product.getElementsByTagName('a')[0];
		product.getElementsByTagName('input')[0].onchange = function(a){
			var href = a.href.split('/');
			href[href.length-1] = this.value
			a.href = href.join('/');
		}.bind(product.getElementsByTagName('input')[0],aAdd)
		product.getElementsByTagName('input')[0].onchange();
		
		aAdd.onclick = function(product){
			var qty = product.getElementsByTagName('input')[0].value;
			if(isNaN(qty) || qty < 1){
				product.getElementsByTagName('span')[1].innerHTML = "Please specify a valid number.";
				if(!document.all){
					product.getElementsByTagName('span')[1].fade({
						duration:4.0,
						from : 1.0,
						to : 0.0,
						afterFinish : function(o){
							o.element.innerHTML = '';
							o.element.show();
						}
						
					});
				}
				return false;
			}
			
			new Ajax.Request(
				this.href + '.json',
				{
					onComplete : function(){
						this.getElementsByTagName('img')[1].style.display = 'none';
						this.getElementsByTagName('div')[0].style.display = '';
						
						this.getElementsByTagName('span')[1].innerHTML = "Added";
						
						if(!document.all){
							this.getElementsByTagName('span')[1].fade({
								duration:4.0,
								from : 1.0,
								to : 0.0,
								afterFinish : function(o){
									o.element.innerHTML = '';
									o.element.show();
								}
								
							});
						}
						
						App.Global.updateCartItemsCount();
						
						return false;
					}.bind(product),
					onLoading : function(){
						this.getElementsByTagName('img')[1].style.display = '';
						this.getElementsByTagName('div')[0].style.display = 'none';
					}.bind(product)
				}
			)
			
			return false;
		}.bind(aAdd,product);
	}
	
}

App.InitCatalog = function(){
	
	var products = $('cont').childNodes;
	for( var i=0; i<products.length;i++){
		var product = products[i];
		if(product.nodeName.toLowerCase() != 'div' ) continue;
		
		var aAdd = product.getElementsByTagName('a')[0];
		product.getElementsByTagName('input')[0].onchange = function(a){
			var href = a.href.split('/');
			href[href.length-1] = this.value
			a.href = href.join('/');
		}.bind(product.getElementsByTagName('input')[0],aAdd)
		product.getElementsByTagName('input')[0].onchange();
		
		product.getElementsByTagName('select')[0].onchange = function(a){
			var href = a.href.split('/');
			href[href.length-2] = this.value
			a.href = href.join('/');
		}.bind(product.getElementsByTagName('select')[0],aAdd)
		product.getElementsByTagName('select')[0].onchange();
		
		aAdd.onclick = function(product){
			var qty = product.getElementsByTagName('input')[0].value;
			if(isNaN(qty) || qty < 1){
				product.getElementsByTagName('span')[1].style.display = '';
				product.getElementsByTagName('span')[1].innerHTML = "Please specify a valid number.";
				if(!document.all){
					this.getElementsByTagName('span')[1].fade({
						duration:4.0,
						from : 1.0,
						to : 0.0,
						afterFinish : function(o){
							o.element.innerHTML = '';
							o.element.show();
						}
						
					});
				}
				return false;
			}
			
			new Ajax.Request(
				this.href + '.json',
				{
					onComplete : function(o){
						this.getElementsByTagName('img')[1].style.display = 'none';
						this.getElementsByTagName('div')[0].style.display = '';
						
						this.getElementsByTagName('span')[1].innerHTML = "Added";
						this.getElementsByTagName('input')[0].value = '';
						
						if(!document.all){
							this.getElementsByTagName('span')[1].fade({
								duration:4.0,
								from : 1.0,
								to : 0.0,
								afterFinish : function(o){
									o.element.innerHTML = '';
									o.element.show();
								}
								
							});
						}
						
						App.Global.updateCartItemsCount();
						
						return false;
					}.bind(product),
					onLoading : function(){
						this.getElementsByTagName('img')[1].style.display = '';
						this.getElementsByTagName('div')[0].style.display = 'none';
					}.bind(product)
				}
			)
			
			return false;
		}.bind(aAdd,product);
	}
}


App.InitCart = function(){
	
	this.updateCartTotal = function(){
		var cartItems = $('cart-list').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
		var cartTotal = 0;
		for(var i=0;i<cartItems.length;i++){
			cartTotal += cartItems[i].getTotal();
		}
		$('cart_total').innerHTML = '$' + App.Global.number_format(cartTotal,2);
	};
	
	this.getCartTotal = function(){
		return $('cart_total').innerHTML;
	};
	
	var qtys = $('cart-list').getElementsByTagName('input');
	var cartItems = $('cart-list').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
	var aDels = document.getElementsByClassName('cart_remove');
	
	for(var i=0;i<aDels.length;i++){
		aDels[i].onclick = function(Cart){
			var tmpId = this.href.split('/'); tmpId = tmpId[tmpId.length-1];
			
			new Ajax.Request(
				this.href + '.json',
				{
					onComplete : function(Cart,tmpId,o){
					
						$('cart-list').getElementsByTagName('tbody')[0].removeChild($('cart_item_' + tmpId));
						
						Cart.updateCartTotal();
						
						if( Cart.getCartTotal() == 0 ){ location.reload(); return; }
						
						App.Global.updateCartItemsCount();
						
					}.bind(this,Cart,tmpId)
				}
			);
			return false;
		}.bind(aDels[i],this)
	}
	
	
	for(var i=0;i<qtys.length;i++){
		var qty = qtys[i];
		
		if(qty.type.toLowerCase() != "text") continue;
		
		qty.onkeyup = function(Cart){
			if(isNaN(this.value) || this.value < 1){ this.value = 1; return; }
			
			this.value = parseInt(this.value);
			
			var id = this.name.match(/[a-z0-9]+/gi)[3];
			$('cart_total_' + id).innerHTML = '$' + App.Global.number_format($('cart_price_' + id).innerHTML.replace('$','') * this.value,2);
			
			new Ajax.Request(
				App.baseURL + '/store/carts/update_quantity/' + id + '/' + this.value + '.json',
				{
					onComplete: function(Cart,o){
						Cart.updateCartTotal();
						this.style.borderColor = "black";
						
					}.bind(this,Cart),
					onLoading : function(){
						this.style.borderColor = "red";	
					}.bind(this,Cart)
				}
				
			);
		}.bind(qty,this)
		
	}
	
	for(var i=0;i<cartItems.length;i++){
		cartItem = cartItems[i];
		cartItem.getTotal = function(){
			return this.getElementsByTagName('input')[0].value * this.getElementsByTagName('td')[2].innerHTML.replace('$','');
		}
	}
}


App.InitCartStep2 = function(cartTotal){
	this.getShippingValue = function(tmpShipping){
		var tmpValue = tmpShipping[tmpShipping.selectedIndex].innerHTML;
		var tmpRegex = /[0-9]+\.[0-9]+/;
		tmpValue = Number(tmpValue.match(tmpRegex)[0]);
		return tmpValue;
	}
	
	this.cartTotal = cartTotal;
	
	var tmpShipping = $('UserShipping');
	tmpShipping.onchange = function(DataScreen){
		tmpValue = DataScreen.getShippingValue(tmpShipping);
		$('cart-total').innerHTML = '$' + App.Global.number_format(tmpValue + DataScreen.cartTotal,2);
	}.bind(tmpShipping,this);
	tmpShipping.onchange();
	
	var tmpDiscount = $('UserDiscountCoupon');
	var aApplyDiscountCode = $('apply-discount');
	aApplyDiscountCode.onclick = function(Cart){
		new Ajax.Request(
			App.baseURL + '/discounts/get_coupon/' + $('UserDiscountCoupon').value + '.json',
			{
				onComplete: function(Cart,o){
					Coupon = eval(o.responseText).Discount;
					if(Coupon){
						
						var totalDiscount = (Boolean(parseInt(Coupon.isAbsolute))) ? Coupon.discount : (Coupon.discount * Cart.cartTotal / 100);
						
						if(totalDiscount){
							this.cartTotal = App.Global.number_format(Cart.cartTotal - totalDiscount + Cart.getShippingValue($('UserShipping')),2);
							$('cart-total').innerHTML = '$' + this.cartTotal;
							$('discount-fieldset').style.display = "none";
							$('cart-total').highlight();
						}
					}
					$('UserDiscountCoupon').style.borderColor = "black";
				}.bind(this,Cart),
				onLoading : function(){
					$('UserDiscountCoupon').style.borderColor = "red";
				}.bind(this,Cart)
			}
			
		);
		
		return false;
	}.bind(aApplyDiscountCode,this);
	
	
}