__Cart = function(){
	this.container = $_('#OSCCart');
	this.URLGetCartHTML = SmartCheckout.APIURL+'?ax=1&function=get_cart';
	this.URLUpdateCart = SmartCheckout.APIURL+'?ax=1&function=update_cart&action=update';
	this.updateControl = $_('#OSCCartUpdateControl');
	
	this.changed = false;	// If cart changed - set flag
	this.focused = true;
	
	this.currentChecksum = this.getCartChecksum();
	this.changesHandle();
}

__Cart.prototype.getCartContents = function(cbf){
	var self = this;
	this.container.loadingBig(1);
	$_(this.URLGetCartHTML).GET(function(data){
		if(data.stderr.errOccured){
			switch(data.stderr.errCode){
				case "err_checkout_not_allowed_msg":
					window.location.href = 'error_message.php?error_min_order';
				break;
				case "NO_PRODUCTS":
					window.location.reload();
					return;
				break;
			}
			return false;
		}
		
		
		if(!data || !data.stdout || !data.stdout.length)
			window.location.reload();
		else{
			self.container.innerHTML = data.stdout;	
			if($_('#OSCCart').$_('~input').empty()){	// E.g. all shippable products are removed
				ShippingMethod.hide();
			}
			self.changesHandle();
		}if(cbf)
			cbf()	
	})
}

__Cart.prototype.updateCart = function(cbf){
	var self = this;
	var inputs = this.container.$_('~input');
	this.container.loadingBig(1);
	if(inputs && (inputs.length || inputs.tagName)){
		$_(this.URLUpdateCart).POST(inputs.encode2URI(), function(){
			self.getCartContents(cbf);
			Totals.getContents();
		})
	}
}

__Cart.prototype.changesHandle = function(){

	var self = this;
	var inputs = $_('#OSCCart').$_('~input');
	if(!inputs.empty()){
		// If element lost focus and no other element from form catched focus, update cart to server
		inputs.attach('blur', function(){	
			self.focused = false;
			setTimeout(function(){
				if(self.currentChecksum != self.getCartChecksum() && !self.focused){
					self.updateCart(function(){
						self.currentChecksum = self.getCartChecksum();
					});
				}
			}, 1000)
		})
		
		inputs.attach('keypress', function(e){	
			if(e.keyCode != 13) return true;
			self.focused = false;
			setTimeout(function(){
				if(self.currentChecksum != self.getCartChecksum() && !self.focused){
					self.updateCart(function(){
						self.currentChecksum = self.getCartChecksum();
					});
				}
			}, 1000)
		})		
		
		
		inputs.attach('focus', function(){
			self.focused = true;
		});
	}else 				// No inputs found
		return false
}

__Cart.prototype.getCartChecksum = function(){
	var inputs = $_('#OSCCart').$_('~input');
	if(!inputs.empty()){
		return inputs.CRC32();
	}else
		return 0;// No inputs found
}


