
doRequest = new Class({
	url: null,
	method: 'post',
	onSuccess: null,
	onRequest: null,
	onFailure: null,
	assync: false,
	data: null,

	initialize: function(options) {
		this.url = options.url ? options.url : this.url;
		this.method = options.method ? options.method : this.method;
		this.onSuccess = options.onSuccess ? options.onSuccess : this.onSuccess;
		this.onRequest = options.onRequest ? options.onRequest : this.onRequest;
		this.onFailure = options.onFailure ? options.onFailure : this.onFailure;
		this.assync = options.assync ? options.assync : this.assync;
		this.data = options.data ? options.data : this.data;
	},

	request: function() {
	  options = {
            url: this.url,
            method: this.method,
            assync: this.assync, 
            onRequest: this.onRequest,
            onSuccess: this.onSuccess,
            onFailure: this.onFailure
            } 
  		myRequest = new Request(options);
  		myRequest.send(this.data);
	}
});

tContent = new Class({
	initialize: function(html) {
		if(html == 'unlogged'){
			document.location.href = 'http://www.e-numizmatyka.pl/portal/strona-glowna/home/logowanie.html';
		}
		else {
			eval('JSONData = (' + html + ')');
			this.setContent(JSONData);
		}
	},

	setContent: function(JSONData){
		el = $$('.columnRight .boxTopMiddle h3').getElement('strong');
		el.set('html', 'Produkty');

		$('sellProducts').set('html', '');

		div = new Element('div', {
			'align': 'right'
		});
		$('sellProducts').adopt(div);

		button = new Element('input', {
			'type': 'button',
			'value': 'dodaj / przejdź do koszyka',
			'class': 'button',
			'styles': {
				'width': '150px',
				'margin': '0 0 5px 0'
			},
			'onclick': 'shoppingCart.cartIn()'
		});
		div.adopt(button);

		table = new Element('table', {
			'id': 'mainTable',
			'cellpadding': '2',
			'cellspacing': '0',
			'border': '0',
			'width': '100%' 
		});
		$('sellProducts').adopt(table);

		tr = new Element('tr');
		table.adopt(tr);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeader',
			'html': '&nbsp;'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '50%',
			'class': 'tableHeader',
			'align': 'left',
			'html': '<strong>Nazwa</strong>'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeader',
			'align': 'center',
			'html': '<strong>Cena</strong>'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeader',
			'align': 'center',
			'html': '<strong>Marża %</strong>'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeader',
			'align': 'center',
			'html': '<strong>Waga g</strong>'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeaderRight',
			'align': 'center',
			'html': '<strong>Ilość</strong>'
		});
		tr.adopt(th);

		JSONData.items.each(function(el, index){
			odd = index % 2 == 0 ? '' : 'Odd';
			tr = new Element('tr', {
				'class': 'row' + odd,
				'onmouseover': 'this.className = \'rowHover\'',
				'onmouseout': 'this.className = \'row'+odd+'\''
			});
			table.adopt(tr);

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' + odd
			});
			tr.adopt(td);			
			checkbox = new Element('input', {
				'type': 'checkbox',
				'name': 'id[]',
				'value': el.id
			})
			td.adopt(checkbox);

			td = new Element('td', {
				'width': '50%',
				'class': 'tableRow' + odd,
				'align': 'left',
				'html': '<a href="#" onClick="selectBox(this); return false;">' + el.name + '</a>'
			});
			tr.adopt(td);

			price = parseFloat(el.price);
			price = shoppingCart.formatPrice(price.toFixed(2));

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' +odd,
				'align': 'center',
				'html': price
			});
			tr.adopt(td);	

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' +odd,
				'align': 'center',
				'html': el.margin
			});
			tr.adopt(td);

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' +odd,
				'align': 'center',
				'html': parseFloat(el.weight).toFixed(2)
			});
			tr.adopt(td);

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' +odd+ 'Right',
				'align': 'center'
			});
			tr.adopt(td);

			input = new Element('input', {
				'id': 'input' + el.id,
				'type': 'text',
				'name': 'qty[]',
				'class': 'field',
				'size': '7',
				'styles': {
					'text-align': 'center'
				}
			})
			td.adopt(input);		
		});

		div = new Element('div', {
			'align': 'right'
		});
		$('sellProducts').adopt(div);

		button = new Element('input', {
			'type': 'button',
			'value': 'dodaj / przejdź do koszyka',
			'class': 'button',
			'styles': {
				'width': '150px',
				'margin': '5px 0 5px 0'
			},
			'onclick': 'shoppingCart.cartIn()'
		});
		div.adopt(button);

		div = new Element('div', {
			'styles': {
				'float': 'right',
				'text-align': 'right'
			},
			'html': '<br /><font style="font-size: 11px;"><strong>Cena 1 uncji złota w USD:</strong> ' +shoppingCart.formatPriceNoSufix(JSONData.metal)+ '<br /><strong>Cena dolara:</strong> ' +shoppingCart.formatPrice(JSONData.currency)+ '<br /></font>'
		});
		$('sellProducts').adopt(div);

		div = new Element('div', {
			'styles': {
				'clear': 'both'
			}
		});
		$('sellProducts').adopt(div);

		html = $('sellProducts').get('html');
		$('sellProducts').set('html', html);

		$$('#sellProducts input[type=text]').each(function(el, index){
			if(el.value == ''){
				el.value = '1';
			}
		});
	}	
});


cContent = new Class({
	initialize: function(html) {
		if(html == 'unlogged'){
			document.location.href = 'http://www.e-numizmatyka.pl/portal/strona-glowna/home/logowanie.html';
		}
		else {
			this.setContent();
		}
	},

	setContent: function(){
		$('sellProducts').set('html', '');
	
		if(shoppingCart.cartContent.length == 0){
			div = new Element('div', {
				'align': 'right'
			});
			$('sellProducts').adopt(div);

			img = new Element('img', {
				'src': 'assets/templates/enumizmatyka/images/btn/back_bt.gif',
				'border': '0',
				'styles': {
					'cursor': 'pointer'
				},
				'onclick': 'shoppingCart.cartBack()',
				'title': 'Powrót do spisu produktów'
			});

			div.adopt(img);

			div = new Element('div', {
				'align': 'center',
				'html': '<strong>Twój koszyk jest pusty</strong>'
			});
			$('sellProducts').adopt(div);	

			html = $('sellProducts').get('html');
			$('sellProducts').set('html', html);

			return;		
		}

		div = new Element('div', {
			'align': 'right'
		});
		$('sellProducts').adopt(div);

		img = new Element('img', {
			'src': 'assets/templates/enumizmatyka/images/btn/back_bt.gif',
			'border': '0',
			'styles': {
				'cursor': 'pointer'
			},
			'onclick': 'shoppingCart.cartBack()',
			'title': 'Powrót do spisu produktów'
		});

		div.adopt(img);

		table = new Element('table', {
			'id': 'mainTable',
			'cellpadding': '2',
			'cellspacing': '0',
			'border': '0',
			'width': '100%' 
		});
		$('sellProducts').adopt(table);

		tr = new Element('tr');
		table.adopt(tr);

		th = new Element('th', {
			'width': '5%',
			'class': 'tableHeader',
			'html': 'Lp.'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '50%',
			'class': 'tableHeader',
			'align': 'left',
			'html': '<strong>Nazwa</strong>'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeader',
			'align': 'center',
			'html': '<strong>Cena</strong>'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeader',
			'align': 'center',
			'html': '<strong>Marża %</strong>'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeader',
			'align': 'center',
			'html': '<strong>Waga g</strong>'
		});
		tr.adopt(th);


		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeader',
			'align': 'center',
			'html': '<strong>Ilość</strong>'
		});
		tr.adopt(th);

		th = new Element('th', {
			'width': '10%',
			'class': 'tableHeaderRight',
			'align': 'center',
			'html': '<strong>Usuń</strong>'
		});
		tr.adopt(th);

		var total = 0;
		var totalWeight = 0;
		shoppingCart.cartContent.each(function(el2, index){
			total += parseFloat(shoppingCart.listData[el2.id].price) * parseInt(el2.qty);
			totalWeight += parseFloat(shoppingCart.listData[el2.id].weight) * parseInt(el2.qty);
		});

		shoppingCart.cartContent.each(function(el, index){
			odd = index % 2 == 0 ? '' : 'Odd';
			tr = new Element('tr', {
				'class': 'row' + odd,
				'onmouseover': 'this.className = \'rowHover\'',
				'onmouseout': 'this.className = \'row'+odd+'\''
			});
			table.adopt(tr);

			td = new Element('td', {
				'width': '5%',
				'class': 'tableRow' + odd,
				'align': 'center',
				'html': (index + 1) + '.'
			});
			tr.adopt(td);


			td = new Element('td', {
				'width': '50%',
				'class': 'tableRow' + odd,
				'align': 'left',
				'html': shoppingCart.listData[el.id].name
			});
			tr.adopt(td);

			price = parseFloat(shoppingCart.listData[el.id].price) * parseInt(el.qty);
			price = shoppingCart.formatPrice(price.toFixed(2));

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' +odd,
				'align': 'center',
				'html': price
			});
			tr.adopt(td);

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' +odd,
				'align': 'center',
				'html': shoppingCart.listData[el.id].margin
			});
			tr.adopt(td);

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' +odd,
				'align': 'center',
				'html': (parseFloat(shoppingCart.listData[el.id].weight) * parseInt(el.qty)).toFixed(2)
			});
			tr.adopt(td);		
		

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' +odd,
				'align': 'center'
			});
			tr.adopt(td);

			input = new Element('input', {
				'id': 'input' + el.id,
				'type': 'text',
				'name': 'qty[]',
				'class': 'field',
				'size': '7',
				'styles': {
					'text-align': 'center'
				}
			});
			td.adopt(input);	

			td = new Element('td', {
				'width': '10%',
				'class': 'tableRow' + odd+ 'Right'
			});
			tr.adopt(td);
			
			checkbox = new Element('input', {
				'type': 'checkbox',
				'name': 'id[]',
				'value': el.id
			})
			td.adopt(checkbox);
		
		});

		br = new Element('br');
		$('sellProducts').adopt(br);

		div = new Element('div', {
			'styles': {
				'float': 'right',
				'text-align': 'right'
			},
			'html': '<font style="font-size: 11px;"><br /><strong>Cena złota: </strong>' +shoppingCart.formatPrice(shoppingCart.metal).replace("zł", "$")+ '<br /><strong>Cena dolara:</strong> ' +shoppingCart.formatPrice(shoppingCart.currency)+ '<br /><strong>Łączna waga:</strong> ' +totalWeight.toFixed(2)+ ' g<br /><strong>Suma:</strong> ' + shoppingCart.formatPrice(total.toFixed(2)) + '</font>'
		});
		$('sellProducts').adopt(div);

		div = new Element('div', {
			'styles': {
				'clear': 'both',
				'height': '10px'
			}
		});
		$('sellProducts').adopt(div);

		div = new Element('div', {
			'styles': {
				'float': 'left'
			}
		});
		$('sellProducts').adopt(div);

		button = new Element('input', {
			'type': 'button',
			'value': 'przelicz',
			'class': 'button',
			'onclick': 'shoppingCart.cartRecalculate()'
		});
		div.adopt(button);

		div = new Element('div', {
			'styles': {
				'float': 'right'
			}
		});
		$('sellProducts').adopt(div);

		button = new Element('input', {
			'type': 'button',
			'value': 'złóż ofertę',
			'class': 'button',
			'onclick': 'shoppingCart.cartPurchase()'
		});
		div.adopt(button);

		div = new Element('div', {
			'styles': {
				'clear': 'both'
			}
		});
		$('sellProducts').adopt(div);

		html = $('sellProducts').get('html');
		$('sellProducts').set('html', html);

		$$('#sellProducts input[type=text]').each(function(el, index){
			id = el.id.replace('input', '');
			shoppingCart.cartContent.each(function(el2, index){
				if(id == el2.id) {
					qty = el2.qty;
				}
			});

			el.value = qty;
		});
	} 	
});


Cart = new Class({
	Implements: Chain,

	initialize: function() {},

	cartIn: function(){
     		this.chain.apply(this, [
						function() {
							el = $$('.columnRight .boxTopMiddle h3').getElement('strong');
							el.set('html', 'Koszyk');
						},
						function() {this.checkInputs()}, 
						function() {
							var hide = new Fx.Tween('sellProducts', {
								'property': 'opacity',
								'duration': '1000',
								'link': 'chain',
								'onComplete': function() {
									data = '';
									shoppingCart.cartContent.each(function(el, index) {
										rand = Math.random();
										data += el.id + ':' + el.qty + ',';
									});
									if(shoppingCart.cartContent.length > 0){
										data = data.substr(0, data.length - 1);
									}
									data = 'data=' + data + '&rand=' + rand;
									req = new doRequest({
										'data': data,
										'url': '/portal/index.php?id=1693',
										'onSuccess': function(html) {
											eval('JSONData = (' + html + ')');
											shoppingCart.listData = {};
											JSONData.items.each(function(el, index) {
												shoppingCart.listData[el.id]= {name: el.name, price: el.price, margin: el.margin, weight: el.weight};
											});


											shoppingCart.cartContent = [];
											JSONData.cart.each(function(el, index) {
												shoppingCart.cartContent.push(el);														});

											shoppingCart.metal = JSONData.metal;
											shoppingCart.currency = JSONData.currency;

											new cContent(JSONData);
											this.onComplete = function() {};
										}.bind(this),
					
										'onRequest': function() {
											$('sellProducts').set('opacity', 1);
											$('sellProducts').set('html', 'Trwa uaktualnianie danych...');
										},
										'onFailure': function() {alert('Błąd wczytywania danych')}
									});
									req.request();
								}
							 });		
							hide.start(1, 0); 
						}
					]);
		flag = true;
		$$('#sellProducts input[type=text]').each(function(el, index){
			reg = /^[1-9]{1}[0-9]*$/;
			if(reg.test(el.value) != true){
				flag = false;
			}
		});

		if(!flag){
			alert('Ilość produktów musi być liczbą!');
			this.clearChain();
		}
        	while(this.$chain.length) this.callChain();
	},


	cartRecalculate: function(){

     		this.chain.apply(this, [
						function() {
							el = $$('.columnRight .boxTopMiddle h3').getElement('strong');
							el.set('html', 'Koszyk');
						},
						function() {this.removeInputs()},
						function() {this.updateCart()}, 
						function() {
							var hide = new Fx.Tween('sellProducts', {
								'property': 'opacity',
								'duration': '1000',
								'link': 'chain',
								'onComplete': function() {
									data = '';
									shoppingCart.cartContent.each(function(el, index) {
										rand = Math.random();
										data += el.id + ':' + el.qty + ',';
									});
									if(shoppingCart.cartContent.length > 0){
										data = data.substr(0, data.length - 1);
									}
									data = 'data=' + data + '&rand=' + rand + '&recalculate=1';
									req = new doRequest({
										'data': data,
										'url': '/portal/index.php?id=1693',
										'onSuccess': function(html) {
											eval('JSONData = (' + html + ')');
											shoppingCart.listData = {};
											JSONData.items.each(function(el, index) {
												shoppingCart.listData[el.id]= {name: el.name, price: el.price, margin: el.margin, weight: el.weight};
											});

											shoppingCart.cartContent = [];
											JSONData.cart.each(function(el, index) {
												shoppingCart.cartContent.push(el);														});
											
											shoppingCart.metal = JSONData.metal;
											shoppingCart.currency = JSONData.currency;

											new cContent(html);
											this.onComplete = function() {};
										}.bind(this),
					
										'onRequest': function() {
											$('sellProducts').set('opacity', 1);
											$('sellProducts').set('html', 'Trwa uaktualnianie danych...');
										},
										'onFailure': function() {alert('Błąd wczytywania danych')}
									});
									req.request();
								}
							 });		
							hide.start(1, 0); 
						}
					]);
		flag = true;
		$$('#sellProducts input[type=text]').each(function(el, index){
			reg = /^[1-9]{1}[0-9]*$/;
			if(reg.test(el.value) != true){
				flag = false;
			}
		});

		if(!flag){
			alert('Ilość produktów musi być liczbą!');
			this.clearChain();
		}
        	while(this.$chain.length) this.callChain();
	},


	cartPurchase: function(){
     		this.chain.apply(this, [
						function() {
							el = $$('.columnRight .boxTopMiddle h3').getElement('strong');
							el.set('html', 'Potwierdzenie złożenia oferty');
						},
						function() {this.checkInputs()}, 
						function() {
							var hide = new Fx.Tween('sellProducts', {
								'property': 'opacity',
								'duration': '1000',
								'link': 'chain',
								'onComplete': function() {
									data = '';
									shoppingCart.cartContent.each(function(el, index) {
										rand = Math.random();
										data += el.id + ':' + el.qty + ',';
									});
									if(shoppingCart.cartContent.length > 0){
										data = data.substr(0, data.length - 1);
									}
									data = 'data=' + data + '&rand=' + rand;
									shoppingCart.cartContent = [];

									req = new doRequest({
										'data': data,
										'url': '/portal/index.php?id=1696',
										'onSuccess': function(html) {	
											if(html == 'unlogged'){
												document.location.href = 'http://www.e-numizmatyka.pl/portal/strona-glowna/home/logowanie.html';
											}
											else{								
												this.onComplete = function() {};
												$('sellProducts').set('html', html);
											}
										}.bind(this),
					
										'onRequest': function() {
											$('sellProducts').set('opacity', 1);
											$('sellProducts').set('html', 'Trwa transakcja...');
										},
										'onFailure': function() {alert('Błąd wczytywania danych')}
									});
									req.request();
								}
							 });		
							hide.start(1, 0); 
						}
					]);
		flag = true;
		$$('#sellProducts input[type=text]').each(function(el, index){
			reg = /^[1-9]{1}[0-9]*$/;
			if(reg.test(el.value) != true){
				flag = false;
			}
		});

		if(!flag){
			alert('Ilość produktów musi być liczbą!');
			this.clearChain();
		}
        	while(this.$chain.length) this.callChain();
	},


	cartContent: [],

	listData: {},

	metal: null,

	currency: null,

	checkInputs: function() {
		$$('#sellProducts input[type=checkbox]').each(function(el, index){
			if(el.checked == true){
				this.setCart(el.value);
			}
		}.bind(this));
	},

	removeInputs: function() {
		$$('#sellProducts input[type=checkbox]').each(function(el, index){
			if(el.checked == true){
				this.unsetCart(el.value);
			}
		}.bind(this));
	},
	setCart: function(value){
		if(parseInt($('input' + value).value) > 0){
			flag = true;
			this.cartContent.each(function(el, index){
				if(el.id == value){
					this.cartContent[index] = {id: value, qty: parseInt($('input' + value).value)};
					flag = false;
					return;
				}
			}.bind(this));

			if(flag) this.cartContent.push({id: value, qty: parseInt($('input' + value).value)});
		}
	},

	unsetCart: function(value){
		elements = this.cartContent;
		elements.each(function(el, index){
			if($defined(el)) {
				if(el.id == value){
					this.cartContent.erase(el);
					return;
				}
			}
		}.bind(this));	
	},

	updateCart: function(){
		this.cartContent.each(function(el, index){
			this.cartContent[index] = {id: el.id, qty: parseInt($('input' + el.id).value)}
		}.bind(this));	
	},

	suffix: 'zł',

	formatPrice: function(price){
		price = price.toString();
		price += ' ' + this.suffix; 

		return price;
	},
	
	formatPriceNoSufix: function(price){
		price = price.toString(); 

		return price;
	},

	cartBack: function(){
		id = $('sellProducts').retrieve('category');
		req = new doRequest({
			'url': '/portal/index.php?id=1693&cat=' + id,
			'onSuccess': function(html) {new tContent(html)},
					
			'onRequest': function() {						
				if(!$('spinImg')){
					$('sellProducts').set('html', '');
					var Img = new Element('img',{
    						'id': 'spinImg',
    						'src': 'assets/templates/enumizmatyka/images/bg/spin.gif' 
					});
					$('sellProducts').adopt(Img);					
				}						
			},
			'onFailure': function() {alert('Błąd wczytywania danych')}
		});
		req.request();
	}
});

var shoppingCart = new Cart();

function selectBox(el) {
	$(el).getParent().getParent().getChildren().each(function(element, index) {
		if(element.tagName == 'TD'){
			element.getChildren().each(function(element2, index2) {
				if(element2.get('TYPE') == 'checkbox'){
					element2.checked = true;
				}
			});
		}
	});
	shoppingCart.cartIn();
}

window.addEvent('domready', function(){
	$$('.loadProducts').each(function(el, index) {
		el.addEvent('click', function(event){
			event.stop();
			id = this.get('rel');
			$('sellProducts').store('category', id);
			rand = Math.random();
			req = new doRequest({
					'data': 'rand=' + rand,
					'url': '/portal/index.php?id=1693&cat=' + id,
					'onSuccess': function(html) {new tContent(html)},					
					'onRequest': function() {						
						if(!$('spinImg')){
							$('sellProducts').set('html', '');
							var Img = new Element('img',{
    								'id': 'spinImg',
    								'src': 'assets/templates/enumizmatyka/images/bg/spin.gif' 
							});
							$('sellProducts').adopt(Img);					
						}						
					},
					'onFailure': function() {alert('Błąd wczytywania danych')}
			});
			req.request();
			
			
		});
	});
});

window.addEvent('domready', function(){
	if($defined($('sellProducts'))) {
		id = '';
		$('sellProducts').store('category', '');
		rand = Math.random();
		req = new doRequest({
			'data': 'rand=' + rand,
			'url': '/portal/index.php?id=1693&cat=' + id,
			'onSuccess': function(html) {new tContent(html)},
			'onRequest': function() {						
				if(!$('spinImg')){
					$('sellProducts').set('html', '');
					var Img = new Element('img',{
    						'id': 'spinImg',
    						'src': 'assets/templates/enumizmatyka/images/bg/spin.gif' 
					});
					$('sellProducts').adopt(Img);					
				}						
			},
			'onFailure': function() {alert('Błąd wczytywania danych')}
		});
		req.request();
	}
});

