var myebooks = {};


myebooks.Basket = Class.create({

	initialize: function(basketId) {
		this.basketId = basketId;
		this.total = 0;
		this.items = [];

		//this.emptyHtml = '<div class="empty">Δεν υπάρχουν προϊόντα<br />στο καλάθι σας</div>';
		this.emptyHtml = '<div class="empty">' + bundle.emptyHtml_a + '<br />' + bundle.emptyHtml_b + '</div>';
		this.itemsHtml = new Template(
			'<div class="items">' +
			'<a href="javascript:void(0)" onclick="myBasket.show();" title="'+
			bundle.itemsHtml_a+'">'+bundle.itemsHtml_b+
			'<strong>#{cnt}</strong> '+bundle.itemsHtml_c+'</a>' +
			'<div class="price"><span>'+bundle.itemsHtml_d+' =</span> <strong>#{totalFormatted}</strong></div>' +
			'</div>'
		);
		this.initUI();
		this.load();
	},

	initUI: function() {
		this.basketUI = $(this.basketId);
		this.summary = this.basketUI.down('.basket-summary');
		this.popup = this.basketUI.down('.basketBox');
		var itemTemplate = this.popup.down('.Template');
		var html = itemTemplate.innerHTML;
		html = html.replace("%7B", "{").replace("%7D", "}");
		this.popupItemHtml = new Template( html );

		itemTemplate.remove();

		var el = this.popup;
		this.basketUI.down('.basket-icon').observe( 'click', function() { if (this.total) { el.toggle(); } }.bind(this) );
		this.popup.down('.headClose a' ).observe('click', function() {el.hide();});
	},

	updateUI: function(basket) {
		if (basket.price<0) this.total = 0;
		else this.total = basket.price;

		if (basket.priceFormatted<0) this.totalFormatted = 0;
		else this.totalFormatted =  basket.priceFormatted;

		this.items = basket.items;
		basket.items.each(function(item){
			if(!item.discount){
				item.unitPrice2Formatted = null;
				item.discount = new Object();
				item.discount.title = '&nbsp;';
			}
			else{
				if(!item.unitPrice2Formatted){
					item.unitPrice2Formatted = item.unitPriceFormatted;
				}
			}
		});
		this.updateSummary();
		this.updatePopup();
	},

	updateSummary: function() {
		var div = this.summary.firstDescendant(), html;
		if ( this.items.length > 0  ) {
			html = this.itemsHtml.evaluate({
				cnt: this.items.length,
				total: this.total,
				totalFormatted: this.totalFormatted
			});

		} else {
			html = this.emptyHtml;
		}
		div.replace( html );
	},

	updatePopup: function() {
		var body = this.popup.down('.body');

		var list = body.down('ul');
		list.select('li').each(function(li, idx) {
			if (idx >0 ) li.remove();
		});
		this.items.each(function(item, idx) {
			var li =  new Element('li');
			list.insert( li );
			li.insert( this.popupItemHtml.evaluate(item) );
			li.down('.delete').observe('click', function() {
				this.remove( item.path );
			}.bind( this ));
		}, this);

		body.down('.total strong').update( this.totalFormatted );
	},

	load: function() {
		BasketService.getBasket({
			callback: this.updateUI,
			scope: this
		});
	},

	addOffer : function(isbn){
		var div = $('shadowbox_content').down('.offer-list');
		var frms = div.getElementsByTagName('form');
		var bookInserted = false;
		var offerPaths = new Object();
		offerPaths.offerBookPaths = new Array();
		for (var i = 0; i < frms.length; i++) {
		    var form = frms[i];
		    var formElems = form.getElementsByTagName('input');
			var checkBoxes = new Array();
			var maxsel = 0;
			var offer;
			for(var j = 0; j < formElems.length; j++){
				if(formElems[j].getAttribute('type') == 'checkbox') {
					checkBoxes[checkBoxes.length] = formElems[j];
				} else if(formElems[j].getAttribute('type') == 'hidden') {
					if(formElems[j].getAttribute('name') == 'maxsel'){
						maxsel = formElems[j].value;
					} else if(formElems[j].getAttribute('name') == 'bookpath'){
						offerPaths.parentBookPath = formElems[j].value;
					} else if(formElems[j].getAttribute('name') == 'offerpath'){
						offer = formElems[j].value;
					}
				}
			}
			var selected = 0;
			for(var j = 0; j < checkBoxes.length; j++){
				if(checkBoxes[j].checked == true){
					offerPaths.offerBookPaths[offerPaths.offerBookPaths.length] = checkBoxes[j].value;
					selected++;
					if(selected > maxsel){
						alert(bundle.offer);
						return;
					}
				}
			}
		}
		this.addOfferToBasket(offerPaths, offer, isbn);
		Shadowbox.close();
	},

	addOfferToBasket: function(offerPaths, offer, isbn) {
		BasketService.addOfferToBasket(offerPaths, offer, {
			callback: this.onAdd,
			exceptionHandler: function(msg, exception){
				if(exception.javaClassName == 'gr.myebooks.DuplicateItemException') {
					alert(msg);
				} else if(exception.javaClassName == 'gr.myebooks.CommonBooksWarningException') {
					var answer = confirm(msg);
					if(answer){
						this.add(path, isbn, answer);
					}
				} else if(exception.javaClassName == 'gr.myebooks.RemoveDuplicateItemException') {
					var answer = confirm(msg);
					if(answer){
						this.remove(path);
						this.add(path, isbn, unchecked);
					}
				}else if(msg == 'only same type') {
					alert(bundle.sameTypeOnly);
				}
			},
			scope: this,
			arg: isbn
		});
	},

	add: function(path, isbn, unchecked) {
		BasketService.addToBasket(path, unchecked, null, null, null, {
			callback: this.onAdd,
			exceptionHandler: function(msg,exception) {
				if(exception.javaClassName == 'gr.myebooks.DuplicateItemException') {
					alert(msg);
				} else if(exception.javaClassName == 'gr.myebooks.CommonBooksWarningException') {
					var answer = confirm(msg);
					if(answer){
						this.add(path, isbn, answer);
					}
				} else if(exception.javaClassName == 'gr.myebooks.RemoveDuplicateItemException') {
					var answer = confirm(msg);
					if(answer){
						this.remove(path);
						this.add(path, isbn, unchecked);
					}
				}else if(msg == 'only same type') {
					alert(bundle.sameTypeOnly);
				}
			},
			scope: this,
			arg: isbn
		});
	},

	addMagazine: function(path, issn, issue, unchecked) {
		issn = issn + issue;
		BasketService.addToBasket(path, unchecked, null, null, null, {
			callback: this.onAdd,
			exceptionHandler: function(msg,exception) {
				if(exception.javaClassName == 'gr.myebooks.DuplicateItemException') {
					alert(bundle.itemExist);
				} else if(exception.javaClassName == 'gr.myebooks.CommonBooksWarningException') {
					var answer = confirm(msg);
					if(answer){
						this.add(path, issn, issue, answer);
					}
				} else if(exception.javaClassName == 'gr.myebooks.RemoveDuplicateItemException') {
					var answer = confirm(msg);
					if(answer){
						this.remove(path);
						this.add(path, issn, issue, unchecked);
					}
				}
			},
			scope: this,
			arg: issn
		});
	},

	addPackage: function(path, id, unchecked) {
		BasketService.addToBasket(path, unchecked, null, null, null, {
			callback: this.onAdd,
			exceptionHandler: function(msg,exception) {
				if(exception.javaClassName == 'gr.myebooks.DuplicateItemException') {
					alert(bundle.itemExist);
				} else if(exception.javaClassName == 'gr.myebooks.CommonBooksWarningException') {
					var answer = confirm(msg);
					if(answer){
						this.addPackage(path, id, answer);
					}
				} else if(exception.javaClassName == 'gr.myebooks.RemoveDuplicateItemException') {
					var answer = confirm(msg);
					if(answer){
						this.remove(exception.itemPath);
						this.addPackage(path, id, unchecked);
					}
				}
			},
			scope: this,
			arg: id
		});
	},

	add_new: function(path, isbn, unchecked) {
		BasketService.getBasketItem(path, {
			callback: this.onBasketItem,
			exceptionHandler: function(msg,exception) {
				alert(msg);
			},
			scope: this
		});
	},

	onBasketItem: function (basketItem) {
		alert('Check basket item');
	},


	remove: function(path) {
		BasketService.removeFromBasket(path, {
			callback: this.updateUI,
			scope: this
		});
	},

	clear: function() {
		BasketService.clear({
			callback: this.updateUI,
			scope: this
		});
	},

	show: function() {
		if ( this.items.length > 0 ) {
			this.popup.show();
		}
	},

	toggle: function() {
		if ( this.items.length > 0 ) {
			this.popup.toggle();
		}
	},

	onAdd: function (basket, isbn) {
		this.updateUI(basket);
		if ($('basket-message-'+isbn)) {
			//$('basket-message-'+isbn).innerHTML = 'To βιβλίο (ISBN: '+isbn+') προστέθηκε στο καλάθι σας';
			$('basket-message-'+isbn).innerHTML = bundle.add_isbn_c;
			$('basket-message-'+isbn).show();
			setTimeout("$('basket-message-"+isbn+"').hide();", 3000);
		}
	},

	onAddPackage: function (basket, id) {
		this.updateUI(basket);
		if ($('basket-message-'+id)) {
			$('basket-message-'+id).innerHTML = bundle.add_packages;
			$('basket-message-'+id).show();
			setTimeout("$('basket-message-"+id+"').hide();", 3000);
		}
	}
});



myebooks.initPayment = function(paymentPath,invoiceRequest,fullname,address,vat,taxOffice,confirmButton,isChecked,
							isGift,recipEmail,giftSubject,giftMessage,delivery_fullname,delivery_address,delivery_country,
							delivery_city,delivery_region,delivery_phone,delivery_postcode,delivery_comments,delivery_email) {
	var invoicing = new Object();
	if(invoiceRequest){
		invoicing.fullname = fullname;
		invoicing.address = address;
		invoicing.vat = vat;
		invoicing.taxOffice = taxOffice;
	} else {
		invoiceRequest = null;
	}

		var deliveryInfo = new Object();
	if(delivery_country && delivery_country!=''){
		deliveryInfo.address = delivery_address;
		deliveryInfo.fullname = delivery_fullname;
		deliveryInfo.country = delivery_country;
		deliveryInfo.city = delivery_city;
		deliveryInfo.region = delivery_region;
		deliveryInfo.phone = delivery_phone;
		deliveryInfo.postcode = delivery_postcode;
		deliveryInfo.comments = delivery_comments;
		deliveryInfo.email = delivery_email;
	}

	var gift = new Object();
	if(isGift){
		gift.email = recipEmail;
		gift.subject = giftSubject;
		gift.message = giftMessage;
		gift.coupon = null;
	} else {
		gift = null;
	}

	BasketService.placeOrder( paymentPath,invoicing,isChecked,gift,deliveryInfo, {
		callback: function(url) {
			window.location = url;
		}, errorHandler:function(errorString, exception) {
			if (exception.javaClassName == 'gr.myebooks.BooksInLibraryException') {
				var answer = confirm(errorString);
				if(answer){
					myebooks.initPayment(paymentPath,invoiceRequest,fullname,address,vat,taxOffice,confirmButton,answer,
							isGift,recipEmail,giftSubject,giftMessage,delivery_fullname,delivery_address,delivery_country,
							delivery_city,delivery_region,delivery_phone,delivery_postcode,delivery_comments,delivery_email);
				}
			}
			else if (errorString.substring(4,0) == 'User') {

						Shadowbox.open({
								content:    bundle.registration,
								player:     "iframe",
								title:      "",
								height:     210,
								width:      460
						});
			    confirmButton.disabled = false;
			}else if (errorString.substring(5,0) == 'Email') {
				alert(errorString);
			    confirmButton.disabled = false;
			} else {
				alert(errorString);
				confirmButton.disabled = false;
			}
		}
	});
};

function loadPackage(packagePath) {

	BasketService.getPackageInfo(
		packagePath, {
		callback: function(res){

			var b = $('package-summary').down('.package-box');
			var itemTemplate = b.down('.Template');
			var html = itemTemplate.innerHTML;
			html = html.replace("%7B", "{").replace("%7D", "}");
			var popupItemHtml = new Template( html );
			var emptyHtml = '<div class="empty">' + bundle.emptyHtml_a + '<br />' + bundle.emptyHtml_b + '</div>';

			var totalDiscountFormatted = res.discountFormatted;
			var totalInitialFormatted = res.initialPriceFormatted;
			var totalFormatted = res.finalPriceFormatted;

			var list = b.down('ul');
			list.select('li').each(function(li, idx) {
				if (idx >0 ) li.remove();
			});
			res.items.each(function(item, idx) {
				var li =  new Element('li');
				list.insert( li );
				li.insert( popupItemHtml.evaluate(item) );
			}, this);

			b.down('.discount strong').update( totalDiscountFormatted );
			b.down('.initial strong').update( totalInitialFormatted );
			b.down('.final strong').update( totalFormatted );
		},
		scope: this
	});
};

function loadItemPackage(packagePath, id) {

	BasketService.getPackageInfo(
		packagePath, {
		callback: function(res){
			var b = $('package-summary-'+id).down('.package-box');

			var itemTemplate = b.down('.Template');
			var html = itemTemplate.innerHTML;
			html = html.replace("%7B", "{").replace("%7D", "}");
			var popupItemHtml = new Template( html );
			var emptyHtml = '<div class="empty">' + bundle.emptyHtml_a + '<br />' + bundle.emptyHtml_b + '</div>';
			var totalDiscountFormatted = res.discountFormatted;
			var totalInitialFormatted = res.initialPriceFormatted;
			var totalFormatted = res.finalPriceFormatted;

			res.items.each(function(item){
				if(!item.unitPrice2Formatted){
					item.unitPrice2Formatted = item.unitPriceFormatted;
				}
			});

			var list = b.down('ul');
			list.select('li').each(function(li, idx) {
				if (idx >0 ) li.remove();
			});
			res.items.each(function(item, idx) {
				var li =  new Element('li');
				list.insert( li );
				 try { li.insert( popupItemHtml.evaluate(item) ); } catch(e) { console.error(e); };
			}, this);

			b.down('.discount strong').update( totalDiscountFormatted );
			b.down('.initial strong').update( totalInitialFormatted );
			b.down('.final strong').update( totalFormatted );
		},
		scope: this,
		arg: id
	});
};


function openOfferBox(isbn){
	Shadowbox.open({
			content:    $('select-offer-books-'+isbn).innerHTML,
			player:     "html",
			title:      "",
			height:     460,
			width:      760
	});
};

