var CartManager = Class.create({

	parent_products:'products'
	,parent_boxes:'addresses'
	,parent_boxes2:'pickups'
	,newaddress_form:'newaddress_form'
	,products:null  // typeOf=Product
	//,giftboxes:null // typeOf=GiftBox
	,boxes:null // typeOf=Address
	,notifications_area:'notifications_area'
	,allow_giftables:false
	,cartid:0
	,boxtype:0

	,initialize: function(parent_products,parent_boxes) {
		if(parent_products)
			this.parent_products = parent_products;
		if(parent_boxes)
			this.parent_boxes = parent_boxes;

		this.products = new Array();
		this.boxes = new Array();
		//this.giftboxes = new Array();
	}


	,addressExists: function(addressid){
		var found=0;
		for(var i=0;i<this.boxes.length;i++)
			if(this.boxes[i].id == addressid)
				found=1;
		return found;
	}

	,checkCartValidity: function(){
		var ret = true;
		for(var i=0;i<this.products.length;i++){
			if(this.products[i].conditiaDeDragabil())
				if(this.products[i].count_available>0)
					ret = false;
		}

		//console.log("CART VALIDITY = "+(ret===true?"VALID":"INVALID"));
		return ret;
	}

	,anythingHappens: function(){
		valid = this.checkCartValidity();
		if(valid){
			$(this.notifications_area).update('Vos produits sont attribués. Vous pouvez passer à l\'étape suivante');
			$(this.notifications_area).show();
			if(alert_was_displayed<=0){
				alert('Vos produits sont attribués. Vous pouvez passer à l\'étape suivante');
				alert_was_displayed++;
			}
		}else{
			alert_was_displayed=0;
			$(this.notifications_area).setStyle('color:orange;');
			$(this.notifications_area).update(
				'<script type="text/javascript">'
				+'	swfobject.registerObject("myId", "7.0.0", "img/etape2_fleche.swf");'
				+'</script>'
				+'<object id="myId" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="444" height="70">'
				+'<param name="movie" value="img/etape2_fleche.swf" />'
        		+'<!--[if !IE]>-->'
				+'<object type="application/x-shockwave-flash" data="img/etape2_fleche.swf" width="444" height="70">'
				+'<!--<![endif]-->'
				+'<div>'
				+'	<img src="img/etape2_fleche.png" style="margin-left:-10px;">'
				+'</div>'
				+'<!--[if !IE]>-->'
				+'</object>'
				+'<!--<![endif]-->'
			+'</object>');
		}
	}

	,addProduct: function(product){
		product.parent_element = this.parent_products;
		product.manager=this;
		this.products.push(product);
	}


	,addBox: function(box){
		box.parent_element = (box.id>=1000 || this.boxtype==2) ? this.parent_boxes : this.parent_boxes2;
		box.manager = this;
		this.boxes.push(box);
	}



	,Render: function(){
		var i=0;
		//console.log("Rendering manager...");
		for(i=0;i<this.products.length;i++){
			this.products[i].Render();
		}

		//console.log("Boxes: #"+this.boxes.length);
		for(i=0;i<this.boxes.length;i++){
			this.boxes[i].Render();
		}

		if(this.boxtype==1){
			/*
			--not the case anymore. This is used only for addresses , as pickup places are static
			var final_warning_div = new Element('div',{}).update('Please use only one shipping depot!<br>You will not be able to finish your order otherwise!');
			final_warning_div.setStyle({'float':'left','color':'red','fontWeight':'800'});
			//alert(this.parent_boxes2);
			$(this.parent_boxes2).appendChild(final_warning_div);
			*/
		}
	}

	/**
	*	Returns a product by its id
	*	INPUT: productid(int) = the ID of the product
	*	RETURN: product(Product)/false(BOOL) = the product of the search, or false if none found
	*/
	,getProduct: function(productid){
		for(var i=0;i<this.products.length;i++)
			if(this.products[i].id==productid)
				return this.products[i];
		return false;
	}


	/**
	*	Returns a box by its id
	*	INPUT: boxid(int) = the ID of the box
	*	INPUT: boxtype(int) = the TYPE of the box (1=address / 2=giftbox)
	*	RETURN: box(Address or giftbox)/false(BOOL) = the box of the search, or false if none found
	*/
	,getBox: function(boxid,boxtype){
		for(var i=0;i<this.boxes.length;i++)
			if(this.boxes[i].id==boxid && this.boxes[i].type==boxtype)
				return this.boxes[i];
		return false;
	}


	,assignThingToAddressInitially: function(boxid,productid,childboxid,quantity){
		//console.log('ATTAI: boxid(address)='+boxid+', productid='+productid+' ,childboxid='+childboxid+', quantity='+quantity+' END');
		for(var i=0;i<this.boxes.length;i++){
			if(this.boxes[i].id==boxid){
				var true_productid = productid>0 ? productid : childboxid;
				this.boxes[i].addProduct(true_productid,quantity);
			}
		}
	}

	,assignProductToBoxInitially: function(productid,boxid,boxtype,quantity){
		for(var i=0;i<this.boxes.length;i++)
			if(this.boxes[i].id==boxid && this.boxes[i].type==boxtype)
				this.boxes[i].addProduct(productid,quantity);
	}

	,assignProductToBox: function(productid,boxid,boxtype){
		for(var i=0;i<this.boxes.length;i++)
			if(this.boxes[i].id==boxid && this.boxes[i].type==boxtype)
				this.boxes[i].addProduct(productid,1);
	}

	,unlinkProductFromBox: function(productid,boxid,boxtype){
		//console.log("Product #"+productid +" removed from box #"+ boxid);
		for(var i=0;i<this.boxes.length;i++)
			if(this.boxes[i].id==boxid && this.boxes[i].type==boxtype)
				this.boxes[i].unlinkProduct(productid);
	}


	,getProductUsage: function(productid){
		usage=0;
		for(var i=0;i<this.boxes.length;i++){
			for(var j=0;j<this.boxes[i].products.length;j++){
				if(this.boxes[i].products[j].productid==productid){
					usage += this.boxes[i].products[j].quantity;
					//console.log("Gasit in adresa "+this.boxes[i].city+" in numar de "+this.boxes[i].products[j].quantity)
				}
			}
		}
		return usage;
	}

	,getProductRemaining: function(productid){
		product = this.getProduct(productid);
		var usage = this.getProductUsage(productid);
		var remaining = product.count_total - usage;
		//console.log("Product #"+productid+' , qty='+product.count_total+' , usage='+usage+' remaining='+remaining)
		return remaining;
	}

	,createNewBox: function(city,zip,address1,address2,addressid,boxname){
//		var city = $(this.newaddress_form).elements['rec_city'].value;
//		var zip = $(this.newaddress_form).elements['rec_zip'].value;
//		var addressid = $(this.newaddress_form).elements['rec_addressid'].value;
//		var address1 = $(this.newaddress_form).elements['rec_address1'].value;
//		var address2 = $(this.newaddress_form).elements['rec_address2'].value;
		var url = 'index.php?object=cart&method=NewAddress&city='+city+'&zip='+zip+'&address1='+address1+'&address2='+address2+'&addressid='+addressid+'&boxname='+boxname+'&boxtype='+this.boxtype+'&cartid='+this.cartid;
		var self = this;
		new Ajax.Request(url, {
			method: 'post',
			onSuccess: this.createNewBoxExecute.bindAsEventListener(this)
		});
		$('div_'+this.newaddress_form).hide();
		$('toggler_'+this.newaddress_form).show();
	}

	,createNewBoxExecute: function(transport){
		var response = eval('('+transport.responseText+')');
		var id = response.id;
		//console.log("thenewid="+id);
		if(parseInt(id)>0){
			//console.log(response);
			var box = new Box(id,response.city,response.zip,response.address1,response.address2,response.addressid,response.boxname,response.boxtype);
			this.addBox(box);
			this.boxes[this.boxes.length-1].Render();
			//console.log('unu4');
			//console.log('creeam box-ul');
		}else{
			switch(parseInt(id)){
				case 0:	alert("Erreur: Vous n\'êtes plus logué. L\'adresse n\'a pas été ajoutée.");			break;
				case -1:alert("Erreur: La ville n\'est pas spécifiée. L\'adresse n\'a pas été ajoutée.");	break;
				case -2:alert("Erreur: Le code postal n\'est pas spécifiée. L\'adresse n\'a pas été ajoutée.");break;
				case -3:alert("Erreur: L\'adresse n\'est pas spécifiée. L\'adresse n\'a pas été ajoutée.");break;
			}
		}
		//window.parent.reziseIframe('iframe2',document.viewport.getHeight());
	}

	,enablePlusButtons: function(productid,isgiftbox){
		for(var i=0;i<this.boxes.length;i++){
			this.boxes[i].enablePlusButton(productid,isgiftbox);
		}
	}

	,disablePlusButtons: function(productid,isgiftbox){
		for(var i=0;i<this.boxes.length;i++){
			this.boxes[i].disablePlusButton(productid,isgiftbox);
		}
	}

});// CartManager


// o folosim la asignarea produselor atat in adrese, cat si in giftbox-es (unde addressid va pointa defapt catre giftboxid
var ProductInBox = Class.create({
	productid:0
	,boxid:0 // pointeaza catre address.id sau giftbox.id
	,boxtype:0
	,quantity:0
	,parent_element:null
	,manager:null
	,box:null // contine referinta la adresa / giftbox
	,product:null
	,mainid:''
	,initialize: function(productid,boxid,boxtype,quantity) {
		this.productid=productid;
		this.boxid=boxid;
		this.boxtype=boxtype;
		this.quantity=quantity;
		this.mainid = 'productinbox_'+this.productid+'_'+this.boxid;
		//console.log("ASSIGN PRODUCT "+this.productid+' TO ADDRESS '+this.addressid);
	}

	,Render: function(){
		var temp = this.manager.getProduct(this.productid);
		//console.log("rendering on parent "+this.parent_element);
		var div_mare = new Element('div',{'id':this.mainid});
		div_mare.setStyle("width:343px;float:left;");
		var e1 = new Element('div',{'id':'count_'+this.mainid}).update(this.quantity);
		e1.setStyle("font-size:18px;font-weight:800;float:left;margin-top:-1px;");
		var e2 = new Element('img',{'id':'plusbutton_'+this.mainid,'src':'img/plus.gif','hspace':'0'});
		e2.setStyle("position:relative;float:left;cursor:pointer;");
		var e3 = new Element('img',{'id':'minusbutton_'+this.mainid,'src':'img/minus.gif','hspace':'0'});
		e3.setStyle("position:relative;float:left;cursor:pointer;");
		var imgs = temp.isgift>0 ? "<img src='img/gift.gif' border='0' style='float:left;padding-right:5px;'>" : "";
		var div1 = new Element('div');
		var div2 = new Element('div',{'id':'caption_'+this.mainid}).update(imgs + temp.name);
		div2.setStyle("padding-top:2px;font-size:11px;");

		div1.appendChild(e1);
		div1.appendChild(e2);
		div1.appendChild(e3);
		div_mare.appendChild(div1);
		div_mare.appendChild(div2);

		e2.observe('click',this.plusQuantity.bindAsEventListener(this));
		e3.observe('click',this.minusQuantity.bindAsEventListener(this));

		this.box.updateEmptyText();

		$(this.parent_element).appendChild(div_mare);
		this.manager.anythingHappens();
	}



	,enablePlusButton: function(isgiftbox){
		//console.log('IGBpib='+isgiftbox);
		if(this.product.isgiftbox == isgiftbox)
			$('plusbutton_'+this.mainid).src = 'img/plus.gif';
	}

	,disablePlusButton: function(isgiftbox){
		//console.log('IGBpib='+isgiftbox);
		if(this.product.isgiftbox == isgiftbox)
			$('plusbutton_'+this.mainid).src = 'img/plus_disabled2.gif';
	}

	,unRender:function(){
		$(this.parent_element).removeChild($(this.mainid));
		this.manager.anythingHappens();
	}

	,UpdateRender: function(){
		$('count_'+this.mainid).update(this.quantity);
		this.manager.anythingHappens();
	}

	,plusQuantity: function(dont_update_db){
		//console.log(dont_update_db);
		this.modifyQuantity(1,dont_update_db);
	}

	,minusQuantity: function(){
		this.modifyQuantity(-1);
	}

	,modifyQuantity: function(quantity,dont_update_db){
		if(dont_update_db=='undefined' || dont_update_db <=0)
			dont_update_db=0;
		//console.log("remaining:"+this.manager.getProductRemaining(this.productid));
		new_quantity = this.quantity + quantity;
		new_next_quantity = this.quantity + quantity + 1;
		available = this.manager.getProductRemaining(this.productid);
		//console.log('New Quantity would be: '+new_quantity+ ' , available='+available);
		if(new_quantity<=0){

			this.manager.unlinkProductFromBox(this.productid,this.boxid,this.boxtype);
			this.modifyMainQuantityOnProduct(dont_update_db);
		}else if(available<=0 && quantity>0){
			alert("Vous n\'avez plus de produit disponible dans votre panier!");
		}else{

			this.quantity = new_quantity;
			this.UpdateRender();
			this.modifyMainQuantityOnProduct(dont_update_db);
		}

		box = manager.getBox(this.boxid,this.boxtype);
		box.updateEmptyText();
		this.manager.anythingHappens();
	}

	/**
	* Intotdeauna se pleca de la zero. Nu exista alte posibilitati
	* intrucat aceasta functie se apeleaza o singura data, la randarea initialapaginii
	*/
	,updateBoxQuantityFromDB: function(quantity){
		for(var i=0;i<quantity;i++)
			this.plusQuantity(1);
	}

	,updateBoxQuantityInDB : function(quantity){
		//console.log(this.manager.boxtype);
		if(this.manager.boxtype==1){
			var url = 'index.php?object=cart&method=UpdateAddressQuantity&addressid='+this.boxid+'&quantity='+quantity;
			if(this.product.isgiftbox<=0)
				url += '&productid='+this.productid;
			else
				url += '&childboxid='+this.productid;
		}else{
			var url = 'index.php?object=cart&method=UpdateBoxQuantity&productid='+this.productid+'&boxid='+this.boxid+'&quantity='+quantity;
		}
		new Ajax.Request(url, {
			method: 'post',
			onSuccess: this.updateBoxQuantityInDBExecute.bindAsEventListener(this)
		});
	}

	,updateBoxQuantityInDBExecute : function(transport){
		var new_quantity = transport.responseText;
		if(new_quantity>=0){

		}
		this.box.updateShippingCost();
	}


	,modifyMainQuantityOnProduct: function(dont_update_db){
		if(dont_update_db=='undefined' || dont_update_db <=0)
			dont_update_db=0;
		if(dont_update_db!='1') // acest if nu functioneaza?
			this.updateBoxQuantityInDB(this.quantity);
		quantity = this.manager.getProductRemaining(this.productid);
		temp = this.manager.getProduct(this.productid);
		if(temp!=false){
			temp.count_available = quantity;
			temp.UpdateRender();
		}
		this.box.updateShippingCost();
	}

	,dispose: function(){
		this.quantity = 0;
		//console.log('destroyer...');
		this.updateBoxQuantityInDB(0);
	}

});

