var total_price = 0;

window.addEvent('domready', function () {
	
	// (1) Nadaj wszystkich linkon <a href=""> onfocus="blur()
	$$('a').each (function (item) {
		item.addEvent('focus', function () {
			item.blur();
		});
	})	
	
	
	// (2) Input buttony - wyzeruj wartosci po kliknieciu
	if ($chk(login = $('user_login'))) {
		login.addEvents({
			click: function () {
				if (login.value == 'twój login')
					login.value = ''
			},
			blur: function () {
				if (login.value == '')
					login.value = 'twój login'
			}
		})
	}
	
	if ($chk(ns_input = $('newsletter_email'))) {
		ns_input.addEvents({
			click: function () {
				if (ns_input.value == 'adres email')
					ns_input.value = ''
			},
			blur: function () {
				if (ns_input.value == '')
					ns_input.value = 'adres email'
			}
		})
	}	
	
//--------------------------------------------------------//		
//------------     GALERIA MILKBOX     -------------------//
//--------------------------------------------------------//	
	try {
		milkbox.changeOptions({
			resizeTransition: 'quart:out',
			resizeDuration: 700
		
		});
		
		$$('.thumb_photo"').each (function (item) {
			item.setStyle('opacity', .6);
			
			item.addEvent('mouseover', function (event) {
				item.fade('1');
				event.preventDefault();
			})
			item.addEvent('mouseout', function (event) {
				item.fade('.6');
				event.preventDefault();
			})			
		})
	} catch (e) {}		
	
	// (4) Stworz efekt milkBox dla wszystkich elementow <a> zawierajacym w srodku <img /> w tresci podstrony
	/*var body_content = $('body_content');
	if ($chk(body_content)) {
		var links = body_content.getElements('a');
		if ($chk(links)){
			links.each(function(item) {
				if ($chk(item.getFirst('img'))) {
					if (!item.getProperty('rel'))
						item.setProperty('rel', 'milkbox');
				}
			})
			milkbox.reloadGalleries();

		}
	}*/
	
	
	
})


function init_tips() {

		var Tips2 = new Tips(('.tips'), {
			showDelay: 500,
			onShow: function(tip, el){
				tip.fade('in')
			},
			onHide: function(tip, el){
				tip.fade('out')
			}
			
		});
} 


// (5) Wysylanie formularza w 1 kroku
function submit_order1 (value) {
	var login_method = $('login_method');
	var order_form = $('order_form');
	
	if ($chk(login_method) && $chk(order_form)) {
		login_method.value = value
		order_form.submit();
	}
}



init_bookmarks = function () {
	var bookmarks = $('zakladki').getElements('.bookmark');
	var contents = $('zakladki').getElements('.bookmark_content');
	
	bookmarks.each(function(item, i) {		
		item.addEvent('click', function () {
			// (1) Zmien klase wszystkie zakladek
			bookmarks.each(function(item, i) {
				item.removeClass('active')
			})					
			
			// (2) Ustaw aktywna zakladke
			item.addClass('active');
			
			// (3) Ukryj wszystkie zawartosci, boxy,tresci
			contents.each(function(item, i) {
				item.setStyle('display', 'none');
			})		
			
			// (4) Pokaz wybrana tresc
			contents[i].setStyle('display', 'block');
		})		

	})
	
}


/******** NOTES EVENTS *********/

window.addEvent('load', function() {
	var checked = false;
	var note = false;
	if( $$('.new-note') ) {
		$$('.new-note').addEvent('click', function() {
			var id = this.getProperty('id').substr(4,1);
			checked = true;
			$('hidden-note').value = id;
			note = id;
		});
		$$('.new-note').addEvent('mouseenter', function() {
			$$('.new-note').setStyle('background-position', 'top')
			var id = this.getProperty('id').substr(4,1);
			for( i = id ; i > 0 ; i-- )
				$('note' + i).setStyle('background-position', 'bottom');
		});
		$$('.new-note').addEvent('mouseleave', function() {
			$$('.new-note').setStyle('background-position', 'top');
			if( note )
				for( i = note ; i > 0 ; i-- )
					$('note' + i).setStyle('background-position', 'bottom');
		});
	}
	
	if ($('registration_panel')) {
		var form = new FormCheck('registration_panel', {
			display : {
				showErrors : 1,
				titlesInsteadNames : 1,
				errorsLocation : 1,
				indicateErrors : 1,
				indicateErrorsInit : 0,
				keepFocusOnError : 0,
				checkValueIfEmpty : 1,
				addClassErrorToField : 1,
				removeClassErrorOnTipClosure : 1,
				fixPngForIe : 1,
				replaceTipsEffect : 1,

				closeTipsButton : 1,
				tipsPosition : "right",
				tipsOffsetX : -45,
				tipsOffsetY : 0,
				listErrorsAtTop : false,
				scrollToFirst : true,
				fadeDuration : 300
			}
		});			
	}
	
	if ($('koszyk')) {
		var form = new FormCheck('koszyk', {
			display : {
				showErrors : 1,
				titlesInsteadNames : 1,
				errorsLocation : 1,
				indicateErrors : 1,
				indicateErrorsInit : 0,
				keepFocusOnError : 0,
				checkValueIfEmpty : 1,
				addClassErrorToField : 1,
				removeClassErrorOnTipClosure : 1,
				fixPngForIe : 1,
				replaceTipsEffect : 1,
				closeTipsButton : 1,
				tipsPosition : "right",
				tipsOffsetX : -45,
				tipsOffsetY : 0,
				listErrorsAtTop : false,
				scrollToFirst : true,
				fadeDuration : 300
			}
		});
		
		if( $('step3-send') ) {
			$('step3-send').addEvent('click',function() {
				form.onSubmit();
			});
		}
	}
	
	if( $('delivery-address') ) {
		
		$('delivery-address').addEvent('click',function() {
			this.checked ? $('delivery-address-box').removeClass('hidden') : $('delivery-address-box').addClass('hidden');
			if( this.checked ) {
				$('address_name').addClass("validate['required']");
				$('address_street').addClass("validate['required']");
				$('address_city').addClass("validate['required']");
				$('address_zip').addClass("validate['required','kod']");
				$('address_phone').addClass("validate['required']");
				form.register( $('address_name'), 10 );
				form.register( $('address_street'), 11 );
				form.register( $('address_city'), 12 );
				form.register( $('address_zip'), 13 );
				form.register( $('address_phone'), 14 );
			} else {
				form.dispose( $('address_name') );
				form.dispose( $('address_street') );
				form.dispose( $('address_city') );
				form.dispose( $('address_zip') );
				form.dispose( $('address_phone') );
			}
		});
	}
	
	if( $('gift_text') ) {
		$('gift_text').addEvent('click',function() {
			this.checked ? $('gift-text-box').removeClass('hidden') : $('gift-text-box').addClass('hidden');
		});
	}

	if( $('company') ) {
		$('company').addEvent('change',function() {
			this.value == 1 || this.value == 2 ? $('company-box').removeClass('hidden') : $('company-box').addClass('hidden');
			if( this.value == 1 || this.value == 2) {
				form.register( $('company_name') );
				form.register( $('nip') );
				$('nip').setStyle('color', '#C3C3C3');
			} else {
				form.dispose( $('company_name') );
				form.dispose( $('nip') );
			}
		});
	}

	if( $('company') && $('nip') ) {
		$('nip').addEvent('click',function() {
			this.setStyle('color', '#242728');
		});
	}
	
	if( $('total-with-delivery') ) {
		
		function getPrice(number, decimals, dec_point, thousands_sep) {
			decimals = Math.abs(decimals) + 1 ? decimals : 2;
			dec_point = dec_point || '.';
			thousands_sep = thousands_sep || ',';
			var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(number) ? 0 : number) + ''); // returns matches[1] as sign, matches[2] as numbers and matches[3] as decimals
			var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
			return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) +
			(decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
		}
		
		$$('input[name=delivery_type]').removeProperty('disabled');
		$$('input[name=delivery_type]').addEvent('click',function() {
			new Request.JSON({
				//url: 'order/getDeliveryCost',
				url: 'order/getDeliveryCostByCost',
				onSuccess: function( res ) {
					var sum = parseFloat(total_price) + parseFloat(res.price);
					$('total-with-delivery').set('html', getPrice(sum, 2, '.', ' ') );
				}
			}).post({
				id: this.value
			})
		});
	}
	
	
	/**
	 * Payment Form
	 */
	
	var formCheckConfig = {
		submit: false,
		submitByAjax: false,
		flashTips: 1,
		display: {
			errorLocation: 1, 
			indicateErrors: 1, 
			showErrors: 1,
			addClassErrorToField: 1,
			titlesInsteadNames: true,
			fadeDuration: 0,
			scrollToFirst: true
		}
	};
	
	var spinnerImg = new Element('img', {
		src: 'media/images/ajax-loader.gif'
	});

	var spinnerOptions = {message: 'Proszę czekać', img: spinnerImg };
	
	if( $('payment-form') ) {
		formCheck = new FormCheck($('payment-form'), formCheckConfig);
		$('payment-form').addEvent('submit',function() { return false; });
		$('send-payment').addEvent('click',function() {
			var id = $('payment-form').getProperty('action');
//			if (!formCheck.isFormValid()) {
//				formCheck.validations.each(function(item,i) {
//					if (item.errors[0] != undefined) {
//						formCheck.addError(item);
//					}
//				});
//				return false;
//			}
			var req = new Request.JSON({
					url: 'payment_online/getForm',
					useSpinner: true,
					update: $(document.body),
					spinnerOptions: spinnerOptions,
					onSuccess: function(data){
						var type = $$('input[name=type]:checked').map(function(e){return e.value;});
						var form = $('go-to-payment');
						data.each(function(item,i){
							item = item.split('|');
							form.adopt(new Element('input', {'type':'hidden', 'name': item[0], 'value': decodeURIComponent(item[1])}));
						});
						form.adopt(new Element('input', {'type':'hidden', 'name': 'pay_type', 'value': type}));
						form.submit();
						return false;
					}
				}).send({
					method: 'post',
					data: {
						id: id
					}
				});
		});
	}
	
});
