var Box = Class.create({

	id:0
	,city:''
	,zip:''
	,address1:''
	,address2:''
	,schedule:''
	,addressid:0
	,hasmessage:false /* repurpose: is the same as user_addresses.is_giftbox */
	,message:''
	,boxname:''
	,products:null// typeOf=ProductInBox
	,parent_element:'addresses'
	,manager:null
	,did:''
	,type:1
	,empty_text:'Glissez les produits que vous souhaitez livrer à cette adresse'
	,empty_text_pickup:'Glissez vos produits que vous souhaitez voir déposer dans ce dépôt'
	,eth1:"<font style='color:#ccc;font-size:11px;'>"
	,eth2:"</font>"
	,delivery_price_text1 : "Frais de ports: CHF "
	,delivery_price_text2 : ""
	,iam:'abox'
	,hasmap:0
	,warehousename:''

	,initialize: function(id,city,zip,address1,address2,addressid,boxname,type,hasmessage,message,schedule,hasmap,warehousename) {
		this.id = id;
		this.city = city;
		this.zip = zip;
		this.address1 = address1;
		this.address2 = address2;
		this.addressid = addressid;
		this.boxname = boxname;
		this.products = new Array();
		this.warehousename = warehousename;
		if(type)
			this.type=type;
		if(schedule)
			this.schedule=schedule;
		if(hasmap)
			this.hasmap=hasmap;

		this.hasmessage = hasmessage;
		this.message = message;

		this.did = "dropable_box_" + this.id + '_' + this.type;

	}




	,addProduct: function(productid,quantity){
		//console.log("Adding productid="+productid+" in quantity="+quantity+" in me (id="+this.id+")");
		var productinbox = new ProductInBox(productid,this.id,this.type,quantity);
		productinbox.parent_element = 'contents_'+this.did;
		productinbox.manager = this.manager;
		productinbox.box = this;
		//console.log('aaaaaaaaaaaaaa');
		productinbox.product = manager.getProduct(productid);
		//console.log('bbbbbbbbbbbbbb');
		this.products.push(productinbox);
		//console.log('cccccccccccccc');
		this.products[this.products.length-1].Render();
		//console.log('dddddddddddddd');
		this.products[this.products.length-1].modifyMainQuantityOnProduct();
		//console.log('anythinghappends...');
		this.manager.anythingHappens();
	}

	,unlinkProduct: function(productid){
		for(i=0;i<this.products.length;i++)
			if(this.products[i].productid==productid){
				this.products[i].dispose();
				this.products[i].unRender();
				this.products.splice(i,1);
				this.manager.anythingHappens();
				return true;
			}
		this.manager.anythingHappens();
		return false;
	}

	,Render: function(){
		//console.log("Rendering box #"+this.id+" in target: "+this.parent_element);
		var w = BrowserDetect.browser=='Explorer' ? '375px':'340px';
		//alert(BrowserDetect.browser);
		w2 = '100%';
		if(this.id<1000)
			this.empty_text = this.empty_text_pickup;

		var div_mare = new Element('div',{'id':this.did,'style':'float:right;width:'+w+';padding:10px;padding-right:3px;border:2px solid #D52266;margin-bottom:10px;'});

		if(this.type==1){
			// address

			var address = '';
			if(this.id<1000){
				// depot
				address += '<b>' + this.warehousename + '</b> - '
			}
			//console.log('utf8_encode1');
			address += (this.address1.trim()!='' ? ('<br>' + this.address1):'') + (this.address2.trim()!='' ? ('<br>' + this.address2):'') + (this.zip.trim()!='' ? ('<br>' + this.zip):'') + (this.city.trim()!='' ? ('<br>' + this.city):'');
			//console.log('utf8_encode2');
			if(this.schedule!=''){
				address += '<br><font style="font-size:11px;color:#777;">Horaire: ' + this.schedule + '</font><br>';
			}
			//console.log('utf8_encode3');
			var div1 = new Element('div',{'id':'actualaddress_'+this.did,'style':'float:left;font-size:12px;'}).update(address);
			//console.log('utf8_encode4');
		}else{
			// giftbox
			this.empty_text = 'Glissez les produits ici pour les ajouter à ce cadeau';
			var div1 = new Element('div',{'id':'actualaddress_'+this.did,'style':'float:left;font-size:12px;'}).update('');
			var caption = new Element("B",{'id':'bolded_'+this.did}).update(this.boxname);
			caption.setStyle('position:relative;float:left;width:'+(w2)+';');
			div1.appendChild(caption);
		}
		//console.log('dsds');


		var div2 = new Element('div',{'id':'contents_'+this.did,'style':'float:left;width:100%;border-top:1px solid #eee;padding-top:3px;'}).update();
		var div_empty = new Element('div',{'id':'emptytext_'+this.did,'style':'float:left;font-size:12px;'}).update(this.eth1+this.empty_text+this.eth2);

		//-gift
		var div3 = new Element('div',{'id':'isgift_div_'+this.did,'style':'position:relative;float:left;border:0px solid red;width:100%;' + (this.manager.allow_giftables?"":"display:none;")});
		var checkbox = new Element("input",{'id':'isgift_checkbox_'+this.did,'type':'checkbox'});
		checkbox.checked = this.hasmessage;

		checkbox.setStyle("position:relative;float:left;");
		checkbox.observe('click',this.onGiftClick.bindAsEventListener(this));
		var label = new Element('label',{'for':'isgift_checkbox_'+this.did}).update("Ecrire un message");
		label.setStyle('position:relative;float:left;margin-top:2px;');

		var div3message = new Element('div',{'id':'isgift_div_message_'+this.did,'style':'display:'+(this.hasmessage?'':'none')+';position:relative;float:left;border:0px solid red;width:100%;'});
		//var label2 = new Element('label',{'for':'isgift_checkbox_'+this.did}).update("You can fill in a message for the gift:");
		//label2.setStyle('position:relative;float:left;margin-top:2px;');

		var textarea = new Element('textarea',{'id':'isgift_message_'+this.did}).update(this.message);
		textarea.setStyle('width:'+(241)+'px;height:37px;position:relative;float:left;');

		var smb = new Element('a',{'id':'isgift_message_'+this.did,'href':'#'});//.update('<font style="font-size:9px"><br></font>Valider');
		smb.setStyle('float:left;margin-top:7px;margin-left:3px;');
		smb.addClassName('button');
		smb.observe('click',this.saveMessage.bindAsEventListener(this));

		var smb_span = new Element('span').update('Valider');
		smb_span.setStyle('white-space: nowrap; text-align: center;width:60px;');
		smb.appendChild(smb_span);


		div3message.appendChild(textarea);
		div3message.appendChild(smb);
		div3.appendChild(checkbox);
		div3.appendChild(label);
		div3.appendChild(div3message);




		div_mare.appendChild(div1);
		div_mare.appendChild(div3);
		div_mare.appendChild(div2);
		div_mare.appendChild(div_empty);


		if(this.type==1){
			// - adaugam box-ul pentru pret
			var divp1 = new Element('div',{'id':'price_'+this.did}).update(this.delivery_price_text1 + ' 0.--');
			divp1.setStyle('positon:relative;font-size:11px;color:#C6006F;font-weight:bold;display:block;float:left;border-top:1px solid #eee;width:100%;margin-top:3px;');

			div_mare.appendChild(divp1);
		}else{


		}


		if(this.type==1){
			//-pickup
			//console.log("BOXID="+this.id+" ADDRESSID="+this.addressid);
			if(this.id<1000){
				var pickup = new Element('div',{}).update('PICKUP<br>DEPOT');
				pickup.setStyle('position:absolute;top:0px;right:0px;text-align:center;font-size:11px;font-weight:bold;padding:3px;border:2px solid #880042;background-color:#B00055;color:#fff;margin-top:5px;margin-right:5px;');
				div_mare.appendChild(pickup);

				if(this.hasmap){
					var pickupicon = new Element('img',{'src':'img/mapicon.png'});
					pickupicon.setStyle('position:absolute;top:7px;right:60px;cursor:pointer;');
					div_mare.appendChild(pickupicon);
					pickupicon.observe('click',this.openMapPopup.bindAsEventListener(this));
				}
			}

		}
		//alert(this.parent_element);
		$(this.parent_element).appendChild(div_mare);
		Droppables.add(this.did,{
			accept: 'product'
			,onDrop: this.dropSuccess.bindAsEventListener(this)

		});

		//this.populateRender();

		this.manager.anythingHappens();
		this.updateShippingCost();
	}

	,openMapPopup:function(event){
		Popup.open({url:'index.php?object=pickup_places&method=ShowMap&id='+this.id,status:'no'});
	}

	,saveMessage: function(){
		var url = 'index.php?object=cart&method=SaveBoxMessage&boxid='+this.id+'&message='+$('isgift_message_'+this.did).value;
		new Ajax.Request(url, {
			method: 'post',
			onSuccess: this.saveMessageExecute.bindAsEventListener(this)
		});
	}

	,saveMessageExecute:function(transport){
		var response = transport.responseText;
		if(response>0){
			if($('isgift_message_'+this.did).value.trim()!='')
				alert('The message has been saved');
			return false;
		}else{
			alert('Cannot save message');
			return false;
		}

	}

	,updateShippingCost: function(){
		var url = 'index.php?object=cart&method=getAddressCalculations&addressid='+this.id;
		new Ajax.Request(url, {
			method: 'post',
			onSuccess: this.updateShippingCostExecute.bindAsEventListener(this)
		});
	}

	,updateShippingCostExecute: function(transport){
		var response = eval('('+transport.responseText+')');
		var cost = response.cart_address.shipping_costs.total;
		if(cost>0){
			var cost_formatted = response.cart_address.shipping_costs.total_formatted;
			$('price_'+this.did).update(this.delivery_price_text1 + cost_formatted);
			$('price_'+this.did).show();
		}else{
			$('price_'+this.did).hide();
		}
	}

	,populateRender: function(){
		//console.log('populating');
		if(this.type==1){
			var address = this.city + (this.address1.trim()!='' ? ('<br>' + this.address1):'') + (this.address2.trim()!='' ? ('<br>' + this.address2):'') + (this.zip.trim()!='' ? ('<br>' + this.zip):'');
			$('actualaddress_'+this.did).update(address);
		}else{
			var address = (this.addressid<1000?'PICKUP: ':'') + this.city + ', ' + (this.address1.trim()!='' ? (this.address1):'') + (this.address2.trim()!='' ? (' ' + this.address2):'') + (this.zip.trim()!='' ? (' - ' + this.zip):'');
			$('changeaddress_'+this.did).update(address);
			$('bolded_'+this.did).update(this.boxname);
			$("changeaddress_"+this.did).update(address);

		}

		this.updateShippingCost();
	} // populateRender

	,updateRender:function(){

		this.updateCurrentAddressDescriptors();
	}

	,updateMessageSettingsFromDB:function(){
		if(this.type==2){
			$('isgift_message_'+this.did).update(message);
			$('isgift_checkbox_'+this.did).checked = this.hasmessage;
		}
	}

	,updateCurrentAddressDescriptors: function(){
		var url = 'index.php?object=cart&method=GetAddress&addressid='+this.addressid;
		new Ajax.Request(url, {
			method: 'post',
			onSuccess: this.updateCurrentAddressDescriptorsExecute.bindAsEventListener(this)
		});
	}
	,updateCurrentAddressDescriptorsExecute:function(transport){
		var response = eval('('+transport.responseText+')');
		this.city = response.city;
		this.address1 = response.address1;
		this.address2 = response.address2;
		this.zip = response.zip;
		this.populateRender();
	}

	,onGiftClick: function(){
		if($('isgift_checkbox_'+this.did).checked){
			$('isgift_div_message_'+this.did).show();
		}else{
			$('isgift_div_message_'+this.did).hide();
			$('isgift_message_'+this.did).value = '';
			this.message = '';
			this.saveMessage();

		}

		// update user_addresses.is_giftbox
		this.updateBoxGiftStatus();
	}

	,updateBoxGiftStatus: function(){
		var url = 'index.php?object=cart&method=SetBoxGiftStatus&boxid='+this.id+'&is_gift='+($('isgift_checkbox_'+this.did).checked?1:0);
		new Ajax.Request(url, {
			method: 'post',
			onSuccess: this.updateBoxGiftStatusExecute.bindAsEventListener(this)
		});
	}

	,updateBoxGiftStatusExecute:function(transport){
		var response = transport.responseText;
		if(response>0){
			return false;
		}else{
			return false;
		}

	}




	,dropSuccess: function(element){

		var tokens1 = element.id.split('_');
		var tokens2 = this.did.split('_');
		var productid = parseInt(tokens1[1].trim());
		var boxid = parseInt(tokens2[2].trim());
		var boxtype = parseInt(tokens2[3].trim());
		available = this.manager.getProductRemaining(productid);
		if(available>0){
			ahi = this.alreadyHasIt(productid);
			if(ahi!==false){
				ahi.plusQuantity();
			}else{
				//console.log('Assign product #'+productid+' to box #'+boxid+' ,boxtype='+boxtype);
				manager.assignProductToBox(productid,boxid,boxtype);
			}
		}else{
			alert('Vous n\'avez plus de produit disponible dans votre panier!');
		}
		this.manager.anythingHappens();
		this.updateShippingCost();
	}

	,updateBoxQuantityFromDB:function(productid,quantity,boxtype){
		for(i=0;i<this.products.length;i++)
			if(this.products[i].productid==productid && this.products[i].boxtype==boxtype){
				this.products[i].updateBoxQuantityFromDB(quantity);
			}
	}

	,alreadyHasIt: function(productid){
		for(i=0;i<this.products.length;i++)
			if(this.products[i].productid==productid){
				return this.products[i];
			}
		return false;
	}
	,updateEmptyText: function(){
		//console.log("ProdusE:"+this.products.length + ' inh='+$('contents_'+this.did).innerHTML);
		if(this.products.length<=0){
			//console.log("adaugam textul gol");
			$('emptytext_'+this.did).show();
		}else if(this.products.length==1){
			//console.log("scoatem textul gol");
			$('emptytext_'+this.did).hide();
		}
		this.manager.anythingHappens();
	}

	,enablePlusButton: function(productid,isgiftbox){
		//console.log('IGBbox='+isgiftbox);
		for(var i=0;i<this.products.length;i++)
			if(this.products[i].productid==productid)
				this.products[i].enablePlusButton(isgiftbox);
	}

	,disablePlusButton: function(productid,isgiftbox){
		//console.log('IGBbox='+isgiftbox);
		for(var i=0;i<this.products.length;i++)
			if(this.products[i].productid==productid)
				this.products[i].disablePlusButton(isgiftbox);
	}

}); // BOX
