/* 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)
		{ alert(lang_validate_correct_error); }
		this.defaultShowErrors();
	},
	ignore: []
});

jQuery.validator.addMethod( "maxbytes", function( value, element, maxlength ){

		//tinymce :)
		for (var i = 0; i < tinyMCE.editors.length; i++) {
			var textarea = tinyMCE.editors[i].getElement();
			var newText = tinyMCE.editors[i].getContent();      
			$(tinyMCE.editors[i].getElement()).text(newText);
		}

		value = $(element).val();
		var byteAmount = unescape(encodeURIComponent(value)).length;
		return byteAmount <= maxlength;
	},
	"Zbyt długi tekst"
);

/* delConfirm */	

$.fn.delConfirm = function(options){
	return this.dialog({
		modal: true,
		autoOpen: false,
		buttons: [
			{
				text: lang_Delete, 
				click: function() {
					if ( typeof ($('#product-delete-message').dialog.redirectHref) != undefined )
						location.href = $('#product-delete-message').dialog.redirectHref;
					$(this).dialog( "close" );
				}
			},		
			{
				text: lang_Cancel,
				click: function() {
					$(this).dialog( "close" );
				}
		
			}
		]
	});
};

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

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

function marginCount( field_base, field_dest, val ){
	if( val !== '' ){
		if( $( field_base ).val() > 0 ){
			var res = $( field_base ).val();
			if( val.indexOf( '%' ) > -1 ){
				res = parseFloat( res ) * ( 1 + parseFloat( val.replace( '%', '' ) ) / 100 );
			} else{
				res = parseFloat( res ) + parseFloat( val );
			}
			res = Math.round( res * 100 ) / 100;
			$( field_dest ).val( res ).trigger('focusout');
		}
	}
}

$(document).ready(function() {
	
	
	
	$("#confirm-box").dialog({
		autoOpen: false,
		modal: true
    });
	
	$( 'a.delete' ).on( 'click', function( e ){
		e.preventDefault();
		var targetUrl = $(this).attr('href');

		$("#confirm-box").dialog({
			buttons : {
				"Confirm" : function() {
					window.location.href = targetUrl;
				},
				"Cancel" : function() {
					$(this).dialog("close");
				}
			}
		});
	});
	
	
	

$('#value-delete-message').delConfirm();
$('#advsearcher_list .actions .value-delete').click(function(){
	$('#value-delete-message').dialog.redirectHref = $(this).prop('href');
	$('#value-delete-message').dialog( "open" );
	return false;
});

$('#column-delete-message').delConfirm();
$('#advsearcher_columns .actions .column-delete').click(function(){
	$('#column-delete-message').dialog.redirectHref = $(this).prop('href');
	$('#column-delete-message').dialog( "open" );
	return false;
});
/*
$('#fastorder-delete-message').delConfirm();
$('#fastorders .actions .fastorder-delete').click(function(){
	$('#fastorder-delete-message').dialog.redirectHref = $(this).prop('href');
	$('#fastorder-delete-message').dialog( "open" );
	return false;
});

$('#order-delete-message').delConfirm();
$('#orders .actions .order-delete').click(function(){
	$('#order-delete-message').dialog.redirectHref = $(this).prop('href');
	$('#order-delete-message').dialog( "open" );
	return false;
});

$('#page-delete-message').delConfirm();
$('#pages .actions .page-delete').click(function(){
	$('#page-delete-message').dialog.redirectHref = $(this).prop('href');
	$('#page-delete-message').dialog( "open" );
	return false;
});

$('#product-delete-message').delConfirm();
$('#products .actions .product-delete').click(function(){
	$('#product-delete-message').dialog.redirectHref = $(this).prop('href');
	$('#product-delete-message').dialog( "open" );
	return false;
});

$('#user-delete-message').delConfirm();
$('#users .actions .user-delete').click(function(){
	$('#user-delete-message').dialog.redirectHref = $(this).prop('href');
	$('#user-delete-message').dialog( "open" );
	return false;
});
*/
if( $( '#allegro_template_text' ).length > 0 ){
	var val = $( '#allegro_template_text' ).val();
	val = unescape(val) ;
	$(".preview").colorbox({width:"80%", inline:true, href:val});
}

if( $( '#ebay_template_text' ).length > 0 ){
	var val = $( '#ebay_template_text' ).val();
	val = unescape(val) ;
	$(".preview").colorbox({width:"80%", inline:true, href:val});
}

if( $( '#swistak_template_text' ).length > 0 ){
	var val = $( '#swistak_template_text' ).val();
	val = unescape(val) ;
	$(".preview").colorbox({width:"80%", inline:true, href:val});
}

$('form#banners-form #banner-color, .color').ColorPicker({
	color: $(this).val(),
	onSubmit: function(hsb, hex, rgb, el) {
		$(el).val('#'+hex);
		$(el).ColorPickerHide();
	},
	onBeforeShow: function () {
		$(this).ColorPickerSetColor(this.value);
	}
});



$('#bannerFxSelect').change(function(){
	if( $(this).find('option:selected').hasClass('onlysync') ){
		$('#bannerSyncCheck').prop('checked',true).prop('disabled',true);
	} else if( $(this).find('option:selected').hasClass('nosync') ){
		$('#bannerSyncCheck').prop('checked',false).prop('disabled',true);
	} else{
		$('#bannerSyncCheck').prop('disabled',false);
	}
}).trigger('change');
$('#bannerFxForm').submit(function(){
	$('#bannerSyncCheck').prop('disabled',false);
});

$('.continent input').click(function(e){
	$('input.' + $(this).attr('id')).prop('checked', $(this).prop('checked'));
	e.stopPropagation();
});
$('#carrier-countries').on('click', '.continent.show', function(e){
	e.preventDefault();
	$(this).removeClass( 'show' ).addClass( 'hide' ).find('.button').html(' Ukryj &#x25B2;');
	$('input.' + $(this).find('input').attr('id')).parent().show();
});
$('#carrier-countries').on('click', '.continent.hide', function(e){
	e.preventDefault();
	$(this).removeClass( 'hide' ).addClass( 'show' ).find('.button').html(' Pokaż &#x25BC;');
	$('input.' + $(this).find('input').attr('id')).parent().hide();
});
$('.continent').addClass('show').append('<span class="button"> Pokaż &#x25BC;</span>');
$('.continent').each( function(){
	$('input.' + $(this).find('input').attr('id')).parent().hide();
});

$('#discount-value').change(function(){
	if( $(this).val().match( /^[0-9]+%$/ ) ){
		$( '#producer, #coupon_producer' ).prop( 'disabled', false );
	} else{
		$( '#producer, #coupon_producer' ).prop( 'disabled', true ).val( '' );
	}
}).trigger('change');

$('#discount-coupons #select-all').click(function(){
	var sel = $(this).is(':checked');
	$('#discount-coupons tbody td.delete input').prop( 'checked', sel );
});

$('#images-list input.checkall, #files-list input.checkall').click(function(){
	var chk = $(this).is(':checked');
	$(this).closest('table').find('input.check').each(function(){
		$(this).prop('checked', chk);
	});
});
$('#images-list a.action-confirm, #files-list a.action-confirm').click(function(e){
	e.preventDefault();
	var action = $(this).closest('tr').find('select.actions').val();
	var files = $(this).closest('table').find('input.check:checked').closest('tr');
	if( action == '' ){ alert( 'Wybierz akcję' ); }
	else if( action == 'del' ){ files.each(function(){ $(this).find('.del input').prop('checked', true); $(this).hide().next('tr.hidden').hide(); }); }
	else if( match = action.match( /thumb-([0-9]+)/ ) ){ files.each(function(){ $(this).find( '.thumbS' ).val( match[1] ); }); }
	else if( match = action.match( /place-([0-9]+)/ ) ){ files.each(function(){ $(this).find( '.placeS' ).val( match[1] ); }); }
	else if( action == 'fname2desc' ){ files.each(function(){ $(this).find( '.description' ).val( $(this).find( 'span.name' ).html().replace( /\.[^\.]*$/, '' ).replace( /\_/g, ' ' ) ); }); }
});

$('#images-list tr.hidden, #files-list tr.hidden').hide();
$('#images-list a.additional, #files-list a.additional').click(function( e ){
	e.preventDefault();
	$(this).closest('tr').next('tr.hidden').toggle();
});

$('.tabbed').libTabs({wrapper: false});
$('select.multiselect').multiselect({checkAllText: lang_Multiselect_all, uncheckAllText: lang_Multiselect_none, noneSelectedText: lang_Multiselect_not_selected, selectedList: 1, selectedText: lang_Multiselect_selected});

$('#lang-select').bind('change', function(e){autosubmit(this)});

$( "#date-from" ).datepicker({
	defaultDate: "+1w",
	changeMonth: true,
	numberOfMonths: 3,
	dateFormat: 'yy-mm-dd',
	maxDate: $('#date-to').val(),
	onClose: function( selectedDate ) {
		$( "#date-to" ).datepicker( "option", "minDate", selectedDate );
	}
});
$( "#date-to" ).datepicker({
	defaultDate: "+1w",
	changeMonth: true,
	numberOfMonths: 3,
	dateFormat: 'yy-mm-dd',
	minDate: $('#date-from').val(),
	onClose: function( selectedDate ) {
		$( "#date-from" ).datepicker( "option", "maxDate", selectedDate );
	}
});
















$('#page-name').change(function(){
	$('h1 span.autochange').html( $(this).val() );
});

$('#parentpage_overwrite').change(function(){
	$('#oPageParent').val($(this).val());
});
$('#oPageParent').change(function(){
	$('#parentpage_overwrite').val($(this).val());
});

$('#iAuthorized').change(function(){
	if($(this).is(':checked')){
		$('tr.authorized').show();
	} else{
		$('tr.authorized').hide();
	}
}).trigger('change');
if( typeof tags !== 'undefined' ){
	$('#tagit-tags').tagit({
		availableTags: tags,
		singleField: true,
		allowSpaces: true,
	});
}

$('#pages .clone_quantity').change(function(){
	if( !$(this).val().match( /^[0-9]+$/ ) ){
		$(this).val( 1 );
	}
	var link = $(this).closest('tr').find('a.page-clone');
	link.attr( 'href', link.attr('href').replace( /iQuantity=[0-9]*/, 'iQuantity=' + $(this).val() ) );
});


var producerMargin = 0;
var pageMargin = 0;

if( $('#product-form').length > 0 ){
	$('#producer-select').change( function(){
		$.get( '?p=producers-get_margin&iProducer=' + $('#producer-select').val(), null, function( data ){
			producerMargin = data;
			if( producerMargin != null ){
				$('#margin-count-producer img').prop( 'title', lang_Margin_producer + ' (' + producerMargin + ')' );
				$('.margin-count-producer img').prop( 'title', lang_Margin_producer + ' (' + producerMargin + ')' );
			} else{
				$('#margin-count-producer img').prop( 'title', lang_Margin_producer + ' (0)' );
				$('.margin-count-producer img').prop( 'title', lang_Margin_producer + ' (0)' );
			}
		});
	});
	if( $('#producer-select').val() > 0 ){
		$('#producer-select').trigger('change');
	}

	$('#product-main-category').change( function(){
		$.get( '?p=p-get_margin&iPage=' + $('#product-main-category').val(), null, function( data ){
			pageMargin = data;
			if( pageMargin != null ){
				$('#margin-count-category img').prop( 'title', lang_Margin_category + ' (' + pageMargin + ')' );
				$('.margin-count-category img').prop( 'title', lang_Margin_category + ' (' + pageMargin + ')' );
			} else{
				$('#margin-count-category img').prop( 'title', lang_Margin_category + ' (0)' );
				$('.margin-count-category img').prop( 'title', lang_Margin_category + ' (0)' );
			}
		});
	});
	if( $('#product-main-category').val() > 0 ){
		$('#product-main-category').trigger('change');
	}

	$('#sMargin').change(function(){
		if( $(this).val() != null && $(this).val() != '' ){
			$('.margin-count-product img').prop( 'title', lang_Margin_product + ' (' + $(this).val() + ')' );
		} else{
			$('.margin-count-product img').prop( 'title', lang_Margin_product + ' (0)' );
		}
	});
	$('#sMargin').trigger('change');

	$('#product-basic #fPrice').vatCount({
		taxValuesSelect : $('#product-basic #vat'),
		taxValues : aVats,
		taxGrossField : $('#product-basic #fPrice'),
		taxNetField : $('#product-basic #fPriceN')
	});

	$('#product-basic #fPriceN').vatNettoCount({
		taxValuesSelect : $('#product-basic #vat'),
		taxValues : aVats,
		taxGrossField : $('#product-basic #fPrice'),
		taxNetField : $('#product-basic #fPriceN')
	});

	$('#product-basic #fPriceOld').vatCount({
		taxValuesSelect : $('#product-basic #vat'),
		taxValues : aVats,
		taxGrossField : $('#product-basic #fPriceOld'),
		taxNetField : $('#product-basic #fPriceOldN')
	});

	$('#product-basic #fPriceOldN').vatNettoCount({
		taxValuesSelect : $('#product-basic #vat'),
		taxValues : aVats,
		taxGrossField : $('#product-basic #fPriceOld'),
		taxNetField : $('#product-basic #fPriceOldN')
	});

	$('#product-basic #fBuyPrice').vatCount({
		taxValuesSelect : $('#product-basic #vat'),
		taxValues : aVats,
		taxGrossField : $('#product-basic #fBuyPrice'),
		taxNetField : $('#product-basic #fBuyPriceN')
	});

	$('#product-basic #fBuyPriceN').vatNettoCount({
		taxValuesSelect : $('#product-basic #vat'),
		taxValues : aVats,
		taxGrossField : $('#product-basic #fBuyPrice'),
		taxNetField : $('#product-basic #fBuyPriceN')
	});

	$('#product-basic #fPriceTimeValue').vatCount({
		taxValuesSelect : $('#product-basic #vat'),
		taxValues : aVats,
		taxGrossField : $('#product-basic #fPriceTimeValue'),
		taxNetField : $('#product-basic #fPriceTimeValueN')
	});

	$('#product-basic #fPriceTimeValueN').vatNettoCount({
		taxValuesSelect : $('#product-basic #vat'),
		taxValues : aVats,
		taxGrossField : $('#product-basic #fPriceTimeValue'),
		taxNetField : $('#product-basic #fPriceTimeValueN')
	});

	$('#product-name').change(function(){
		$('h1 span.autochange').html( $(this).val() );
	});

	$('#margin-count').on('click', function(e){
		e.preventDefault();
		marginCount( '#fBuyPrice', '#fPrice', $('#sMargin').val() );
	});

	$('#margin-count-producer').on('click', function(e){
		e.preventDefault();
		marginCount( '#fBuyPrice', '#fPrice', producerMargin );
	});

	$('#margin-count-category').on('click', function(e){
		e.preventDefault();
		marginCount( '#fBuyPrice', '#fPrice', pageMargin );
	});

	$('#tagit-tags').tagit({
		availableTags: tags,
		singleField: true,
		allowSpaces: true,
	});
	
	
	// Warianty
	$('#product-variants').on('change', 'input.gross', function(){
		var container = this;
		taxValues = new Array();
		$(aVats).each(function(){
			var value = this;
			taxValues[value.iVat] = 
			{ 
				iVat : value.iVat,
				fVatValue : value.fVatValue,
				sVatText : value.sVatText
			}
		
		});		
		
		var variantVatSelect = $(container).parents('table.product-variant-item').find('select.vat');
		var productVatSelect = $('#product-basic #vat');
		if( variantVatSelect.val() != 0 ){
			selectedVat = variantVatSelect.val();
		} else{
			selectedVat = productVatSelect.val();
		}
		taxValue = taxValues[selectedVat].fVatValue;

		grossVal = $(container).val();

		if (taxValues.length > 0){
			if( grossVal != '' ){
				netValue = parseFloat(grossVal)/(parseFloat(taxValue)+1);
				$(container).closest('td').find('input.netto').val(netValue.toFixed(2));
			} else{
				$(container).closest('td').find('input.netto').val('');
			}
		}
	});

	$('#product-variants').on('change', 'input.netto', function(){
		var container = this;
		taxValues = new Array();
		$(aVats).each(function(){
			var value = this;
			taxValues[value.iVat] = 
			{ 
				iVat : value.iVat,
				fVatValue : value.fVatValue,
				sVatText : value.sVatText
			}
		
		});		
		
		var variantVatSelect = $(container).parents('table.product-variant-item').find('select.vat');
		var productVatSelect = $('#product-basic #vat');
		if( variantVatSelect.val() != 0 ){
			selectedVat = variantVatSelect.val();
		} else{
			selectedVat = productVatSelect.val();
		}
		taxValue = taxValues[selectedVat].fVatValue;

		grossVal = $(container).val();

		if (taxValues.length > 0){
			if( grossVal != '' ){
				netValue = parseFloat(grossVal)*(parseFloat(taxValue)+1);
				$(container).closest('td').find('input.gross').val(netValue.toFixed(2));
			} else{
				$(container).closest('td').find('input.gross').val('');
			}
		}
		
		variantVatSelect.change(function(){
			$(container).trigger("change");
		});
		productVatSelect.change(function(){
			$(container).trigger("change");
		});
	});

	$('#product-variants input.gross').each(function(){
		$(this).trigger('change');
	});
	
	$('#product-variants').on('click', 'td.margin a.margin-count-variant', function(e){
		e.preventDefault();
		marginCount( $(this).closest('tr').find('td.buy-price input.gross'), $(this).closest('tr').find('td.price input.gross'), $(this).closest('tr').find('td.margin input').val() );
	});

	$('#product-variants').on('click', 'td.margin a.margin-count-product', function(e){
		e.preventDefault();
		marginCount( $(this).closest('tr').find('td.buy-price input.gross'), $(this).closest('tr').find('td.price input.gross'), $('#sMargin').val() );
	});

	$('#product-variants').on('click', 'td.margin a.margin-count-producer', function(e){
		e.preventDefault();
		marginCount( $(this).closest('tr').find('td.buy-price input.gross'), $(this).closest('tr').find('td.price input.gross'), producerMargin );
	});

	$('#product-variants').on('click', 'td.margin a.margin-count-category', function(e){
		e.preventDefault();
		marginCount( $(this).closest('tr').find('td.buy-price input.gross'), $(this).closest('tr').find('td.price input.gross'), pageMargin );
	});

	$('#product-variants').on('change', '.variant-stores .stock input', function(e){
		var iVariantStock = 0;
		$(this).parents('.product-variant-item').find('.variant-stores').each(function(){
			if( $(this).find('input[type="checkbox"]').is(':checked') && $(this).find('.stock input').val() > 0 ){
				iVariantStock += parseInt( $(this).find('.stock input').val() );
			}
		});
		$(this).parents('.product-variant-item').find('.stock input[readonly="readonly"]').val(iVariantStock);
	});

	$('#product-variants').on('click', '.variant-stores input[type="checkbox"]', function(e){
		$(this).parents('.variant-stores').find('.stock input').trigger('change');
	});

	$('#product-variants').on('click', '.product-variant-item .stock .hide', function(e){
		e.preventDefault();
		$(this).parents('.product-variant-item').find('.variant-stores').hide();
		$(this).hide();
	});

	$('#product-variants').on('click', '.product-variant-item .stock input', function(e){
		e.preventDefault();
		$(this).parents('.product-variant-item').find('.variant-stores').show();
		$(this).parents('.stock').find('.hide').show();
	});

	$('#product-variants .product-variant-item .stock .hide').trigger('click');
	
	$('#product-form').submit(function(){
		$('#product-variant-list .product-variant-item').each(function(){
			var bChecked = false;
			var checkboxes = $(this).find('.variant-stores input[type="checkbox"]');
			checkboxes.each(function(){
				if( $(this).is(':checked') ) bChecked = true;
			});
			if( !bChecked ){
				checkboxes.first().trigger('click'); //prop('checked', true);
			}
		});
	});

	$('#attributes-groups').change(function(){
		if( $(this).val() != '' ){
			var aAttributes = $.parseJSON( $(this).val() );
			$('#AttributesList input[type=checkbox]').each(function(){
				$(this).prop('checked', $.inArray(parseInt($(this).val()), aAttributes)>-1);
				$(this).trigger( 'change' );
			});
		}
	});
	$('#AttributesList').hide();
	$('#attributes-show').click(function(e){
		e.preventDefault();
		$('#AttributesList').toggle();
	});

	//Zniżki
	$(document).bind('reenable_visible_canbuy', function(){
		$('#product-delivery_discounts input[type="checkbox"][name^="aGroupsInfo"][name$="[iVisible]"]').prop('disabled', $('#product-delivery_discounts input[type="checkbox"][name="iVisibleAll"]').is(':checked') );
		$('#product-delivery_discounts input[type="checkbox"][name="iVisiblePriceAll"]').prop('disabled', !$('#product-delivery_discounts input[type="checkbox"][name="iVisibleAll"]').is(':checked') );
		$('#product-delivery_discounts input[type="checkbox"][name="iCanBuyAll"]').prop('disabled', !$('#product-delivery_discounts input[type="checkbox"][name="iVisiblePriceAll"]').is(':checked') );
		$('#product-delivery_discounts input[type="checkbox"][name^="aGroupsInfo"][name$="[iVisiblePrice]"]').each( function(){
			$(this).prop('disabled', ( $('#product-delivery_discounts input[type="checkbox"][name="iVisiblePriceAll"]').is(':checked') && !$('#product-delivery_discounts input[type="checkbox"][name="iVisiblePriceAll"]').prop('disabled') )
																	|| ( !($('#product-delivery_discounts input[type="checkbox"][name="iVisibleAll"]').is(':checked')) && !($(this).closest('tr').find('input[type="checkbox"][name$="[iVisible]"]').is(':checked')) ) );
		});
		$('#product-delivery_discounts input[type="checkbox"][name^="aGroupsInfo"][name$="[iCanBuy]"]').each( function(){
			$(this).prop('disabled', ( $('#product-delivery_discounts input[type="checkbox"][name="iCanBuyAll"]').is(':checked') && !$('#product-delivery_discounts input[type="checkbox"][name="iCanBuyAll"]').prop('disabled') )
																	|| ( !($('#product-delivery_discounts input[type="checkbox"][name="iVisiblePriceAll"]').is(':checked')) && !($(this).closest('tr').find('input[type="checkbox"][name$="[iVisiblePrice]"]').is(':checked')) ) );
		});
		if( $('#product-delivery_discounts input[type="checkbox"]:disabled:checked').length > 0 ){
			$('#product-delivery_discounts input[type="checkbox"]:disabled:checked').prop('checked', false);
			$(document).trigger('reenable_visible_canbuy');
		}
	});
	$(document).trigger('reenable_visible_canbuy');
	$('#product-delivery_discounts input[type="checkbox"]').change(function(){
		$(document).trigger('reenable_visible_canbuy');
	});

}

//Tabela zastosowań
$('.advsearcher_column_container a.dialog').prop('disabled', true).first().prop('disabled', false);
$('.advsearcher_column select').change(function(){
	var select = this;
	$(select).closest('.advsearcher_column_container').nextAll('.advsearcher_column_container').find('select').html( '<option value="">' + lang_Select + '</option>' ).prop('disabled', true);
	$(select).closest('.advsearcher_column_container').nextAll('.advsearcher_column_container').find('a.dialog').prop('disabled', true);
	if( $(select).val() > 0 ){
		$.get('admin.php', {'p': 'advsearcher-getsub', 'iValue': $(select).val()}, function( data ){
			$(select).closest('.advsearcher_column_container').next('.advsearcher_column_container').find('select').html( '<option value="">' + lang_Select + '</option>' + data ).prop('disabled', false);
			$(select).closest('.advsearcher_column_container').next('.advsearcher_column_container').find('a.dialog').prop('disabled', false);
			var action = $(select).closest('.advsearcher_column_container').next('.advsearcher_column_container').find('div.dialog input.action').val();
			action = action.replace( /iParentValue=[0-9]*/, 'iParentValue=' + $(select).val() );
			$(select).closest('.advsearcher_column_container').next('.advsearcher_column_container').find('div.dialog input.action').val( action );
		});
	}
});
$('.add').click(function(e){
	e.preventDefault();
	if( $(this).prev('.advsearcher_column_container').find('select').val() > 0 ){
		var value = $(this).prev('.advsearcher_column_container').find('select').val();
		var data = '';
		$(this).prevAll('.advsearcher_column_container').each(function(){
			if( data == '' ) data = $(this).find('select option:selected').text();
			else data = $(this).find('select option:selected').text() + ' &raquo; ' + data;
		});
		if( $(this).closest('table').find('tr.item_' + value).length == 0 ){
			//Nie dodawaj, jak już taki sam jest
			$(this).closest('tr').before('<tr class="item item_' + value + '"><td class="id">' + value + '</td><td class="name">' + data + '</td><td class="del"><a class="advsearcher-delete" href="#"><img src="' + config_dir_templates + 'admin/images/ico/delete.png" alt="' + lang_Delete + '" title="' + lang_Delete + '"/></a></td>	<td class="value" style="display: none"><input type="hidden" value="' + value + '" name="aAdvsearcherValues[]" /></td></tr>');
		}
	}
});
$('#product-advsearcher, .multiple_additional_option.advsearcher').on('click', 'td.del a', function(e){
	e.preventDefault();
	$(this).closest('tr').remove();
});



if( $('#products-search-form').length > 0 ){ //Lista produktów
	$('#search_options').hide();

	$('.rozwin').click(function(e){
		e.preventDefault();
		$(this).toggleClass( 'ui-state-active' );
		$( $(this).attr('href') ).toggle();
	}).mouseover(function(){
		$( this ).addClass( 'ui-state-hover' );
	}).mouseout(function(){
		$( this ).removeClass( 'ui-state-hover' );
	}).closest('.rozwin-container').focusout(function(){
		var rozwincontainer = this;
		setTimeout(function(){
			if( !( $(rozwincontainer).has(document.activeElement).length ) ){
				$(rozwincontainer).find('.rozwin').removeClass( 'ui-state-active' );
				$( $(rozwincontainer).find('.rozwin').attr('href') ).hide();
			}
		}, 10);
	}).find('*').attr('tabindex', -1);

	$('select[multiple="multiple"]').multiselect({checkAllText: lang_Multiselect_all, uncheckAllText: lang_Multiselect_none, noneSelectedText: lang_Multiselect_not_selected, selectedList: 1, selectedText: lang_Multiselect_selected});
	$('#search_options ul li label').mouseover(function(){
		$( this ).addClass( 'ui-state-hover' );
	}).mouseout(function(){
		$( this ).removeClass( 'ui-state-hover' );
	});
	$('#search_options input[type="checkbox"]').change(function(){
		if( $( this ).is(':checked') ){
			var current_option = this;
			$('#search_options input[name="' + $( this ).prop('name') + '"]').each(function(){
				if( this != current_option ){
					$( this ).prop( 'checked', false );
				}
			});
		}
	});
	
	$("td.stock .input, td.price .input").click(function(){
		var stockinput = $(this).parents('tr').find("td.stock .input");
		var priceinput = $(this).parents('tr').find("td.price .input");
		
		var price = '';
		$.colorbox({
			href: 'admin.php?p=products-variants_ajax&iProduct='+$(this).parents("tr").children("td.id").html(),
			title: $(this).parents("tr").find("td.name a").html(),
			onComplete: function(){
				$("#variants-ajax-form input:visible").first().focus();
				$("#variants-ajax-form").submit(function(e){
					e.preventDefault();
					$.colorbox.close();
				});
			},
			onCleanup: function(){
				price = $("#variants-ajax-form #price").val();
				$.ajaxSetup({async: false});
				$.post( $("#variants-ajax-form").prop('action'), $("#variants-ajax-form").serialize(), function(data){
					if( data.substr(0, 1) == 't' ){
						stockinput.html( data.substr(1) );
						priceinput.html( price );
					} else
						alert( lang_Products_ajax_Error );
				});
				$.ajaxSetup({async: true});
			}
		});
	});
	
	$('#select-all').click(function(){
		var sel = $(this).is(':checked');
		$('#products tbody td.selected input').prop( 'checked', sel );
	});
	
	$('#multiple_modify').change(function(){
		$('.multiple_additional_option').hide().find('input, select, textarea');//.prop('disabled', true);
		$('.multiple_additional_option.' + $(this).val() ).show().find('input, select, textarea');//.prop('disabled', false);
		$('#main-form').css('margin-bottom', $('.floatcontainer').css('height') );
	}).trigger('change');
	
	$('.clone_quantity').change(function(){
		if( !$(this).val().match( /^[0-9]+$/ ) ){
			$(this).val( 1 );
		}
		var link = $(this).closest('tr').find('a.product-clone');
		link.attr( 'href', link.attr('href').replace( /iQuantity=[0-9]*/, 'iQuantity=' + $(this).val() ) );
	});

	$(document).bind('reenable_visible_canbuy', function(){
		$('#product-discounts input[type="checkbox"][name^="aGroupsInfo"][name$="[iVisible]"]').prop('disabled', $('#product-discounts input[type="checkbox"][name="iVisibleAll"]').is(':checked') );
		$('#product-discounts input[type="checkbox"][name="iVisiblePriceAll"]').prop('disabled', !$('#product-discounts input[type="checkbox"][name="iVisibleAll"]').is(':checked') );
		$('#product-discounts input[type="checkbox"][name="iCanBuyAll"]').prop('disabled', !$('#product-discounts input[type="checkbox"][name="iVisiblePriceAll"]').is(':checked') );
		$('#product-discounts input[type="checkbox"][name^="aGroupsInfo"][name$="[iVisiblePrice]"]').each( function(){
			$(this).prop('disabled', ( $('#product-discounts input[type="checkbox"][name="iVisiblePriceAll"]').is(':checked') && !$('#product-discounts input[type="checkbox"][name="iVisiblePriceAll"]').prop('disabled') )
																	|| ( !($('#product-discounts input[type="checkbox"][name="iVisibleAll"]').is(':checked')) && !($(this).closest('tr').find('input[type="checkbox"][name$="[iVisible]"]').is(':checked')) ) );
		});
		$('#product-discounts input[type="checkbox"][name^="aGroupsInfo"][name$="[iCanBuy]"]').each( function(){
			$(this).prop('disabled', ( $('#product-discounts input[type="checkbox"][name="iCanBuyAll"]').is(':checked') && !$('#product-discounts input[type="checkbox"][name="iCanBuyAll"]').prop('disabled') )
																	|| ( !($('#product-discounts input[type="checkbox"][name="iVisiblePriceAll"]').is(':checked')) && !($(this).closest('tr').find('input[type="checkbox"][name$="[iVisiblePrice]"]').is(':checked')) ) );
		});
		if( $('#product-discounts input[type="checkbox"]:disabled:checked').length > 0 ){
			$('#product-discounts input[type="checkbox"]:disabled:checked').prop('checked', false);
			$(document).trigger('reenable_visible_canbuy');
		}
	});
	$(document).trigger('reenable_visible_canbuy');
	$('#product-discounts input[type="checkbox"]').change(function(){
		$(document).trigger('reenable_visible_canbuy');
	});

}

$('#sms_debug_cell input').click(function(){
	if( $(this).is(':checked') ) return confirm( lang_SMS_debug_confirm );
});
$('#get-sender-names-available').click(function(e){
	e.preventDefault();
	$.get( 'https://api1.serwersms.pl/zdalnie/index.php?login='+$('#serwersms_login').val()+'&haslo='+$('#serwersms_pass').val()+'&akcja=nazwa_nadawcy&operacja=lista', function(data){
		var names = [];
		$( data.getElementsByTagName('NADAWCA') ).each( function(){ if( this.childNodes[0].nodeValue == 'Autoryzowano' ){ names.push( this.getAttribute('nazwa') ); } });
		var value = $('#sender_name_container input').val();
		var select = '<select name="sms_sender_name"><option value="">___ - Sms ECO</option>';
		$( names ).each(function(){
			select += '<option value="' + this + '" ' + ( this == value ? 'selected="selected"' : null ) + '>' + this + '</option>';
		});
		select += '</select>';
		$('#sender_name_container').html(select);
	});
});

$('#stock2min').prop("readonly",true);
$('#stock3min').prop("readonly",true);
$('#stock4min').prop("readonly",true);

$('#stock1max').focusout(function(){
	val = parseInt($(this).val()) + 1;
	$('#stock2min').val(val);
});

$('#stock2max').focusout(function(){
	val = parseInt($(this).val()) + 1;
	$('#stock3min').val(val);
});

$('#stock3max').focusout(function(){
	val = parseInt($(this).val()) + 1;
	$('#stock4min').val(val);
});

$('.tab.smartoffer').bind( 'afterTabChanged', function(){
	var currentTab = $(this);
	$(this).find('a.loader').each(function(){
		var url = $(this).prop('href');
		$.get( url, null, function(data){
			currentTab.html( data );
		});
		$(this).after('<img src="' + config_dir_scripts + 'colorbox/images/loading.gif" alt="" /> ' + lang_Loading);
		$(this).remove();
	});
});

$('.tab').bind( 'afterTabChanged', function(){
	var id = $(this).attr('id');
	if( $(this).closest('form').length > 0 ){
		if( $(this).closest('form').find('input.activeTabId').length > 0 ){
			$(this).closest('form').find('input.activeTabId').val( id );
		}
		else{
			$(this).closest('form').prepend('<input type="hidden" class="activeTabId" value="'+id+'" name="activeTabId" />');
		}
	} else{
		$('div.tab form').each(function(){
			if( $(this).find('input.activeTabId').length > 0 ){
				$(this).find('input.activeTabId').val( id );
			}
			else{
				$(this).prepend('<input type="hidden" class="activeTabId" value="'+id+'" name="activeTabId" />');
			}
		});
	}
});






$(".colorbox-inline").colorbox({width:"50%", inline:true});
$(".colorbox_stores").colorbox({});

setTimeout( function(){ $('.msg').addClass('active').click(function(e){ e.preventDefault(); $(this).removeClass( 'active' ); }); }, 500 );

$('#menu-swap').click(function(e){
	e.preventDefault();
	$('#container').toggleClass('small normal');
	$.setCookie('admin_menu_style',$('#container').hasClass('small')?'small':'normal');
});

if( $('.tab-headers').length > 0 ){
	$('#body').css( 'margin-top', ( $('.tab-headers').height() + 8 ) + 'px' ).addClass('tabbed');
	$('.tab-headers').css( 'margin-top', ( - $('.tab-headers').height() - 14 ) + 'px' );
}

$('#admin_actions a.post').click(function(e){
	$(this).closest('tr').next('tr').toggle();
});
$('#admin_actions tr.post').hide();


$('#products-select #products tbody tr').each(function(){
	 
	var row = this;
	row.id_field = $(this).find('.id a');
	row.name_field = $(this).find('.name a');
	row.eid = row.id_field.text();
	row.name = row.name_field.text();

	$(row.name_field, row.name_field).click(function(){
		var product_list_selected = new Array();	
		var product = new Object();
		product.name = row.name;
		product.item_id = row.eid;
		product_list_selected.push(product);
		
		window.parent.window_call(request_type, product_list_selected);
		window.parent.$.colorbox.close();
		
		return false;
	});
	
});

$('#products-multiselect .save input, #users-multiselect .save input, #pages-multiselect .save input, #groups-multiselect .save input, #producers-multiselect .save input').each(function(){
	$(this).click(function(){
		var items_list = $(this).parents('form').find('tbody tr');
		var items_list_selected = new Array();	
		items_list.each(function(){
			var item = new Object();
			item.select = $(this).find('.enabled input')[0];
			item.name = $(this).find('.name span.hidden').html();
			if( item.name == undefined )
				item.name = $(this).find('.name label').text();
			item.item_id = $(this).find('.id label').text();
			if ($(item.select).is(':checked'))
			{ items_list_selected.push(item); }
		});
		
		window.parent.window_call(request_type, items_list_selected);
		window.parent.$.colorbox.close();
		return false;
		
	});
});

$('.variant-move-select').colorbox({iframe:true, width: '1000', height: '90%'});
$('.related-select, .users-select, .pages-select, .groups-select, .producer-select').colorbox({iframe:true, width: '1000', height: '90%'});
$('a.colorbox').colorbox({width: '1000', height: '150'});
$('a.photo').colorbox();
$('a.poczta').colorbox({width: '400', height: '200'});
$('a.ifirma').colorbox({width: '1050', height: '450'});

$('#product-related .related, #users-multiselect, #pages-multiselect, #producers-multiselect, #groups-multiselect').each(function(){
	var related = this;
	related.type_name = $(related).prop("id");
	
	related.related_item_container = $(related).find('tbody');
	related.related_item_list = $(related).find('tbody tr');
	related.related_item_empty = $(related).find('thead tr.item')[0];
	
	
	related.parse = function(){
		related.related_item_list = $(related).find('tbody tr');
		
		related.related_item_list.each(function(){	
			var related_item = this;
			related_item.item_id = $(related_item).find('.id').text();
			related_item.del = $(related_item).find('.del a');
			$(related_item.del).click(function(){
				var select_item = $(this).parents('#product-form #pages-multiselect');
				$(related_item).hide();
				$(related_item).remove();
				if(select_item.length > 0){
					select_item.trigger('update_main_category');
				}
				related.parse();
				return false;
			});
		});
	};
	
	related.add_item = function(new_item){
		var new_related = $(related.related_item_empty).clone();
		new_related_content = new_related.html();
		new_related_content = new_related_content.replace(/%iId%/g,new_item.item_id);
		new_related_content = new_related_content.replace(/%sName%/g,new_item.name);
		$(new_related).html(new_related_content);
		
	
		related.related_item_container.append(new_related);
		$(new_related).show();
		
		related.parse();
	};
	
	related.update = function(){
		$(document.global_data[related.type_name]).each(function(){
			var item = this;
			var found = false;

			related.related_item_list.each(function(){	
				var item_related = this;
				if (item.item_id == item_related.item_id)
				{ found = true; }
			});

			if (!found)
			{ related.add_item(item); }

		});
		if($(this).is('#product-form #pages-multiselect')){
			$(this).trigger('update_main_category');
		}
	};
	
	$(document).bind('event_'+related.type_name, function(){
		related.update();
	});
	
	related.parse();

});

$('#product-form #pages-multiselect').bind('update_main_category', function(){
	var categories = $(this);
	var categoryMain = $('#product-main-category');
	var val = categoryMain.val();
	var selectedCategories = categories.find('tbody tr');
	categoryMain.empty();
	selectedCategories.each(function(){
		categoryMain.append( '<option value="' + $(this).find('td.id').html() + '">' + $(this).find('td.name').html() + '</option>' );
	});
	categoryMain.find('option[value='+val+']').prop('selected',true);
	categoryMain.trigger('change');
});



$('#file-list-server table tbody').each(function(){
	$(this).hide();
});

$('#file-new-link').click(function(){
	var fileForm = $('#file-empty').clone();
	$(fileForm).insertBefore($(this));
	$(fileForm).show();
	$(fileForm).removeAttr("id");
	return false;
});


/*  */
/* products - main-category */
/*  */


$('select#product-pages').change(function(){
	var categories = $('select#product-pages');
	var categoryMain = $('#product-main-category');
	var val = categoryMain.val();
	var selectedCategories = categories.find('option:selected').clone();
	selectedCategories.each(function(){
		var text = $(this).html();
		text = text.replace(/&nbsp;/gi,"");
		$(this).html(text);
	});
	categoryMain.empty();
	categoryMain.append(selectedCategories);
	categoryMain.find('option[value='+val+']').prop('selected',true);;
	
});


/*  */
/* orders - nowa pozycja zamówienia */
/*  */

$('#ordered-products').each(function(){
	var order = this;
	order.newItemCounter = 0;
	order.body = $(order).find('table tbody');
	order.emptyItem = $(order).find('#new-order-item')[0];
	$(order.emptyItem).hide();
	order.newItemButton = $(order).find('#new-order-item-button');
	$(order.newItemButton).hide();
	
	order.newItemButton.click(function(){
	
		var newItem = $(order.emptyItem).clone();
		
		var newItemContent = $(newItem).html();
		newItemContent = newItemContent.replace(/%ItemId%/g,order.newItemCounter);
		$(newItem).html(newItemContent);
		$(newItem).removeAttr("id").show();
		order.body.append(newItem);
		order.newItemCounter++;
		return false;
	});
});

/*  */
/* polls - nowa pozycja sondy */
/*  */

$('#polls-form').each(function(){
	var cont = this;
	cont.newItemCounter = 0;
	cont.body = $(cont).find('table tbody');
	cont.emptyItem = $(cont).find('#new-answer-item')[0];
	$(cont.emptyItem).hide();
	cont.newItemButton = $(cont).find('#new-answer-item-button');
	
	cont.itemListBind = function(){
	
		cont.newItemCounter = 0;
		cont.itemList = $(cont).find('table tbody tr.answer-item');
		
		$(cont.itemList).each(function(){
			var item = this;
			item.delItemButton = $(item).find('.delete-answer-item-button');
			cont.newItemCounter++;

			$(item.delItemButton).click(function(){
				$(item).remove();
				return false;
			});
		});
	
	};
	
	cont.itemListBind();
	
	cont.newItemButton.click(function(){

		var newItem = $(cont.emptyItem).clone();
		$(newItem).removeAttr("id").show();
		cont.body.append(newItem);
		cont.itemListBind();
		return false;
	});
	
	
});



/*  */
/*  */
/*  */


/*  */
/* obsługa wariantów po stronie administracyjnej */
/*  */


// Zastrzeżenie: przy dodawaniu nowego wariantu id dublują się gdyż nowy wariant tworzony jest na podstawie pustego wariantu a ten tworzony jest z tego samego bloku co wszystkie warianty
// w php zamieniane są tylko "name" z "aVariants" na "aNewVariants", "id" pozostaje bez zmian.
// id dla atrybutów jest poprawiane poniżej
var pv = $('#product-variant-container')[0];
if (pv != undefined)
{
	pv.list = $(pv).find("#product-variant-list");
	
	pv.selectedNewAttribs;
	
	pv.newVariantItemCounter = 1;
	pv.emptyVariant = $(pv).find('#product-variant-list .product-variant:first-child')[0];
	//$(pv.newVariant).detach();
	pv.emptyVariantItem = $(pv.emptyVariant).find(".product-variant-item")[0];
	pv.emptyVariantItem.emptyItem = true;
	$(pv.emptyVariant).hide();
	
	/* lista atrybutów do wyboru */
	pv.newAttribsList = $(pv).find('#variantAttributeNew .product-variant-attribute');
	pv.newAttribs = Array();
	
	pv.variantAdditionalInfoButton = $(pv).find('#variant-additional')[0];
	$(pv.variantAdditionalInfoButton).click(function(){
		$(pv).trigger("variantAdditionalInfoButtonEvent");
		return false;
	})
	
	/* parsowanie attributes select na obiekty JS/JQ */
	$(pv.newAttribsList).each(function(){
		var iNewAttrib = $(this).prop("id").split('-')[3];
		pv.newAttribs[iNewAttrib] = this;
		pv.newAttribs[iNewAttrib].pid = iNewAttrib;
	});
	
	pv.variants = Array();
	
	/* aktalizuje listę variantów */
	pv.updateVariants = function(idAttrib)
	{
		/* ----------------------- */	

		/* parsowanie istniejących variant i ich attributes na obiekty JS/JQ */
		pv.variantsList = $(pv).find(".product-variant-item");

		$(pv).unbind("variantAdditionalInfoButtonEvent");

		/* operowanie na variant */
		$(pv.variantsList).each(function(){
			var variant = this;

			variant.additionalInfoRow = $(variant).find(".variant-additional");

			/* określenie id variant */
			/* id dla istniejącego */
			if( variant.emptyItem != true && variant.newItem != true)
			{ 
				variant.pid = $(variant).prop("id").split('-')[1]; 
				variant.pid_name = $(variant).prop("id");
				pv.variants[variant.pid] = variant;
			}
			//* specjalne id dla pustego */
			if (variant.emptyItem)
			{ 
				variant.pid = 0; 
				pv.variants[variant.pid] = variant;
				//alert("b"+variant.pid);
			}
			/* id dla nowego (niezapisanego) */
			if (variant.newItem)
			{
				variant.pid = $(variant).prop("id").split('-')[1];
				variant.pid_name = $(variant).prop("id");
				pv.variants.push(variant);
				//alert("c"+variant.pid);
			}

			variant.attribListTable = $(variant).find(".product-variant-attributes")[0];

			/* metody variant */

			/* określenie tabeli z attribs of variant */
			variant.attribs = Array();		
			variant.updateVariantAttribs = function()
			{
				variant.attribsList = $(variant).find(".product-variant-attribute");

				/* operowanie na attribut of variant */
				(variant.attribsList).each(function(){
					/* określenie id attrib of variant */
					var iAttrib = $(this).prop("id").split('-')[3];

					variant.attribs[iAttrib] = this;
					variant.attribs[iAttrib].pid = iAttrib;
				});	
			}	

			variant.removeAttrib = function(idAttrib)
			{
				$(variant.attribs[idAttrib]).detach();
				variant.attribs[idAttrib] = null;
			};

			variant.addAttrib = function(idAttrib)
			{
				newAttrib = $(pv.newAttribs[idAttrib]).clone();
				newAttribSelect = newAttrib.find("select");
				newAttribSelect.prop("name","aVariants["+variant.pid+"][aAttributes]["+idAttrib+"]");
				newAttribSelect.prop("id","variant-"+variant.pid+"-attribute-"+idAttrib+"-select");
				newAttribSelect.parent('span').parent('div').prop("id","variant-"+variant.pid+"-attribute-"+idAttrib);
				newAttribSelect.parent('span').parent('div').find("div.dialog").prop("id","variant_attribute_quick_add-"+variant.pid+"-attribute-"+idAttrib);
				newAttribSelect.parent('span').parent('div').find("div.dialog input.rel").prop("value","#variant-"+variant.pid+"-attribute-"+idAttrib+"-select");
				newAttribSelect.parent('span').parent('div').find("a.dialog").prop("href","#variant_attribute_quick_add-"+variant.pid+"-attribute-"+idAttrib);
				if (variant.emptyItem)
				{ 
					newAttribSelect.prop("name","aNewVariants[%VariantId%][aAttributes]["+idAttrib+"]"); 
					newAttribSelect.prop("id","newvariant-%VariantId%-attribute-"+idAttrib+"-select");
					newAttribSelect.parent('span').parent('div').prop("id","newvariant-%VariantId%-attribute-"+idAttrib);
					newAttribSelect.parent('span').parent('div').find("div.dialog").prop("id","newvariant_attribute_quick_add-%VariantId%-attribute-"+idAttrib);
					newAttribSelect.parent('span').parent('div').find("div.dialog input.rel").prop("value","#newvariant-%VariantId%-attribute-"+idAttrib+"-select");
					newAttribSelect.parent('span').parent('div').find("a.dialog").prop("href","#newvariant_attribute_quick_add-%VariantId%-attribute-"+idAttrib);
				}
				if (variant.newItem)
				{
					newAttribSelect.prop("name","aNewVariants["+variant.pid+"][aAttributes]["+idAttrib+"]");
					newAttribSelect.prop("id","newvariant-"+variant.pid+"-attribute-"+idAttrib+"-select");
					newAttribSelect.parent('span').parent('div').prop("id","newvariant-"+variant.pid+"-attribute-"+idAttrib);
					newAttribSelect.parent('span').parent('div').find("div.dialog").prop("id","newvariant_attribute_quick_add-"+variant.pid+"-attribute-"+idAttrib);
					newAttribSelect.parent('span').parent('div').find("div.dialog input.rel").prop("value","#newvariant-"+variant.pid+"-attribute-"+idAttrib+"-select");
					newAttribSelect.parent('span').parent('div').find("a.dialog").prop("href","#newvariant_attribute_quick_add-"+variant.pid+"-attribute-"+idAttrib);
				}

				$(variant.attribListTable).append(newAttrib);

				variant.updateVariantAttribs();
			};

			variant.updateVariantAttribs();

			variant.deleteVariant = function()
			{ $(variant).remove();};

			$(document).bind('event_'+variant.pid_name, function(){
				// obsługa przeniesienia do innego produktu
				$(document.global_data[variant.pid_name]).each(function(){
					var item = this;
					var exec_url = 'admin.php?p=products-move_variant&iVariant=' + variant.pid + '&iProduct=' + item.item_id;
					//alert(exec_url);
					$.ajax({
						url: exec_url,
						success: function(data) {
							if ($.parseJSON(data))
							{ variant.deleteVariant(); alert('Wariant został przeniesiony'); }
							else
							{ alert('Błąd przenoszenia wariantów. Występuje niezgodność atrybutów pomiędzy produktami. '); }
						}
					});
				});
			});

			variant.additionalInfoRowShow = function()
			{variant.additionalInfoRow.show();}

			variant.additionalInfoRowHide = function()
			{variant.additionalInfoRow.hide();}

			$(pv).bind("variantAdditionalInfoButtonEvent", function(){
				if ($(variant.additionalInfoRow).is(':visible'))
				{variant.additionalInfoRowHide();}
				else
				{variant.additionalInfoRowShow();}
			});

			variant.additionalInfoRowHide();

		});
		/* ----------------------- */		
	};
	
	pv.updateVariants();
	
	/* uaktualnia liste atrybutów w variantach wg listy id variantów w parametrze */
	pv.updateAttrib = function(idAttrib)
	{
		/* weryfikacja czy istniejace atrybuty są w wybranych - jeżeli nie - usuwanie */
		$(pv.variants).each(function(){
			var variant = this;
			if(!$.isWindow(variant))
			{
				$(variant.attribs).each(function(){
					var attrib = this;
					if(!$.isWindow(attrib))
					{

						if($.inArray(attrib.pid,idAttrib) == -1)
						{
							variant.removeAttrib(attrib.pid);
						}
					}
				});
			}
		});
		
		/* weryfikacja czy wybrane atrybuty są w istniejacych - jeżeli nie - dodawanie */
		$(idAttrib).each(function(){
			var newId = this;
			$(pv.variants).each(function(){
				var variant = this;
				if(!$.isWindow(variant))
				{
					var exists = false;
					$(variant.attribs).each(function()
					{
						var attrib = this;
						if(!$.isWindow(attrib)) {	
							if (attrib.pid == newId)
							{ exists = true;}
						}
					});
					
					if(!exists) 
					{ variant.addAttrib(newId);}
				}				
			});
		});		
	};
	
	pv.createNewVariant = function()
	{
		var newVariant = $(pv.emptyVariant).clone()[0];
		
		/* zmiana zawartości - wpisanie id oraz zmiana name/label */
		newVariantContent = $(newVariant).html();
		newVariantContent = newVariantContent.replace(/%VariantId%/g,pv.newVariantItemCounter);
		$(newVariant).html(newVariantContent);
		
		/* podpięcie do obiektu - listy z wariantami */
		
		/* włączenie */
		pv.list.append(newVariant);
		
		var newVariantItem = $(newVariant).find(".product-variant-item")[0];
		newVariantItem.newItem = true;
		$(newVariant).show();
		pv.newVariantItemCounter++;
		
		pv.updateVariants();	
	};
	
	pv.cloneVariant = function( clonedVariant )
	{
		var newVariant = $(pv.emptyVariant).clone()[0];
		
		/* zmiana zawartości - wpisanie id oraz zmiana name/label */
		newVariantContent = $(newVariant).html();
		newVariantContent = newVariantContent.replace(/%VariantId%/g,pv.newVariantItemCounter);
		$(newVariant).html(newVariantContent);
		
		$(clonedVariant).find('.product-variant-attributes select').each(function(){
			$(newVariant).find('.product-variant-attributes select.' + $(this).attr('class') ).val($(this).val());
		});
		
		/* podpięcie do obiektu - listy z wariantami */
		
		/* włączenie */
		clonedVariant.after(newVariant);
		
		var newVariantItem = $(newVariant).find(".product-variant-item")[0];
		newVariantItem.newItem = true;
		$(newVariant).show();
		pv.newVariantItemCounter++;
		
		pv.updateVariants();
	}
	
	
	/* podpięcie akcji zmiany wyboru ilości attributes */
	$('#AttributesList input').change(function(){
		var list = $(this).parents('#AttributesList');
		pv.selectedNewAttribs = [];
		$(list).find( 'input:checked' ).each(function(){
			pv.selectedNewAttribs.push( $(this).val() );
		});
		pv.updateAttrib(pv.selectedNewAttribs);
	})
	
	/* podpięcie akcji klonowania wariantu */
	$('#product-variants').on('click', 'a.clone_variant', function(){
		pv.cloneVariant( $(this).closest('tr.product-variant') );
		return false;
	});
	
	/* podpięcie akcji dodania nowego wariantu pod przycisk */
	$('#product-varaiant-new').click(function(){
		pv.createNewVariant();
		return false;
	});
	
	if($(pv.variants).length == 1)
	{	
		pv.createNewVariant();
	};
	
	$('#AttributesList').trigger('change');
}

/*  */
/* ACTION */
/*  */

$('#action-grupy-list li ul').each(function(){
	$(this).hide();
});

$('#action-grupy-list li a.hider').click(function(){
	$(this).parent().children('ul').toggle();
	if( $(this).children('span').html() == '+' )
		$(this).children('span').html( '-' );
	else
		$(this).children('span').html( '+' );
});

var kategoria = '';

$('#action-grupy-list li a.products-loader').click(function(){
	$('#action-produkty-list table').each(function(){
		$(this).css('display', 'none');
	});

	$('#action-grupy-list li.selected').each(function(){
		$(this).removeClass('selected');
	});
	
	kategoria = $(this).attr('href').substring(1);
	
	$(this).parent('li').addClass('selected');

	if( $('#action-produkty-list table#'+kategoria).length ){
		$('#action-produkty-list table#'+kategoria).each(function(){
			$(this).css('display', 'block');
		});
	} else{
		var json = $.ajax({
												url: "admin.php?p=action-full_list_products&cat_id="+kategoria,
												global: false,
												type: "GET",
												dataType: "html",
												async:false
											}).responseText;

		$('#action-produkty-list').append('<table id="'+kategoria+'" class="action-produkty-table"><tr><th class="id">Id</th><th class="nazwa">Nazwa</th><th class="netto">Cena netto</th><th class="vat">Vat</th><th class="producent">Producent</th><th class="stan">Stan</th><th class="akc"></th><th class="marza">Marża</th></tr></table>');
		var products = $.parseJSON( json );
		$(products).each(function(){
			if( this.iStatus == null ) this.iStatus = '';
			if( this.fMarza == null ) this.fMarza = '';
			$('#action-produkty-list table#'+kategoria).append('<tr id="row-'+this.sId_Produktu+'"><td><img src="templates/admin/images/ico/system-info.png" alt="'+this.sId_Produktu+'" title="'+this.sId_Produktu+'" /></td><td>'+this.sNazwa+'</td><td>'+this.fNetto+'</td><td>'+this.fVat+'</td><td>'+this.sProducent+'</td><td>'+this.iStan+'</td><td class="akc"><input type="text" name="status-'+this.sId_Produktu+'" value="'+this.iStatus+'" /></td><td class="marza"><input type="text" name="marza-'+this.sId_Produktu+'" value="'+this.fMarza+'" />%</td></tr>');
		});
		
		$('#action-produkty-list table#'+kategoria+' td.akc input').each(function(){
			$(this).css('display', 'none');
			$(this).parent().append('<img src="templates/admin/images/yes-no-default-'+$(this).val()+'.png" style="display: inline" />');
		});		
	}

	$('#action-produkty-list td.akc img').click(function(){
		var value = $(this).parent().children('input').val();
		if( value == '' ) value = '1';
		else if( value == '1' ) value = '0';
		else if( value == '0' ) value = '';
		$(this).parent().children('input').val(value);
		$(this).attr('src', 'templates/admin/images/yes-no-default-'+value+'.png');
	});

	return false;
});

$('#action-grupy-list span.akc input').each(function(){
	$(this).css('display', 'none');
	$(this).parent().append('<img src="templates/admin/images/yes-no-default-'+$(this).val()+'.png" style="display: inline" />');
});		

$('#action-grupy-list span.akc img').click(function(){
	var value = $(this).parent().children('input').val();
	if( value == '' ) value = '1';
	else if( value == '1' ) value = '0';
	else if( value == '0' ) value = '';
	$(this).parent().children('input').val(value);
	$(this).attr('src', 'templates/admin/images/yes-no-default-'+value+'.png');
});

/*  */
/*  */
/*  */

	function file_dir_loaded(){
		$('div#colorbox div#cboxWrapper div div#cboxContent div#cboxLoadedContent div#file-list-server a.choose').bind( 'click', function(e){
			e.preventDefault();
			$('.files-dir').append( '<tr><td colspan="3"><input type="text" readonly="readonly" class="checkbox" name="aDirFiles[]" value="'+ $(this).html() +'" /></td></tr>' );
			$.colorbox.close();
		});
		$('div#colorbox div#cboxWrapper div div#cboxContent div#cboxLoadedContent p a').colorbox({ onComplete: file_dir_loaded });
		$('div#colorbox div#cboxWrapper div div#cboxContent div#cboxLoadedContent form').submit(function(e){
			e.preventDefault();
			$.colorbox({ onComplete: file_dir_loaded, href: $(this).prop( 'action' ) + '?' + $(this).serialize() });
		});
	}

	$('#add-file-dir-link').attr( 'href', '?p=files-productdir' );
	$('#add-file-dir-link').colorbox({ onComplete: file_dir_loaded });

	$('.Show_levels').each(function(){
		var listItem = $(this).parent().parent();
		var level = listItem.prop('class').replace('l', '');
		if (listItem.next().hasClass( 'l' + ( parseInt( level ) + 1 ) ) ){
			$(this).css('display', 'inline-block').addClass('show_level');
			listItem.nextAll( '.l' + ( parseInt( level ) + 1) ).hide();
		}
	})
	$('.Show_levels').click(function(){
		if( $(this).hasClass('show_level') ){
			$(this).removeClass('show_level');
			var level = $(this).parent().parent().prop('class');
			var brother = $(this).parent().parent().next();
			$(this).addClass('hide_level');
			do{
				if(brother.hasClass('l' + ( parseInt( level.replace('l', '') ) + 1 ) ) ){
					brother.show();
				}
				brother = brother.next();
				var brotherlevel = brother.prop('class');
				brotherlevel = parseInt( brotherlevel.replace('l', '') );
				var thislevel = parseInt( level.replace('l', '') );
			} while( brotherlevel>thislevel && brother.html() != undefined );
		}else if( $(this).hasClass('hide_level') ){
			$(this).removeClass('hide_level');
			var level = $(this).parent().parent().prop('class');
			var brother = $(this).parent().parent().next();
			$(this).addClass('show_level');
			do{
				brother.hide().find('.Show_levels').removeClass('hide_level').addClass('show_level');
				brother = brother.next();
				var brotherlevel = brother.prop('class');
				brotherlevel = parseInt( brotherlevel.replace( 'l', '' ) );
				var thislevel = parseInt( level.replace( 'l', '' ) );
			} while( brotherlevel>thislevel && brother.html() != undefined );
		}
		return false;
	});

	$('body').on('click', 'a.dialog', function(e){
		e.preventDefault();
		
		var oTmp = $(this).parent('td');
		if( oTmp.length <= 0 ){
			var oTmp = $(this).parent('span').parent('div');
			if( oTmp.length <= 0 ){
				var oTmp = $(this).parent('li');
			}
		}
		console.log( oTmp );
		var buttonsOpts = {};
		buttonsOpts[lang_add] =	function(){
															//Dodawanie
															var sName   = $(this).find('input[type=text]').val();
															var sId     = $(this).find('input.rel').val();
															var sAdd    = $(this).find('input.rel_additional').val();
															var sAction = $(this).find('input.action').val();
															var oDialog = this;
															$.get( sAction + encodeURIComponent( sName ), '', function(data){
																if( parseInt( data ) > 0 ){
																	$(sId).find('option[selected]').prop('selected', false).removeAttr('selected');
																	$(sId).append( '<option value="' + data + '" selected="selected">' + sName + '</option>' ).trigger('change');
																	$(sAdd+":not("+sId+")").append( '<option value="' + data + '">' + sName + '</option>' );
																	
																	console.log( this );
																	$( oTmp ).find( 'select[multiple="multiple"]' ).multiselect('refresh');
																	$(oDialog).dialog('close');
																} else{
																	alert( data );
																}
															});
														};
		buttonsOpts[lang_cancel] =	function(){
																	$(this).dialog('close');
																};
		
		oTmp.find($(this).attr('href')).dialog({
			autoOpen: false,
			height: 150,
			width: 350,
			modal: true,
			buttons: buttonsOpts,
			close: function(){
				$(this).find('input[type=text]').val('');
			}
		});
		
		$($(this).attr('href')).dialog('open');
	});

	$('#highlited-list').on('click', 'a.del', function(e){
		e.preventDefault();
		$(this).parent().parent().detach();
	});

	$('#highlited-list').on('click', 'a.up', function(e){
		e.preventDefault();
		var hl_box = $(this).parent().parent();
		var prev = hl_box.prev('div');
		if( prev.length > 0 ){
			hl_box.insertBefore(prev);
		}
	});

	$('#highlited-list').on('click', 'a.down', function(e){
		e.preventDefault();
		var hl_box = $(this).parent().parent();
		var next = hl_box.next('div');
		if( next.length > 0 ){
			hl_box.insertAfter(next);
		}
	});
	
	$('#highlited-list').on('change', 'select.template', function(){
		var box = $(this).parent().parent();
		var oldclass = box.attr( 'class' );
		var newclass = $(this).find('option:selected').attr('class');
		if( newclass != oldclass ){
			box.addClass( newclass, { duration: 600 } ).removeClass( oldclass, { duration: 600 } );
		}
	});

	$('#highlited-add').on( 'click', function(e){
		e.preventDefault();
		$('#highlited-list').prepend( $('#highlited-new').html() );
	});
	
	$('input.datetime').datetimepicker({
		prevText: '&#x3c;Poprzedni',
		nextText: 'Następny&#x3e;',
		monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
		'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
		monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
		'Lip','Sie','Wrz','Pa','Lis','Gru'],
		dayNames: ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
		dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
		dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
		weekHeader: 'Tydz',
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: '',
		currentText: lang_currentText,
		closeText: lang_closeText,
		timeOnlyTitle: lang_timeOnlyTitle,
		timeText: lang_timeText,
		hourText: lang_hourText,
		minuteText: lang_minuteText,
		secondText: lang_secondText,
		timezoneText: lang_timezoneText,
		timeFormat: 'HH:mm:ss',
	});
	
	$('input.date').datepicker({
		prevText: '&#x3c;Poprzedni',
		nextText: 'Następny&#x3e;',
		monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
		'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
		monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
		'Lip','Sie','Wrz','Pa','Lis','Gru'],
		dayNames: ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
		dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
		dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
		weekHeader: 'Tydz',
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: '',
	});

	/**Tooltip add from jQuery UI*/
	$(function() {
		$( '.tTip' ).tooltip({
			position: {
				my: "left-60 bottom-40",
				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/g, '<br/>' );
			},			
			hide: { duration: 0 }
		});
	});

	$(document).on('change', 'select#packType', function(){
		$('label.hide').hide();
		$('label.hide.packType-'+$(this).val()).show();
	});
	
	
	
	$( 'a.delete' ).on( 'click', function( e ){
		e.preventDefault();
		var sUrl = $( this ).attr( 'href' );
		var sToDelete = $( this ).closest( 'tr' ).find( 'td.name a' ).html();
		if( sToDelete != '' && sToDelete != null && sToDelete != 'undefined' ) sToDelete = '"' + sToDelete + '"';
		$( '#confirm-box a#confirm-action' ).attr( 'href', sUrl );
		$( '#confirm-box span#todelete' ).html( sToDelete );
		$.colorbox({width:"500px", inline:true, href:'#confirm-box'});
	});
	
	$( 'body' ).on( 'click', 'a#nonconfirm-action', function( e ){
		$.colorbox.close();
	});
	$( 'select.dpd-src' ).change( function(){
		if( $( this ).val().length > 0 && $( this ).val() != '' ){
			$( this ).next( '.dpdgen' ).removeClass( 'disabled' );
		}
	});
	
	$('div#attributes ul li select[multiple="multiple"]').multiselect({checkAllText: lang_Multiselect_all, uncheckAllText: lang_Multiselect_none, noneSelectedText: lang_Multiselect_not_selected, selectedList: 1, selectedText: lang_Multiselect_selected});
	$( 'ul#AttributesProductList input.checkbox' ).change(function(){
		var iAttribute = this.value;
		if( this.checked ){
			$( 'div#attributes ul' ).find( 'li#attribute-product-' + iAttribute ).show();
			$( 'div#attributes ul' ).find( 'li#attribute-product-' + iAttribute + ' select' ).removeAttr( 'disabled' );
		}else{
			$( 'div#attributes ul' ).find( 'li#attribute-product-' + iAttribute ).hide();
			$( 'div#attributes ul' ).find( 'li#attribute-product-' + iAttribute + ' select' ).attr( 'disabled', 'disabled' );
		}
	});
	
});