var cart;
window.addEvent ("domready", function () {
	cart = new Cart();	
})

//w widoku produkut przypisuje zdarzenia na przyciski
function init_buttons () {
	try {
		//czyszczenie koszyka
		$('clear_cart').addEvent('click', function(){
			request_clear_cart();
			cart.clear_cart();
		})
		
		//skladania zapytania
		$('order').addEvent('click', function () {
			cart.make_order();
		})

	
	} catch (e) {}
}

function init_buttons2(order_now){
	try {

		//wyslij zapytanie
		$('send_query_btn').addEvent('click', function(){
			cart.send_query(order_now);
			
			
		})
		
		//komuniakat o bledzei
		cart.msg_silde = new Fx.Slide('msg_error_cart').hide();
		$('msg_error_cart').setStyle('visibility', 'visible');
	} 
	catch (e) {
	}
}



var Cart = new Class ({
	overallOpacity: 0.7,
	prod_cont_top: 100,
	prod_count: 0,
	empty: '',
	empty_slide: '',
	total_price: '',
	total_price_slide: '',
	closed: true,
	moving_busy: false,
	removing_busy: false,
	msg_slide: '',
	
	initialize: function () {
		//ukryj ciemna warstwe
		this.overlay = new Overlay ({ /* from overlay.js */
			height: 850, 
			cover_h: $(window).getScrollSize().x + 50
		})
		
		this.empty = $('empty');
		this.total_price = $('total_price');
		this.is_print = false;
		
		//koszyk zainicjalizuj slide
		$$('#cart_content .cart_prod').each (function (item, i) {
			new Fx.Slide (item.getFirst('.cart_prod_2'), {
				transition: Fx.Transitions.Cubic.easeOut,
				duration: 800,
				link: 'cancel'
			});				
			this.prod_count++;
		}.bind(this))
		
		// komunikat o pustym koszyku
		this.empty_slide = new Fx.Slide (this.empty, {
			transition: Fx.Transitions.Cubic.easeOut,
			duration: 800
		})
		if (this.empty.getStyle('display') == 'none') {
			this.empty_slide.hide();
		}
		
		//total price i realizuj zamowienie
		this.total_price_slide = new Fx.Slide (this.total_price, {
			transition: Fx.Transitions.Cubic.easeOut,
			duration: 800,
			link: 'cancel'
		})
	},
	
	init_print_calc:function  () {
		var fx_calc_nadruki = new Array();
		$$(".cart_calc_bottom").each (function(item, k) {
			fx_calc_nadruki[k] = new Fx.Slide (item, {
				transition: Fx.Transitions.Cubic.easeInOut,
				duration: 500,
				link: 'cancel'				
			}).hide();	
		})

		$$(".calc_rollover").each (function(item, k) {
			item.addEvent('click', function () {
				fx_calc_nadruki[k].toggle();
			})
		})
			

	},	
	
	
	addToCart: function (id) {
		//zdefiniuj funkcje ktora jest wywolywana w momencie kiedy warsta zostanie pokazana
		this.overlay.showContent = function () {
			request_addToCart(id, this.overlay)	
		}.bind(this);
		
		this.overlay.show();	
	},
	
	//przenoszenie do koszyka
	moveToCart: function (id) {
		//wywolaj asynchroniczne zadanie aby zapisac do sesji
		if (!this.moving_busy && !product.calculating && !this.removing_busy) {
			this.moving_busy = true;
			request_moveToCart(id, this.price, this.ilosc_sztuk, this.is_print, this.ilosc_kolorow, this.ilosc_miejsc, this.zdobienie);
			this.overlay.hide()
		}
		
	},
	
	order_now: function (id) {
		request_orderNow(id, this.price, this.ilosc_sztuk, this.is_print, this.ilosc_kolorow, this.ilosc_miejsc, this.zdobienie);
	},
	
	handle_moveToCart: function (response) {

		var cart;
		var empty = $('empty');
		this.price = '';
		//ukryj informacje o tym, ze koszyk jest pusty (niezaleznie od tego czy juz jest ukryta czy nie)
		//i po skonczeniu animacji wysun produkt
		
		this.empty_slide.onComplete = function () {
			slider.hide();
			product.setStyle('display', 'block');
			slider.slideIn();	
			this.empty.setStyle('display', 'none');
			this.empty_slide.onComplete = $empty;
			
			this.total_price.setStyle('display', 'block');	
			this.total_price_slide.slideIn();
				
		}.bind (this)
			
		if (this.prod_count == 0) {
			this.empty_slide.slideOut();
		}
		
		///sprawdz czy istnieje contener na elementy w koszyku (jesli nie to utworz go)
		if (!(cart = $('cart_prod_cont'))) {
			var cart = new Element ('div', {
				'id' : 'cart_prod_cont'
			})
			
			//wstaw element
			cart.inject ($('cart_content'), 'top');
		}
		
		//stworz nowy element w koszyku
		var product = new Element ('div', {
			'class': 'cart_prod',
			'styles': {
				'display': 'none'
			}
		})
		product.set('html',
			'<div class="cart_prod_2">' + 
			'<div class="cart_remove_prod"><img src="media/img/cart/cart_delete.gif" alt="Remove product" onclick="cart.removeFromCart(this)" /></div>' +
			'<div class="cart_prod_title">'+ response.product.name +'</div>' +
			'<div class="clear"></div>' +

			'<div class="cart_unit">Sztuk: <strong>'+ response.product.amount +'</strong></div>' +
			'<div class="cart_price">Cena: <strong>' + response.product.price + '</strong></div>' +
			'<div class="clear_l"></div></div>');
			
		
		product.inject (cart, 'bottom');
		
		var last_index = ($$('#cart_content .cart_prod').length);

		var slider = new Fx.Slide ($$('#cart_content .cart_prod')[last_index-1].getElement('.cart_prod_2'), {
			transition: Fx.Transitions.Quad.easeOut,
			duration: 700,
			onComplete: function () {
				this.moving_busy = false;
			}.bind (this)
		});
		
		if (this.empty.getStyle('display') == 'none') {
			slider.hide();
			product.setStyle('display', 'block');
			slider.slideIn();	
		}
		this.prod_count++;	
		
		this.update_total_price.pass(response.total_price).run();
		
	},
	
//--- Usuwanie z koszyka ----//
// uruchamiane z poziomu widoku koszyka (nie tego po prawej stronie), ale calkowitego widoku ze szczegolami.
// wywoluje metode removeFromCart
	remove_from_cart2: function (indx) {
		var indx = new Element(indx);
		var item_to_remove = indx.getParent('.basket_product_cont');

		var index = '';
		$$('#basket .basket_product_cont').each(function(elem, i){
		
			if (elem == item_to_remove) {
				index = i;
			}
		})

		this.removeFromCart ('', index);
	},

//---- Usuwanie z koszyka, ale po kliknieciu usun w koszyku podrczenych po prawej stronie
	removeFromCart: function (img, index) {

		if (!this.moving_busy && !product.calculating && !this.removing_busy) {
			this.removing_busy = true

			//sprawdz czy widok koszyka jest aktywny, jesli tak to pokaz maske wczytywanie danych...
			this.set_viewcart_mask();
			
			//jesli przekazujemy parametr index to znaczy ze metoda zostala wywolana z widoku koszyka i wiemy ktory element wywalic
			if (index === '' || (!$defined(index))) {
				var elem = new Element(img);
				
				
				var elem_to_remove = img.getParent().getParent().getParent().getParent();
				
				var index;
				$$('#cart_content .cart_prod').each(function(elem, i){
				
					if (elem == elem_to_remove) {
						index = i;
					}
				})
			}
			
			var item_to_remove = $$('#cart_content .cart_prod')[index];
			
			var slider = new Fx.Slide($$('#cart_content .cart_prod')[index].getElement('.cart_prod_2'), {
				transition: Fx.Transitions.Cubic.easeOut,
				duration: 600,
				onComplete: function(){
					if (item_to_remove) {
						item_to_remove.destroy();
					}
					//jesli jest ustawiona zmienna index to znaczy ze usuwanie jest wywolywane z widoku koszyka, i nalezy odwiezyc widok
					if (index !== '') {
					
	
					}
				}.bind(this)
			});
			
			if (this.prod_count == 1) {
				this.hide_total_price();		
			}
			
			$$('#cart_content .cart_prod')[index].set('class', 'cart_prod_removing');
			slider.slideOut();
			//wyslij zadanie php do serwera aby usunac z sesji
			request_removeFromCart(index); //from request.js
			this.prod_count--;
		}	
	},
	
	setPrice: function (price, ilosc_sztuk, is_print, ilosc_miejsc, ilosc_kolorow, zdobienie) {
		
		this.price = price;	 //laczna cena
		this.is_print = is_print; //czy ze znakowaniem
		this.ilosc_sztuk = ilosc_sztuk; //ilosc zamawianych sztuk 
		this.ilosc_miejsc = ilosc_miejsc; //ilosc miejsc nadruku
		this.ilosc_kolorow = ilosc_kolorow; //ilosc kolorw nadruku
		this.zdobienie = zdobienie //wybrane zdobienie (id)

	},
	
	set_is_print: function (val) {
		this.is_print = val;
	},
	
	update_total_price: function (total) {
		var total_price_div = $('cart_total_price');
		total_price_div.getFirst('span').set('text', total);
		
		
		if (this.last_color  == '') {
			this.last_color = total_price_div.getStyle('color');
		}		

		var my_tween = new Fx.Tween(total_price_div,{
			transition: Fx.Transitions.Quad.easeOut,
			duration: 400,
			onComplete: function () {
				total_price_div.set('tween', {
					transition: Fx.Transitions.Quad.easeIn,
					duration: 500					
				}).tween ('color', this.last_color);
			}
		})
		my_tween.start('color', '#FFDD3F');
	},
	
	
	clear_cart: function () {
		//wywolaj zaadnie do serwera i wyrzuc wszystko z koszyka zapisanego do sesji
		//request_clear_cart();		
		
		if (!this.moving_busy && !product.calculating && !this.removing_busy) {
			this.removing_busy = true;			
			
			//dla wszystkich produktow w koszykuj wykonaj metode slideOut czyli chowamy je, a pozniej obiekty usuwamy z drzewa html
			var products = $$('#cart_prod_cont .cart_prod');
			products.each(function (item, i) {
				new Fx.Slide(item, {
					onComplete: function(){
						item = item.getParent()
						if (item) {
							item.destroy();
						}
					
					}
				}).slideOut();
			})	
			
			//ukryj laczna kwote zamowienia
			this.hide_total_price();	
			this.prod_count = 0;
		}		
	},
	
//sprawdz czy widok koszyka jest aktywny, jesli tak to pokaz maske wczytywanie danych...
	set_viewcart_mask: function () {
		var cart_cont = $('cart' + '_' + 'show' + '_' + 1);
		if (cart_cont) {
		
			if (cart_cont.getStyle('display') == "block") {
				cart_cont.set('html', '&nbsp;');
				product.fadeCoverIn()
				$('product_loader').setStyle('visibility', 'visible');//pokaz loader
			}
		}		
	},
	
//ukrywa laczna wartosc zamowienia kiedy koszyk jest pusty	
	hide_total_price: function () {
		this.total_price_slide.onComplete = function(){
			this.total_price.setStyle('display', 'none');
			this.total_price_slide.onComplete = $empty;
			
			this.empty.setStyle('display', 'block');
			this.empty_slide.onComplete = $empty;
			this.empty_slide.slideIn();
		}.bind(this)			
		this.total_price_slide.slideOut()			
	},
	
// Przelicza caly koszyk w zaleznosci od podanej ilosci sztuk i zaproponowanych rabatow	
	przelicz: function () {
		przelicz_request ();
	},
	
	update_cart_prices: function (res) {

		var products = $('cart_prod_cont').getElements('.cart_prod_2');
		products.each (function (item, i) {
			var amount = item.getFirst ('.cart_unit').getFirst('strong');
			amount.set('html', res.root[i].amount);
			
			var price = item.getFirst ('.cart_price').getFirst('strong');
			price.set('html', res.root[i].price_formated);
		})
		this.update_total_price(res.total)
		//console.profileEnd();
	},
	
	
//zloz zapytanie
	make_order: function () {
		this.realization_date = $('date').value;
		request_view('cart', 'show', 1, 2);
	}, 
	
	
//wslij zapytanie
	send_query: function (order_now) {
		//sprawdz czy na liscie jest wybrany jakis handlowiec
		var handlowiec = $('form_order').handlowiec.value;
		//var email = $('form_order').email.value;
		var tresc = $('tresc').value;
		var comments = $('comments').value;
		if (!handlowiec) {
			this.msg_silde.slideIn();
			return false;
		} else {
			this.msg_silde.slideOut();
			request_sendQuery(this.realization_date, handlowiec,order_now,'',tresc,comments);
		}
		
	},
	
	set_order_refresh: function () {
		var order_history;
		if($defined($('orders_history_1'))) {
			order_history = $('orders_history_1');
			
			order_history.set('class', 'product_list refresh')
		}
	},
	
	create_html: function (host, id) {
		var url = host + 'pdf/generate_html/';
		var tmp = [];
		id.each(function(item,i){
			tmp.push(item.value);
		});
		
		url += tmp.join(',');
		window.open (url, '_blank', 'width=900,height=800,scrollbars=yes');
	},
	
	save_offer: function (id) {
		var tmp = [];
		id.each(function(item,i){
			tmp.push(item.value);
		});
		var req = new Request.JSON({
			url: 'pdf/save_offer',
			onSuccess: function(data) {
				$('link_to_offer').set('html', 'Oferta została wysłana');
			}
		}).post({
			data: JSON.encode(tmp),
			dla: $('offer-for').value,
			na_rece: $('offer-hands').value,
			dotyczy: $('offer-dotyczy').value,
			sztuk: $('sztuk').value,
			termin: $('termin').value,
			waznosc: $('waznosc').value,
			charakterystyka: $('charakterystyka').value,
			email: $('offer-email').value,
			telefon: $('offer-phone').value
		});
	},
	
	accept_offer: function (id, val) {
		var req = new Request.JSON({
			url: 'pdf/accept_offer',
			onSuccess: function(data) {
				if( val == 1 )
					$('accept-box').set('html', 'Oferta zaakceptowana');
				if( val == -1 )
					$('accept-box').set('html', 'Oferta odrzucona');
		}
		}).post({
			id: id,
			val: val
		});
	},
	
	create_pdf: function (host, id, offert) {
		var url =  host + 'pdf/generate_pdf/';
		var tmp = [];
		id.each(function(item,i){
			tmp.push(item.value);
		});
		
		url += tmp.join(',');
		
		if (offert)		 {
			url += '2';
			
			//pobierz wszystkie dane do wypelnienia
			var params = this.get_offert_param();
			if (!params) 
				return false;

		}

		window.open (url, '_blank')
	},
	
	create_doc: function (host, id, offert) {
		var url =  host + 'pdf/generate_word/';
		var tmp = [];
		id.each(function(item,i){
			tmp.push(item.value);
		});
		
		url += tmp.join(',');
		if (offert)		 {
			url += '2';
		}

		window.open (url, '_blank')		
	},
	
	set_offert_send_action: function (url, html, id) {
		
		
		
		this.oForm = $('offert_form');
		
		var tmp = [];
		id.each(function(item,i){
			tmp.push(item.value);
		});
		
		url += tmp.join(',');
		
		this.oForm.onsubmit = function () {
			if (html == 1) {
				window.open (url, this.target, 'width=750,height=800,scrollbars=yes,menubar=yes');
				return true;
			} else {
				window.open (url, this.target);
				return true;				
			}
		}
		this.oForm.action = url;
	
	},
	
	validate_offert_params: function (offert_params){
		var success = true;
	/*	if (!this.oForm) {
			this.oForm = $('offert_form');
		}

		//dla kogo		
		if (this.oForm.o_for_who.value.trim() == '') {
			//alert(this.oForm.getElements('input')[0])
			this.oForm.getElements('input')[0].highlight();			
			success = false;
		}	

		//na rece		
		if (this.oForm.o_hands.value.trim() == '') {
			this.oForm.getElements('input')[1].highlight();
			success = false;			
		}	
		
		//dotyczy		
		if (this.oForm.o_dotyczy.value.trim() == '') {
			this.oForm.getElements('input')[2].highlight();
			success = false;			
		}	*/	
		
	/*	//termin
		if (this.oForm.o_termin.value.trim() == '') {
			this.oForm.o_termin.highlight();
			success = false;			
		}
		
		//ceny_sztuki
		if (this.oForm.o_ceny_sztuki.value.trim() == '') {
			this.oForm.o_ceny_sztuki.highlight();
			success = false;			
		}	
		
		//platnosc
		if (this.oForm.o_platnosc.value.trim() == '') {
			this.oForm.o_platnosc.highlight();
			success = false;			
		}	
		
		//transport
		if (this.oForm.o_transport.value.trim() == '') {
			this.oForm.o_transport.highlight();
			success = false;			
		}	
		
		//waznosc
		if (this.oForm.o_waznosc.value.trim() == '') {
			this.oForm.o_waznosc.highlight();
			success = false;			
		}							*/			
				
		return success;
	},
	
	set_overlay: function (n) {
		var height = 800 + Math.ceil(n / 2) * 160;
		this.overlay.setHeight(height);
	}
})



