jQuery.fn.extend({
	sumValues: function() {
		var sum = 0;
		this.each(function() {
			sum += parseFloat( $(this).val() );
		});
		return sum;
	}
});
jQuery.fn.addHidden = function (name, value) {
    return this.each(function () {
        var input = $("<input>").attr("type", "hidden").attr("name", name).val(value);
        $(this).append($(input));
    });
};

/* dafaults validate plugin */
$.validator.setDefaults({
	//submitHandler: function() { alert("Submitted!") },
	errorClass: "validation-error",
	validClass: "validation-ok",
	onfocusout: false,
	onkeyup: false,
	onclick: false,
	errorPlacement: function(error, element){},
	showErrors: function(errorMap, errorList){
		if (this.numberOfInvalids() > 0)
		{
			var message_text = '<div class="colorbox_message"><h1>' + lang_validate_correct_error + '</h1><p>' + errorList[0].message + '</p></div>'; $.colorbox({html: message_text});
		}
		this.defaultShowErrors();
	},
	ignore: []
});

validate_settings = {
	required: lang_validate_required,
	remote: lang_validate_remote,
	email: lang_validate_email,
	url: lang_validate_url,
	date: lang_validate_date,
	dateISO: lang_validate_dateISO,
	number: lang_validate_number,
	digits: lang_validate_digits,
	creditcard: lang_validate_creditcard,
	equalTo: lang_validate_equalTo,
	accept: lang_validate_accept,
	maxlength: jQuery.validator.format(lang_validate_maxlength),
	minlength: jQuery.validator.format(lang_validate_minlength),
	rangelength: jQuery.validator.format(lang_validate_rangelength),
	range: jQuery.validator.format(lang_validate_range),
	max: jQuery.validator.format(lang_validate_max),
	min: jQuery.validator.format(lang_validate_min)
}

$.extend(jQuery.validator.messages, validate_settings);

/* cb_settings - standardowe ustawienia */
cb_settings = {
	maxHeight:'90%',
	maxWidth:'90%',
	slideshowStart: lang_cb_slideshowStart,
	slideshowStop: lang_cb_slideshowStop,
	current: lang_cb_current,
	previous: lang_cb_previous,
	next: lang_cb_next,
	close: lang_cb_close,
	scrolling: false
}

$.extend(jQuery.colorbox.settings, cb_settings);


/**Tooltip add from jQuery UI*/
$(function() {
	$( '.tTip' ).tooltip({
		position: {
			my: "left-60 bottom-5",
			at: "center top",
			using: function( position, feedback ) {
				$( this ).css( position )
				.append("<div class='top'>")
				.append("<div class='bottom'>");
			}
		},
		content: function(){
			var element = $( this );
			return element.attr( "title" ).replace( '\x0A', '<br/>' );
		},			
		hide: { duration: 0 }
	});
});

function autosubmit(e)
{ $(e).closest('form').trigger("submit"); }

document.global_data = new Array();
function window_call(type_name, data)
{
	document.global_data[type_name] = data;
	$(document).trigger('event_'+type_name);
}

$(document).ready(function() {
	$("form#filter select.multiselect, form#filter-slider select.multiselect").multiselect({checkAllText: lang_Multiselect_all, uncheckAllText: lang_Multiselect_none, noneSelectedText: lang_Multiselect_not_selected, selectedList: 1, selectedText: lang_Multiselect_selected});

	$('form#filter .filter_attribute_slider').each(function(){
		var iOptions = $(this).find('ul li').length;
		var oContainer = this;
		var iFrom = false;
		var iTo = false;
		var i = 1;
		$(oContainer).find('ul li').each(function(){
			if( $(this).find('input').is('[checked]') ){
				if( iFrom == false )
					iFrom = i;
				iTo = i;
			}
			i++;
		});
		$(this).find('.slider').slider({
			min: 1,
			max: iOptions,
			range: $(oContainer).is( '.range' ),
			slide: function( event, ui ){
								var i = 1;
								var sFirst = '';
								var sLast = '';
								$(oContainer).find('ul li input').each(function(){
									if( ( !$(oContainer).is( '.range' ) && i == ui.value ) || ( $(oContainer).is( '.range' ) && i <= ui.values[1] && i >= ui.values[0] ) ){
										$(this).prop( 'checked', true );
										sLast = $(this).parents('label').find('span').html();
										if( sFirst == '' ){
											sFirst = sLast;
										}
									}
									else{ $(this).removeAttr( 'checked', '' ); }
									i++;
								});
								if( $(oContainer).is( '.range' ) ){
									$(oContainer).find('.val').html( sFirst + ' - ' + sLast );
								} else{
									$(oContainer).find('.val').html( sFirst );
								}
							}
		});
		if( $(oContainer).is( '.range' ) ){
			$(this).find('.slider').slider('option', 'values', [ iFrom, iTo ]);
		} else{
			$(this).find('.slider').slider('option', 'value', iFrom);
		}
		$(oContainer).find('.val').css( 'display', 'block' );
		$(oContainer).find('ul').css( 'display', 'none' );
	});
	
	$('form#filter .filter_attribute_slider_special').each(function(){
		var iMin = 100000000;
		var iMax = 1;
		
		$(this).find('ul li').each(function(){
			var vals = $(this).find('span').html().split('-');
			if( vals[0] < iMin ){
				iMin = vals[0];
			}
			if( vals[1] > iMax ){
				iMax = vals[1];
			}
		});
		
		var oContainer = this;
		$(this).find('.slider').slider({
			min: 1,
			max: iMax - iMin + 1,
			range: false,
			slide: function( event, ui ){
								$(oContainer).find('ul li input').each(function(){
									var vals = $(this).parents('label').find('span').html().split('-');
									if( ui.value + parseInt( iMin ) - 1 >= vals[0] && ui.value + parseInt( iMin ) - 1 <= vals[1] ){
										$(this).prop( 'checked', true );
									} else{
										$(this).removeAttr( 'checked', '' );
									}
								});
								$(oContainer).find('.val').html( parseInt( ui.value ) + parseInt( iMin ) - 1 );
							}
		});
		$(oContainer).find('.val').css( 'display', 'block' );
		$(oContainer).find('ul').css( 'display', 'none' );
	});
	
	$("form#filter > ul li ul li.value-hidden").hide();
	$("form#filter > ul > li").each(function(){
		if($(this).find('ul li.value-hidden').length > 0){
			$(this).find('ul').after('<a href="#" class="filter-values show" rel="nofollow">' + lang_hide_show_values + '</a>');
		}
	});
	$('form#filter a.filter-values').on('click', function(e){
		e.preventDefault();
		if($(this).is('.show')){
			$(this).parent().find("ul li.value-hidden").show('fast');
			$(this).removeClass('show').addClass('hide');
		} else{
			$(this).parent().find("ul li.value-hidden").hide('fast');
			$(this).removeClass('hide').addClass('show');
		}
	});
	
	$("form#filter > ul li.attribute-hidden").hide();
	if($("form#filter > ul li.attribute-hidden").length > 0){
		$("form#filter > ul").after('<a href="#" class="filter-attribs show" rel="nofollow">' + lang_hide_show_attribs + '</a>');
	}
	$('form#filter a.filter-attribs').on('click', function(e){
		e.preventDefault();
		if($(this).is('.show')){
			$("form#filter > ul li.attribute-hidden").show('fast');
			$(this).removeClass('show').addClass('hide');
		} else{
			$("form#filter > ul li.attribute-hidden").hide('fast');
			$(this).removeClass('hide').addClass('show');
		}
	});


	$('.products-per-page').bind('change', function(e){autosubmit(this)});
	$('.products-sort').bind('change', function(e){autosubmit(this)});

	/*    */
	/* inicjalizacja standardowych skryptów bibliotek i wtyczek  */
	/*    */

	/* obsługa colorbox */
	$('.images-gallery a').colorbox();
	$('.images-list a').colorbox();
	$('a.photo').colorbox();

	//Ukrywanie miniaturek, jeśli dostępne jest tylko jedno zdjęcie produktu
	$('#gallery_list').each(function(){
		if( $(this).children().length <= 1 ){
			$(this).css( 'display', 'none' );
		}
	});

	/* obsługa star-rate */
	$('#products-comment #rating-wrapper').stars({ inputType: "select" });

	/* obsługa zakładek produktów */
	$('#product-tabs').libTabs({animate: true});
	$('#product-tabs div.tab').bind('afterTabChanged',function(){
		$(this).find('.recaptcha_widget').each(function(){
			recaptcha_on('#'+$(this).attr('id'));
		});
	});

	$('#product-ask-button').colorbox({inline:true, href:"#product-ask", width: '400px'});
	$('#product-error-button').colorbox({inline:true, href:"#product-error", width: '400px'});
	$('#product-negotiate-button').colorbox({inline:true, href:"#product-negotiate", width: '400px'});
	$('a.products_avail_newsletter').colorbox({
		inline:true,
		href:"#product-avail-newsletter",
		width: '400px',
		onComplete: function(){
			var param = $(this).attr('href');
			if( param.match( /#iProductVariant=[0-9]+/ ) ){
				$('#product-avail-newsletter input[name="iProductVariant"]').val( param.replace( '#iProductVariant=', '' ) );
			}
			else{
				$('#product-avail-newsletter input[name="iProductVariant"]').val( '' );
			}
		}
	});

	$('#zagiel-button').colorbox({iframe:true, width: '880', height: '90%', scrolling:true});
	$('#box_zagiel a').click(function(e){e.preventDefault(); window.open($(this).prop('href'));});//colorbox({iframe:true, width: '800', height: '90%'});

	/* social link */
	$('#fb-share').prop('target','_blank').click(function(){
		window.open($(this).prop('href'),'mywindow','width=600,height=400');
		return false;
	});
	$('#twitter-share').prop('target','_blank').click(function(){
		window.open($(this).prop('href'),'mywindow','width=600,height=400');
		return false;
	});
	$('#nk-share').prop('target','_blank');
	$('#blip-share').prop('target','_blank');

	/* obsługa zakładek product-related i highlighted_list_photo */
	/* przygotowanie - przeniesienie zdjęć poza listę */
	$('#product .product-related ul, #content .hl_list_photo ul').each(function(){
		var list = $(this);
		var photos = $(this).find('li .photo, li .nophoto');
		photos.each(function(){
			var photo = $(this).detach();
			photo.insertAfter(list);
		});
	});
	/* obsługa zakładek po zmodyfikowaiu listy */
	$('#content .product-related').libTabs({hoverSwitch: true, activeList: true, activeAnchor : false, click: false});
	$('#content .hl_list_photo .product-highlighted').libTabs({hoverSwitch: true, activeList: true, activeAnchor : false, click: false});

	/*    */
	/*    */
	/* skrypty własne */
	/*    */
	/*    */

	/*    */
	/* obsługa porównywarki */
	/*    */

	var compare_cookie_name = c_prefix+'_compare';

	$('.compare-show a').prop('target','_blank').click(function(){
		window.open($(this).prop('href'),'mywindow','width=900,height=800,scrollbars=1');
		return false;
	});

	$('#compare a.delete-all').each(function(){
		var item = this;
		$(item).click(function(){
			$.setCookie(compare_cookie_name,'[]');
			window.opener.location.reload( true );
			window.close();
			return false;
		});
	});

	$('a.delete-all').each(function(){
		var item = this;
		$(item).click(function(){
			$.setCookie(compare_cookie_name,'[]');
			location.reload( true );
			return false;
		});
	});

	$('#compare a.delete').each(function(){
		var item = this;
		item.pid = $(item).parent('td').prop('class').split('-')[1];
		item.pclass = $(item).parent('td').prop('class');

		$(item).click(function(){
			// usunięcie produktu
			var products_json = $.getCookie(compare_cookie_name);
			products = products_json;
			if (products.indexOf(item.pid) != -1)
			{ products.splice(products.indexOf(item.pid),1); }

			products_json = $.toJSON(products);
			$.setCookie(compare_cookie_name,products_json);

			$('#compare .'+item.pclass).hide();

			return false;
		});
	});

	$('#page .products').each(function(){
		var list = this;
		list.products = $(list).find('li, tbody tr');
		$(list.products).each(function(){
			var product = this;
			product.pid = $(product).prop('id').split("_")[2];
			product.compareButton = $(product).find('.compare input');
			product.compareIn = $(product.compareButton).is(':checked');
			$(product.compareButton).change(function(){
				//akcje dodania/usuniecia
				var products;
				var products_json = $.getCookie(compare_cookie_name);
				if ((products_json == null) || (products_json == ''))
				{
					products = new Array();
				}
				else
				{
					products = products_json;
				}

				if(product.compareIn)
				{
					//usunięcie
					if (products.indexOf(product.pid) != -1)
					{ products.splice(products.indexOf(product.pid),1); }

				}
				else
				{
					//dodanie
					if (products.indexOf(product.pid) == -1)
					{ products.push(product.pid); }

				}
				products_json = $.toJSON(products);
				$.setCookie(compare_cookie_name,products_json);

				product.compareIn = $(product.compareButton).is(':checked');
			});


		});



	});


	/*    */
	/* paczkomaty */
	/*    */

	/* okno na etapie zamówienia */
	$('#paczkomaty #paczkomaty-button').colorbox({iframe:true, width: '800', height: '300'});


	$('#order .order-delivery #paczkomaty').each(function(){
		var item = this;
		item.eid = $(item).prop('id');
		item.paczkomatSelected_item = $('#paczkomaty-selected').get(0);
		item.paczkomatSelectedValue_item = $('#paczkomaty-selected-value').get(0);
		item.paczkomatSelectedValue_item_display = $('#paczkomaty-selected-value + span').get(0);
		item.paczkomatEmpty_item = $('#paczkomaty-empty').get(0);
		item.paczkomatEmptyValue_item = $('#paczkomaty-empty-value').get(0);

		$(item).hide();

		
		if ($(item.paczkomatSelectedValue_item).val().length != 0)
		{
			$(item.paczkomatEmpty_item).hide();
			$(item.paczkomatSelected_item).show().find('input').removeAttr('disabled');
		}
		else
		{
			$(item.paczkomatSelected_item).hide().find('input').prop('disabled', true);
			$(item.paczkomatEmpty_item).show();
		}

		item.paczkomatNameUpdate = function(paczkomatName){
			if (paczkomatName != 0)
			{
				$(item.paczkomatSelectedValue_item).val(paczkomatName);
				$(item.paczkomatSelectedValue_item_display).html(paczkomatName);
				$(item.paczkomatSelected_item).show().find('input').removeAttr('disabled');
				$(item.paczkomatEmpty_item).hide();
			}
			else
			{
				$(item.paczkomatSelected_item).hide().find('input').prop('disabled', true);
				$(item.paczkomatEmpty_item).show();
			}
		};

		$(document).bind('event_'+item.eid, function(){
			item.paczkomatNameUpdate(document.global_data[item.eid]);
		});

		$('#order .order-delivery #ordered-products').bind('deliveryChange', function(event){
			$('#order-delivery input').parent().removeClass('checked');
			$('#order-delivery input:checked').parent().addClass('checked');
			var selectedItem = $('#order-delivery input:checked').get(0);
			if (paczkomatyId == selectedItem.carrier ){
				$(item).slideDown();
				$(item).find('a#paczkomaty-button').attr('href', $(item).find('a#paczkomaty-button').attr('href').replace( /paid_on_delivery=t?/, 'paid_on_delivery=' + (pobraniaId == selectedItem.payment ? 't' : '') ) );
				$(item.paczkomatSelected_item).find('input').removeAttr('disabled');
				item.paczkomatNameUpdate($('#paczkomaty-selected-value').val());
			} else{
				$(item).slideUp(); $(item.paczkomatSelected_item).find('input').prop('disabled', true);
			}
		});
	});

	$('.order-paczkomaty #paczkomaty-nearest-submit').each(function(){
		this.send = function(){
			var paczkomat = $('#paczkomaty-nearest-select').val();
			window.parent.window_call(request_type, paczkomat);
			window.parent.$.colorbox.close();
			return false;
		};
	});

	$('.order-paczkomaty #paczkomaty-intown-submit').each(function(){
		this.send = function(){
			var paczkomat = $('#paczkomaty-intown-select').val();
			window.parent.window_call(request_type, paczkomat);
			window.parent.$.colorbox.close();
			return false;
		};
	});

	$('.order-paczkomaty #order-paczkomaty-intown').each(function(){
		var item = this;

		item.town_item = $(item).find('#paczkomaty-town-select').get(0);
		item.intown_item = $(item).find('#paczkomaty-intown-select').get(0);



		$(item.town_item).change(function(){

			tval = $(item.town_item).val();
			if (tval.length != 0)
			{
				$(item.intown_item).prop("disabled", true);
				$(item.intown_item).empty();
				$.ajax({
					url: "index.php?p=paczkomaty-in_town&town="+encodeURI(tval),
					success: function(data){
						ddata = $.parseJSON(data);
						$(ddata).each(function(){
							var data_item = this;
							data_item.op = wrapSelectOption(data_item.name,data_item.id+": "+data_item.name);
							$(item.intown_item).append(data_item.op);
						});

						$(item.intown_item).prop("disabled", false);

					}
				});
			}
			else
			{
				$(item.intown_item).prop("disabled", true);
				$(item.intown_item).empty();
				var op = wrapSelectOption('-','');
				$(item.intown_item).append(op);
			}


		});

		$(item.town_item).trigger('change');

	});






	/*    */
	/* obsługa wczytywania atrybutów produktu przy dodawaniu do koszyka */
	/*    */

	function wrapSelectOption(text, value)
	{	var item = '<option value="'+value+'">'+text+'</option>'
		return item;
	}

	var basketForm = $('#product form#basket');
	var basketSelectList = basketForm.find('select');
	var def_price = $('#product #order .price.gross > .value').html();
	var def_price_old = $('#product #order .price.gross > .old .value').html();
	var def_price_catalog = $('#product #order .price.gross > .catalog .value').html();
	var def_price_netto = $('#product #order .price.netto > .value').html();
	var def_price_old_netto = $('#product #order .price.netto > .old .value').html();
	var def_price_catalog_netto = $('#product #order .price.netto > .catalog .value').html();
	var def_stock_quantity = $('#product #stock-quantity .value').html();
	var def_availability = $('#product #available .value').html();

	basketSelectList.each(function(i){
		var basketSelectItem = this;
		basketSelectItem.Id = $(basketSelectItem).prop("name").match(/[^\[]*\[(\d+)\]/)[1];

		/* przypisanie następnego pola Select */
		if (basketSelectList[i+1]!=null)
		{
			basketSelectItem.NextItem = basketSelectList[i+1];
			basketSelectItem.NextItemId = $(basketSelectItem.NextItem).prop("name").match(/[^\[]*\[(\d+)\]/)[1];
		}
		else
		{
			basketSelectItem.NextItem = null;
		}

		/* akcja zmiany wyboru - wczytywanie kolejnych select */
		$(basketSelectItem).bind('change', function(e){
			if (basketSelectItem.NextItem != null &&  $.trim($(basketSelectItem).val())!=""){
				/* przypadek standardowy gdy wartości są określone i następuje wczytanie następnego select */
				basketSelectItem.NextItem.loadThis();
				$('#product #order .price.gross > .value').html(def_price);
				$('#product #order .price.gross > .old .value').html(def_price_old);
				$('#product #order .price.gross > .catalog .value').html(def_price_catalog);
				$('#product #order .price.netto > .value').html(def_price_netto);
				$('#product #order .price.netto > .old .value').html(def_price_old_netto);
				$('#product #order .price.netto > .catalog .value').html(def_price_catalog_netto);
				$('#product #stock-quantity .value').html(def_stock_quantity);
				$('#product #available .value').html(def_availability);
			} else if (basketSelectItem.NextItem == null &&  $.trim($(basketSelectItem).val())!="") {
				/* przypadek krańcowy gdy następuje wczytanie wartosci ceny, ilosci, dostawy*/
				data = basketSelectItem.data[$(basketSelectItem).val()];
				var vat = 1 + parseFloat( data.vat );
				$('#product #order .price.gross .value').html(data.price);
				$('#product #order .price.netto .value').html((data.price/vat).toFixed(2));
				if (data.price_old != undefined){
					$('#product #order .price.gross .old .value').html(data.price_old);
					$('#product #order .price.netto .old .value').html((data.price_old/vat).toFixed(2));
				}
				if (data.price_catalog != undefined){
					$('#product #order .price.gross .catalog .value').html(data.price_catalog);
					$('#product #order .price.netto .catalog .value').html((data.price_catalog/vat).toFixed(2));
				}
				$('#product #stock-quantity .value').html(data.quantity);
				$('#product #available .value').html(data.availability);
				if( data.image != undefined ){
					$('#gallery_list img[src^="upload/"][src$="/'+data.image+'"]').each(function(){
						$(this).trigger('click');
					});
				}
			} else if ($.trim($(basketSelectItem).val())=="") {
				/* przypadek gdy nastepuje reset select */
				if(basketSelectItem.NextItem != null)
				{ basketSelectItem.NextItem.disable(); }
				$('#product #order .price.gross > .value').html(def_price);
				$('#product #order .price.gross > .old .value').html(def_price_old);
				$('#product #order .price.gross > .catalog .value').html(def_price_catalog);
				$('#product #order .price.netto > .value').html(def_price_netto);
				$('#product #order .price.netto > .old .value').html(def_price_old_netto);
				$('#product #order .price.netto > .catalog .value').html(def_price_catalog_netto);
				$('#product #stock-quantity .value').html(def_stock_quantity);
				$('#product #available .value').html(def_availability);
			}
			if( $('#product #price-catalog').length > 0 && $('#product #price-catalog').html().length > 0 ){
				var discountPercent = ( 1 - ( parseFloat( $('#product #price').html() ) / parseFloat( $('#product #price-catalog').html() ) ) ) * 100;
				var discountValue = parseFloat( $('#product #price-catalog').html() ) - parseFloat( $('#product #price').html() );
				$('#price-container #discount-container #discount-percent').html(discountPercent.toFixed(0) + '%');
				$('#price-container #discount-container #discount-value').html(discountValue.toFixed(2));
				
			}
		});

		/* dezaktywacja select i nastepnych select */
		basketSelectItem.disable = function(){
			$(basketSelectItem).prop("disabled", true);
			basketSelectItem.enabled = false;
			$(basketSelectItem).empty();

			var item = wrapSelectOption(lang_Select_other_attributes, "");
			$(basketSelectItem).append(item);
			/* wyłącznie kolejnych pozycji select */
			if (basketSelectItem.NextItem != null) {
				basketSelectItem.NextItem.disable();
			}
		}

		/* aktywacja select */
		basketSelectItem.enable = function(){
			$(basketSelectItem).removeAttr("disabled");
			basketSelectItem.enabled = true;
			$(basketSelectItem).empty();
			var item = wrapSelectOption(lang_Select, "");
			$(basketSelectItem).append(item);
		}

		basketSelectItem.loadThis = function(){
			basketSelectItem.disable();
			/* wyszukanie wszystkich aktywnych select i stworzenie stringa dla JSON request */
			string = "";
			basketSelectList.each(function(){
				var item = this;
				if (item.enabled && $.trim($(item).val())!="")
				{ string = string + "&attr_val["+item.Id+"]="+$(item).val(); }
			});
			/* akcja wczytania */
			$.getJSON('index.php?p=products_json-attributes_list&id_prod='+iProduct+'&id_attr='+basketSelectItem.Id+string, function(data){
				basketSelectItem.enable();
				/* dodanie option do następnego select */
				basketSelectItem.data = new Array();
				var theOnlyValue = 0;
				$(data).each(function(){
					var item = wrapSelectOption(this.text, this.value);
					basketSelectItem.data[this.value] = this.data;
					theOnlyValue = this.value;
					$(basketSelectItem).append(item);
				});
				if( $(data).length == 1 ){
					$(basketSelectItem).val(theOnlyValue);
					$(basketSelectItem).trigger('change');
				}
			});
		}
	}); // end of basketSelectList.each()

	/* aktywacja funkcji dodawania do koszyka */
	if (basketForm.length != 0 && $(basketSelectList).length != 0)
	{
		basketSelectList[0].disable();
		basketSelectList[0].loadThis();
	}

	/*    */
	/* order-delivery - obsługa zmiany wybodu płatności i przewoźnika, przeliczanie kosztów */
	/*    */

	$(".order-delivery #ordered-products").each(function(){
		var order = this;
		var block_productCost = $('#summary-product-cost-discount');
		if( block_productCost.length == 0 )
			var block_productCost = $('#summary-product-cost');
		var block_deliveryCarrier = $('#summary-delivery-carrier');
		var block_deliveryPayment = $('#summary-delivery-payment');
		var block_deliveryCost = $('#summary-delivery-cost');
		var block_giftCost = $('#summary-gift-cost');
		var block_orderCost = $('#summary-order-cost');

		$('#order-gift-client').prop("disabled", true);
		$('#order-gift-text').prop("disabled", true);

		order.summary = parseFloat(block_orderCost.html());

		$(block_deliveryCarrier).html("-");
		$(block_deliveryPayment).html("-");
		$(block_deliveryCost).html("-");
		$(block_giftCost).html("-");

		sCarriers = $.parseJSON(sCarriers);
		aCarriers = new Array();
		$(sCarriers).each(function(){aCarriers[this.id]=this.name})
		sPayments = $.parseJSON(sPayments);
		aPayments = new Array();
		$(sPayments).each(function(){aPayments[this.id]=this.name})

		function sumOrderCost()
		{
			val_productCost = parseFloat($(block_productCost).html());
			val_productCost = isNaN(val_productCost) ? 0 : val_productCost;
			val_deliveryCost = parseFloat($(block_deliveryCost).html());
			val_deliveryCost = isNaN(val_deliveryCost) ? 0 : val_deliveryCost;
			val_giftCost = parseFloat($(block_giftCost).html());
			val_giftCost = isNaN(val_giftCost) ? 0 : val_giftCost;
			var total = val_productCost + val_deliveryCost + val_giftCost;
			order.summary = total.toFixed(2);

			$(order).trigger("summaryUpdate");

			return total;
		}

		$('#order-delivery input').each(function(){
			var button = this;
			button.carrier = $(button).val().split(";")[0];
			button.payment = $(button).val().split(";")[1];
		});


		$('#order-delivery input').change(function(){
			var button = this;
			$(block_deliveryCarrier).html(aCarriers[button.carrier]);
			$(block_deliveryPayment).html(aPayments[button.payment]);
			cost = $(button).val().split(";")[2];
			val_cost = parseFloat(cost);
			val_cost = isNaN(val_cost) ? 0 : val_cost;
			$(block_deliveryCost).html(val_cost.toFixed(2));
			block_orderCost.html(sumOrderCost().toFixed(2));

			$(order).trigger("deliveryChange");
		});

		$('#order-gift-cb').change(function(){
			if($(this).is(':checked')) {
				$(block_giftCost).html(gift_cost.toFixed(2));
				$('#order-gift-client').prop("disabled", false);
				$('#order-gift-text').prop("disabled", false);
			}
			else {
				$(block_giftCost).html("-");
				$('#order-gift-client').prop("disabled", true);
				$('#order-gift-text').prop("disabled", true);
			}

			block_orderCost.html(sumOrderCost().toFixed(2));
		});



		$(order).find('#zagiel-button').each(function(){
			var zagiel = this;
			zagiel.minPrice = zagielMinPrice;
			$(zagiel).hide(); $(zagiel).parents('p#zagiel').hide();

			$(order).bind("summaryUpdate", function(){
				if (order.summary >= zagiel.minPrice)
				{ $(zagiel).show(); $(zagiel).parents('p#zagiel').show(); $(zagiel).prop("href",zagielSymulatorHref+order.summary); }
				else
				{ $(zagiel).hide(); $(zagiel).parents('p#zagiel').hide(); }
			});
		});

		$(order).find('#LR-button').each(function(){
			var LR = this;
			$(order).bind("summaryUpdate", function(){
				{ $(LR).show(); $(LR).attr("OnClick","return LR_PoliczRate('"+order.summary+"')"); $(LR).attr("href","https://ewniosek.credit-agricole.pl/eWniosek/simulator.jsp?PARAM_TYPE=RAT&PARAM_PROFILE="+LR_psp_id+"&PARAM_CREDIT_AMOUNT=" +order.summary); }
			});
		});

		/* inicjalizacja */
		$('#order-delivery input:checked').trigger("change");
		$('#order-gift-cb').trigger("change");
	});

	/*    */
	/* order-basket - obsługa zmiany ilości produktów - przeliczanie i wysyłanie ajax */
	/*    */

	$('#basket #ordered-products table').each(function(){
		var basket = this;
		basket.form = $(this).parents('form:first');
		basket.items = $(this).find("tbody tr");
		basket.summary_field = $('#summary-cost');
		basket.summary = parseFloat($(basket.summary_field).html());
		basket.summary_bind = function(){ $(basket.summary_field).html(basket.summary); };

		basket.data = new Array();
		var data = $.parseJSON(aStockInfo);

		// iProductVariant, iStock, sOnStockText, sOutOfStockText, iInfStock

		$(data).each(function(){
			var item = this;
			basket.data[this.iProductVariant] = this;
		});

		basket.summaryUpdate = function()
		{
			var summary = 0;
			basket.items.each(function(i){
				var item = this;
				summary = (summary + parseFloat(item.summary));
			});

			basket.summary = summary.toFixed(2);
			basket.summary_bind();

			$(basket).trigger("summaryUpdateEvent");
		};

		basket.sent = false;;
		basket.submitBasket = function()
		{
			var obj = new Array;
			basket.items.each(function(i){
				var item = this;
				obj[i] = {"iProductVariant" : item.pid, "iQuantity" : item.quantity};
			});

			obj= $.toJSON(obj);
			submit_data = 'p=p_json-update_basket&sProductsJSON='+obj;

			if( ! basket.sent ){
				basket.submitBasketAjax();
			}
		};

		basket.submitBasketAjax = function(){

			$.ajax({

				url: 'index.php',
				data : submit_data,
				success: function(msg){
					//alert( "Data Saved: " + msg );
					basket.sent = false;
					if( submit_data != null )
						basket.submitBasketAjax()
				}
			});
			basket.sent = true;
			submit_data = null;
		};

		basket.items.each(function(i){
			var item = this;

			item.pid = $(item).prop("id").split("-")[1];
			item.data = basket.data[item.pid];
			item.availability_field = $(item).find('.availability')[0];
			item.del_field = $(item).find('.del a')[0];
			item.quantity_max = item.data.iStock;
			item.quantity_max_inf = (item.data.iInfStock == 1) ? true : false;
			item.quantity_min = 1;
			item.quantity_input = $(item).find(".quantity input")[0];
			item.quantity = parseInt($(item.quantity_input).val());
			item.quantity_bind = function(){ $(item.quantity_input).val(item.quantity); };

			$(item.del_field).click(function(){
				//$(item).slideUp();
				//return false;
			});

			$(item.quantity_input).focusout(function(){
					result = basket.form.valid();
					if (result)
					{
						item.quantity = parseInt($(item.quantity_input).val());
						basket.submitBasket();
					}
					else
					{ item.quantity_bind(); }


					item.statusVerify();
					item.summaryUpdate();
			});

			item.price_field = $(item).find(".price");
			item.price = parseFloat($(item.price_field).html());
			item.price_bind = function(){ $(item.price_field).val(item.price); };
			item.summary_field = $(item).find(".summary");
			item.summary = parseFloat($(item.summary_field).html());
			item.summary_bind = function(){ $(item.summary_field).html(item.summary); };
			item.del = $(item).find(".del a");

			item.plus = $(item).find(".quantity-change .plus")[0];
			item.plus.enabled = false;
			item.plus.disable = function(){
				this.enabled = false;
				$(this).addClass("disabled");
				$(this).unbind("click");
				$(this).click(function(){
					return false;
				})
			};
			item.plus.enable = function(){
				this.enabled = true;
				$(this).removeClass("disabled");
				$(this).click(function(){
					item.quantity++;
					item.quantity_bind();
					item.statusVerify();
					item.summaryUpdate();
					basket.submitBasket();
					return false;
				})

			};

			item.minus = $(item).find(".quantity-change .minus")[0];
			item.minus.enabled = false;
			item.minus.disable = function(){
				this.enabled = false;
				$(this).addClass("disabled");
				$(this).unbind("click");
				$(this).click(function(){
					return false;
				})
			};
			item.minus.enable = function(){
				this.enabled = true;
				$(this).removeClass("disabled");
				$(this).click(function(){
					basket.form.valid();
					item.quantity--;
					item.quantity_bind();
					item.statusVerify();
					item.summaryUpdate();
					basket.submitBasket();
					return false;
				})
			};

			item.statusVerify = function(){

				if (!item.quantity_max_inf && (item.quantity >= item.quantity_max))
				{
					item.plus.disable();
				}
				else if ((item.quantity_max_inf || (item.quantity <= item.quantity_max)) && !item.plus.enabled )
				{
					item.plus.enable();
				}

				if ((item.quantity <= item.quantity_min))
				{
					item.minus.disable();
				}
				else if ((item.quantity >= item.quantity_min) && !item.minus.enabled )
				{
					item.minus.enable();
				}

				item.avail = null;
				$.each( item.data.aAvailabilities, function( i, avail ){
					if( avail.iStock == 'inf' || avail.iStock >= item.quantity ){
						item.avail = avail;
						return false;
					}
				});
				if( item.avail.sAvailable.length > 0 ){
					$(item.availability_field).html(item.avail.sAvailable);
					if( item.avail.iDays > 3 ){
						$(item.availability_field).addClass('over_3_days');
					} else{
						$(item.availability_field).removeClass('over_3_days');
					}
				}

			};

			item.summaryUpdate = function(){
				item.summary = (item.price * item.quantity).toFixed(2);
				item.summary_bind();
				basket.summaryUpdate();
			};

			item.statusVerify();
			item.summaryUpdate();
		});

		var zagielList = $(basket).find('#zagiel-button');
		zagielList.each(function(){
			var zagiel = this;
			zagiel.minPrice = zagielMinPrice;
			$(zagiel).hide();

			$(basket).bind("summaryUpdateEvent", function(){
				if (basket.summary >= zagiel.minPrice)
				{
					$(zagiel).show();
					$(zagiel).prop("href",zagielSymulatorHref+basket.summary);
				}
				else
				{ $(zagiel).hide(); }
			});
		});

		var LRList = $(basket).find('#LR-button');
		LRList.each(function(){
			var LR = this;
			$(basket).bind("summaryUpdateEvent", function(){
				{ $(LR).show(); $(LR).attr("OnClick","return LR_PoliczRate('"+basket.summary+"')"); $(LR).attr("href","https://ewniosek.credit-agricole.pl/eWniosek/simulator.jsp?PARAM_TYPE=RAT&PARAM_PROFILE="+LR_psp_id+"&PARAM_CREDIT_AMOUNT=" +basket.summary); }
			});
		});

		basket.summaryUpdate();

	});

	$('form#newsletter').submit(function(e){
		e.preventDefault();
		$.post( $(this).prop('action'), $(this).serialize(), function(data){ var message_text = '<div class="colorbox_message">' + data + '</div>'; $.colorbox({html: message_text}); } );
	});

	$('html').on('submit', '#basket-fast-container form', function(e){
		e.preventDefault();
		$.post( $(this).prop('action'), $(this).serialize(), function(data){ if( $( 'input#recaptcha_response_field' ).length > 0 ) Recaptcha.reload(); var message_text = '<div class="colorbox_message"><h1>' + data + '</h1></div>'; $.colorbox({html: message_text}); } );
	});

	var message = $('#page > .cb_message, #product > .cb_message');
	message.css( 'display', 'none' );
	if( message.length > 0 ){
		message_text = message.html();
		message_text = '<div class="colorbox_message">' + message_text + '</div>';
		$.colorbox({html: message_text});
	}

	$(document).bind('event_fotolia', function(){
		$.colorbox.close();
		$( '#' + document.global_data['fotolia_cbox_info'] ).find('span.fotolia input').val( document.global_data['fotolia'].replace( 'photo-', '' ) );
	});
	
	$('#breadcrumb>span>a').click(function(e){
		e.preventDefault();
		var iPage = $(this).prop('href').replace( /^.*?,([0-9]+).*?$/, '$1' );
		var $span = $(this).parent();
		$.get('index.php?p=p_json-get_brothers&iPage='+iPage, function(data){
			$($span).append('<div class="breadcrumb-pages">'+data+'</div>');
		});
	});
	
	$('#breadcrumb > span').mouseleave(function(e){
		$(this).find('div.breadcrumb-pages').remove();
	});

	$('ul.products a.basket.direct, table.products a.basket.direct').click(function(e){
		e.preventDefault();
		var $product = $(this).closest('li, tr');
		$($product).append('<div class="blur"></div>').find('div.blur').hide().fadeIn('slow');
		$.get('index.php?p=p_json-add_to_basket&iProduct='+$(this).prop('href').replace(/^.*?iProductAdd=([0-9]+).*?$/, '$1')+'&iQuantity='+$(this).closest('li, tr').find('input.product_quantity').val(), function(data){
			$('#basket-small-container').html(data.basket_small);
			$('.update_basket_products_count').attr('value', data.iOrderProducts).html(data.iOrderProducts);
			$('.update_basket_products_summary').attr('value', data.fOrderSummary).html(data.fOrderSummary);
			$($product).find('div.blur').html(lang_basket_added).delay(2000).fadeOut('slow',function(){$(this).remove()});
		});
	});
	
	function switchStorageLink( switch_link ){
		$(switch_link).toggleClass( 'add remove' )
			.attr( 'href', $(switch_link).attr( 'href' ).replace( /iProductStorage(Add|Remove)/, function(x){ if( x == 'iProductStorageAdd' ) return 'iProductStorageRemove'; else return 'iProductStorageAdd'; } ) )
			.attr( 'title', $(switch_link).attr( 'title' ).replace( new RegExp( lang_storage_add + '|' + lang_storage_rem, '' ), function(x){ if( x == lang_storage_add ) return lang_storage_rem; else return lang_storage_add; } ) )
			.html( $(switch_link).html().replace( new RegExp( lang_storage_add + '|' + lang_storage_rem, '' ), function(x){ if( x == lang_storage_add ) return lang_storage_rem; else return lang_storage_add; } ) );
	}
	
	$('.products a.storage').click(function(e){
		e.preventDefault();
		var storage_link = this;
		var linkinfo = $(this).attr( 'href' ).match( /iProductStorage(Add|Remove)\=([0-9]+)$/ );
		var url = '?p=p_json-';
		if( linkinfo[1] == 'Add' )
			url += 'add_to_storage';
		else
			url += 'remove_from_storage';
		url += '&iProduct=' + linkinfo[2];
		
		$.get( url, null, function(data){
			$('.update_storage_products_count').attr('value', data).html(data);
			$('a[href="' + $(storage_link).attr('href') + '"]').each( function(){ switchStorageLink( this ); } );
		});
	});

	$('#product-variants div.variant input.basket.submit').click(function(){
		var count = $(this).closest('div.variant').find('input').val();
		if( count < 1 ) count = 1;
		$(this).closest('#product-variants').find('input').val('0');
		$(this).closest('div.variant').find('input').val(count);
	});
	
	$('.product-variants-table input.basket.submit').click(function(){
		var count = $(this).closest('tr').find('input').val();
		if( count < 1 ) count = 1;
		$(this).closest('table').find('input').val('0');
		$(this).closest('tr').find('input').val(count);
	});
	
	(function() {
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
		po.src = 'https://apis.google.com/js/plusone.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	})();

	$('#cookie_main a#cookie_close').click(function(){
		$.setCookie('cookie_info_accepted', 'cookie_info_accepted', {expires : 3650});
		$('#cookie_container').animate({
			bottom: '-150'
		}, 1500, function(){
			$(this).remove();
		})
		return false;
	})
	
	if( !$.getCookie('newsletter') && $('#newsletter_colorbox').length > 0 ){
		$.colorbox({inline: true, href: '#newsletter_colorbox', overlayClose: false, escKey: false, closeButton: false});
		$(window).on("load resize", function(event){
			var iWidthColorBox = $('#newsletter_colorbox').width();
			var iHeightColorBox = $('#newsletter_colorbox').height();
			$.colorbox.resize( {width: iWidthColorBox+20, height: iHeightColorBox} );
		});
		$('#newsletter_colorbox').on('click', 'a#newsletter_not_now', function(e){
			e.preventDefault();
			$.setCookie('newsletter','1');
			$.colorbox.close();
		}).on('click', 'a#newsletter_no', function(e){
			e.preventDefault();
			$.setCookie('newsletter','1',{expires: 30});
			$.colorbox.close();
		}).on('submit', 'form', function(e){
			e.preventDefault();
			$.post( $(this).prop('action'), $(this).serialize(), function(data){ var message_text = '<div class="colorbox_message">' + data + '</div>'; $.colorbox({html: message_text}); } );
		});
	}
	
	$('#mobile-menu-link').click(function(e){
		e.preventDefault();
		$('#mobile-menu').toggleClass('hide');
		if( $('#mobile-menu').is(':visible') == false ){
			$.scrollTo(0, 800, {});
		} else{
			$.scrollTo($("#mobile-menu .selected").offset().top - 130, 800, {});
		}
	});
	
	$('#mobile-menu a.more').click(function(e){
		e.preventDefault();
		$(this).closest('li').find('>ul').slideToggle();
	});
	
	$('div.navi-actions a.top').click( function(e){
		e.preventDefault();
		$.scrollTo(0, 800, {});
	});
	
	jQuery.validator.addMethod( "nip", function( value, element ){
			if( value == '' ) return true;
			var verificator_nip = new Array(6,5,7,2,3,4,5,6,7);
			var nip = value.replace(/[\ \-]/gi, '');
			if( nip.length != 10 ){
				return false;
			} else{
				var n = 0;
				for( var i=0; i<9; i++ ){
					n += nip[i] * verificator_nip[i];
				}
				n %= 11;
				if( n != nip[9] ){
					return false;
				}
			}
			return true;	
		},
		"Proszę o podanie prawidłowego numeru NIP"
	);
	jQuery.validator.addMethod( "postalCodePL", function( value, element ){
			if( value == '' ) return true;
			return value.match(/^[0-9]{2}[\ \-]?[0-9]{3}$/);
		},
		"Proszę o podanie prawidłowego kodu pocztowego"
	);
	jQuery.validator.addMethod( "phone", function( value, element ){
			if( value == '' ) return true;
			var value = value.replace(/[\ \-]/gi, '');
			return value.match(/^[0-9]{9}$/);
		},
		"Proszę o podanie prawidłowego numeru telefonu"
	);
	
	$('a.top').click(function(e){
		e.preventDefault();
	});
	
	var searchTimeout = false;
	
	$('#search1').keyup( function(){
		if( searchTimeout ) clearTimeout( searchTimeout );
		searchTimeout = false;
		$('#search_quick').remove();
		var phrase = $(this).val();
		if( phrase.length > 2 ){
			if( searchTimeout ) clearTimeout( searchTimeout );
			searchTimeout = false;
			searchTimeout = window.setTimeout( function(){
				searchTimeout = false;
				$.get( '?p=p_json-search_quick&sPhrase=' + phrase, function( data ){
					$('#search_quick').remove();
					if( data.length > 0 ) $('#search1').after('<div id="search_quick">' + data + '</div>');
				});
			}, 1000 );
		}
	}).blur(function(){
		if( searchTimeout ) clearTimeout( searchTimeout );
		searchTimeout = false;
		window.setTimeout( function(){
			$('#search_quick').remove();
		}, 200 );
	});
	
	$( 'ul.products, #order-delivery>ul, #search-page-form, div.attributes' ).each( function(){
		var productsWidth = $( this ).innerWidth();
		if( productsWidth <= 415 ){
			$( this ).removeClass( 'resize623 resize831 resize1039 resize1247 resize1248' );
			$( this ).addClass( 'resize415' );
		}else if( productsWidth <= 623 ){
			$( this ).removeClass( 'resize415 resize831 resize1039 resize1247 resize1248' );
			$( this ).addClass( 'resize623' );
		}else if( productsWidth <= 831 ){
			$( this ).removeClass( 'resize415 resize623 resize1039 resize1247 resize1248' );
			$( this ).addClass( 'resize831' );
		}else if( productsWidth <= 1039 ){
			$( this ).removeClass( 'resize415 resize623 resize831 resize1247 resize1248' );
			$( this ).addClass( 'resize1039' );
		}else if( productsWidth <= 1247 ){
			$( this ).removeClass( 'resize415 resize623 resize831 resize1039 resize1248' );
			$( this ).addClass( 'resize1247' );
		}else{
			$( this ).removeClass( 'resize415 resize623 resize831 resize1039 resize1247' );
			$( this ).addClass( 'resize1248' );
		}
	});
	
	$( window ).resize( function(){
		$( 'ul.products, #order-delivery>ul, #search-page-form, div.attributes' ).each( function(){
			var productsWidth = $( this ).innerWidth();
			if( productsWidth <= 415 ){
				$( this ).removeClass( 'resize623 resize831 resize1039 resize1247 resize1248' );
				$( this ).addClass( 'resize415' );
			}else if( productsWidth <= 623 ){
				$( this ).removeClass( 'resize415 resize831 resize1039 resize1247 resize1248' );
				$( this ).addClass( 'resize623' );
			}else if( productsWidth <= 831 ){
				$( this ).removeClass( 'resize415 resize623 resize1039 resize1247 resize1248' );
				$( this ).addClass( 'resize831' );
			}else if( productsWidth <= 1039 ){
				$( this ).removeClass( 'resize415 resize623 resize831 resize1247 resize1248' );
				$( this ).addClass( 'resize1039' );
			}else if( productsWidth <= 1247 ){
				$( this ).removeClass( 'resize415 resize623 resize831 resize1039 resize1248' );
				$( this ).addClass( 'resize1247' );
			}else{
				$( this ).removeClass( 'resize415 resize623 resize831 resize1039 resize1247' );
				$( this ).addClass( 'resize1248' );
			}
		});
	});
	
	$( this ).scroll( function(){
		var scrollValue = $(window).scrollTop();
		if( $('.products-head').length > 0 ){
			var wrapperHeight = $('.products-head').offset().top;
			if( scrollValue > wrapperHeight ){
				$('.compare-wrapper').addClass( 'fix' ); //css( 'position', 'fixed' );
			}else{
				$('.compare-wrapper').removeClass( 'fix' ); //css( 'position', 'static' );
			}
		}
	});
	
});