// JavaScript Document
// Copyright (c) 2001 - Abdoulaye Siby - admin@abdoulaye.com
/*
Codes pour la gestion du shopping cart à partir.
Ce code utilise les fonctions de manipulations  de cookies se trouvant dans le fichier cookies.js
*/

function Array_toSource(){
	//alert(1);
	//return "{code : 1, name: 'test', quantity: 2}";
	/*temp = new Array();
	//for(_item in this){
	for(i = 0; i < _items.length; i++){
		if(_items[i].code == code){
			temp[i] = {code: code, name: _items[i].name, quantity: _items[i].quantity};
		}
	} 
	*/
	/*
	for(_item = 0; _item < _items.length; _item++){
		if(typeof(this[_item]) == 'function') continue;
		alert("_item --> " + _item + '::' + this[_item]+'<<'+typeof(this[_item]));
		if(typeof(this[_item])=="object"){
			temp[_item] = this[_item].toSource();
		} else //if((typeof(this[_item])=="number") || (typeof(this[_item])=="string")){ 
			temp[_item] = _item + ':' + this[_item];
		//}
	}*/
	
	//return temp.join(', ');
}
if(typeof Array.prototype.toSource == "undefined"){
	//Array.prototype.toSource = Array_toSource;
}

function Cart(new_name, new_days){
	//Declaring public functions
	this.addProduct = _addProduct;
	this.getProduct = _getProduct;
	this.checkProduct = _checkProduct;
	this.getAllProducts = _getAllProducts;
	this.removeProduct = _removeProduct;
	this.emptyCart = _emptyCart;
	this.getTarget = _getTarget;
	this.setTarget = _setTarget;
	this.setImages = _setImages;
	this.updateTarget = _updateTarget;
	this.getCount = _getCount;
	this.checkout = _checkout;
	this.changeQuantity = _changeQuantity;
	//this.getCart = _getCart;
	//this.storeCart = _storeCart;
	//this.delCart = _delCart;
	//Declaring private variables
	var _name = "shoppingcart";
	var _days = 0.48;
	var _auto_update = true;
	var _items = new Array();
	var _images = new Array();
	var _target = "";
	var _cart_image_empty = "";
	var _cart_image_full = "";

	if(new_name) {
		_name = new_name;
	}
	if(new_days) {
		_days = _days;
	}
	
	//If a cookies containing a previous existing compatible shopping cart, load it here
	_getCart();
	
	function _addProduct(code, new_name, new_price, new_quantity, new_lang){
		//Add a product into the shopping cart. If the same product code is already in the cart, just update the given product. The quantity will be added (Old Quantity+NewQuantity)
		//This ensure that the product code stays unique in the shopping cart.
        if(new_quantity == 0){
            return _items.length;
        }
		index = _items.length;
		found = false;
		total_quantity = parseInt(new_quantity);
		for(i = 0; i < _items.length; i++){
			if(_items[i].code == code){
				index = i;
				found = true;
			}
		}
		if(found == true){
			total_quantity += parseInt(_items[index].quantity);
		}
		_items[index] = {code: code, name: new_name, price: new_price, quantity: total_quantity, lang: new_lang};
		_storeCart();
		if (_auto_update) {
			_updateTarget();
		}
		return _items.length;
	}
	
	function _getProduct(code){
		//Add a product into the shopping cart. If the same product code is already in the cart, just update the given product.
		//This ensure that the product code stays unique in the shopping cart.
		for(i = 0; i < _items.length; i++){
			if(_items[i].code == code){
				return {code: code, name: _items[i].name, price: _items[i].price, quantity: _items[i].quantity, lang: _items[i].lang};
			}
		}
		return null;
	}
	
	function _checkProduct(code){
		//Add a product into the shopping cart. If the same product code is already in the cart, just update the given product.
		//This ensure that the product code stays unique in the shopping cart.
		for(i = 0; i < _items.length; i++){
			if(_items[i].code == code){
				return true;
			}
		}
		return false;
	}
	
	function _getAllProducts(){
		//Add a product into the shopping cart. If the same product code is already in the cart, just update the given product.
		//This ensure that the product code stays unique in the shopping cart.
		var temp = new Array();
		for(i = 0; i < _items.length; i++){
			temp[i] = {code: _items[i].code, name: _items[i].name, price: _items[i].price, quantity: _items[i].quantity, lang: _items[i].lang};
		}
		return temp;
	}
	
	function _removeProduct(code){
		//Remove a product from the shopping cart
		for(i = 0; i < _items.length; i++){
			if(_items[i].code == code){
				delete _items[i];
			}
		}
		var j=0;
		var _new_items = new Array()
		for(i = 0; i < _items.length; i++){
			//alert(_items[i]);
			if(_items[i]){
				_new_items[j]=_items[i];
				j++;
			}
		}
		delete _items;
		_items = _new_items;
		delete _new_items;
		_storeCart();
		if (_auto_update) {
			_updateTarget();
		}
	}
	
	function _emptyCart(){
		//Empty the current shopping cart
		_items = new Array();
		_storeCart()
		if (_auto_update) {
			_updateTarget();
		}
	}
	
	//Récupére un cookie
	function _getCart(){
		if (document.cookie.length > 0){		//Y a-t-il des cookies?
			debut = document.cookie.indexOf(_name+"=");
			if (debut != -1) {
				debut += _name.length+1;
				fin = document.cookie.indexOf(";", debut);
				if (fin == -1) fin = document.cookie.length;
					try{
						if(typeof Array.prototype.toSource == "undefined"){
							_items = eval(unescape(unescape(document.cookie.substring(debut, fin))));
							//alert(_items);
						} else {
							_items = eval(unescape(document.cookie.substring(debut, fin)));		//Retourner la valeur du cookie
						}
					} catch(e){
						_emptyCart();
					}
				//alert(_items);
				if(typeof(_items) == "undefined"){
					_items = new Array();
				}
			}
		}
	}
		
	function _getCount(){
		return _items.length;
	}
		
		//Crée un cookie en fixant le nombre de jours avant que le cookie ne s'expire
	function _storeCart(){
		//alert(_items.length);
		//cookie_value = _items.toString();
		if(typeof Array.prototype.toSource == "undefined"){
			cookie_value = _toSource(_items);
		} else {
			cookie_value = _items.toSource();
		}
		var date_expiration = new Date ();
		date_expiration.setTime(date_expiration.getTime() + (_days * 24 * 3600 * 1000));
		document.cookie = _name + "=" + escape(cookie_value) + ((_days == null) ? "" : "; expires=" + date_expiration.toGMTString());
	}
	
	//Supprime un cookie
	function _delCart ()
	{
		if (getCookie(_name)) {
			document.cookie = _name + "=" +"; expires=Thu, 01-Jan-70 00:00:01 GMT";  //En mettant la date du cookie au 1er janvier 1970, il sera certainement expiré.
		}
		if (_auto_update) {
			_updateTarget();
		}
	}
	
	function _setTarget(newTarget)
	{
		if(newTarget){
			_target = newTarget
		}
	}
	
	function _getTarget()
	{
		return _target;
	}

	function _setImages(){
		if(!arguments.length)
			return;
		for(var i=0; i<arguments.length; i++)
			_images[i] = arguments[i];
	}

	function _updateTarget()
	{
		var targetNode = document.getElementById(_target);
		if(!targetNode) return false;
		while(targetNode.hasChildNodes()){
			targetNode.removeChild(targetNode.firstChild);
		}
		imgElement = document.createElement("img");
		imgElement.setAttribute("id", "cart_image");
		if(!_items || !_items.length) {
			imgElement.setAttribute("src", _images[0]);
			output = _items.length + ' ' + _PRODUCT;
		} else {
			imgElement.setAttribute("src", _images[( (_items.length + 1) > _images.length)?(_images.length - 1):_items.length]);
			output = "" + _items.length + ' ' + _PRODUCT + ((_items.length > 1) ? "s" : "" );
		}
		with(targetNode){
			appendChild(imgElement);
			appendChild(document.createElement("br"));
			appendChild(document.createTextNode(output));
		}
		return true;
	}
	
	function _checkout(){
		if(_items.length){
			output = "A request will be sent for :\n";
			for(i = 0; i < _items.length; i++){
				output = output + " - " + _items[i].name + " ( code :" + _items[i].code + " )\n";
			}
		} else {
			output = "The Request Cart in empty.";
		}
		alert(output);
	}

	function _changeQuantity(code, new_quantity){
		//Change the quantity of a specific product stored in the shoppingCart
        if(new_quantity == 0){
            return null;
        }
		index = null;
		found = false;
		total_quantity = parseInt(new_quantity);
		for(i = 0; i < _items.length; i++){
			if(_items[i].code == code){
				index = i;
				found = true;
			}
		}
		if(found == true){
			total_quantity += parseInt(_items[index].quantity);
            _items[index].quantity = total_quantity;
            _storeCart();
            if (_auto_update) {
                _updateTarget();
            }
            if(total_quantity <= 0){
                _removeProduct(code)
            }
            return total_quantity;
		} else {
            return null;
        }
	}
	
	function _toSource(_array){
		var temp = new Array();
		for(i = 0; i < _array.length; i++){
			temp[i] = "{code: '" + _items[i].code + "', name: '" + _items[i].name + "', price: '" + _items[i].price + "', quantity: '" + _items[i].quantity + "', lang: '" + _items[i].lang + "'}";
		}
		//alert("[" + temp.join(",") + "]");
		return ("[" + temp.join(",") + "]");
	}
}

