$(document).ready(function() {
	/*Karta edycji towaru*/
	$('.jezyk').each(function() {
		nazwaOpisPokazUkryj($(this));
		$(this).click(function() {nazwaOpisPokazUkryj($(this));});
	});

	function nazwaOpisPokazUkryj(obj)
	{
		var id = $(obj).val();
		if ($(obj).attr('checked')) {
			$('[name="nazwa['+id+']"]').parents(':first').show();
			$('[name="nazwa_uzupelniajaca['+id+']"]').parents(':first').show();
			$('[name="opis['+id+']"]').parents(':first').show();
		} else {
			$('[name="nazwa['+id+']"]').parents(':first').hide();
			$('[name="nazwa_uzupelniajaca['+id+']"]').parents(':first').hide();
			$('[name="opis['+id+']"]').parents(':first').hide();
		}
	}


	if ($('#stan_magazynowy_tryb_id')) {
		sztukiPokazUkryj();
	}


	$('#stan_magazynowy_tryb_id').change(function() {
		sztukiPokazUkryj();
	});

	function sztukiPokazUkryj()
	{
		var globalId = $(':hidden[name=\'globalId\']').val();
		if ($('#stan_magazynowy_tryb_id').val() == globalId) {
			$('#stan_magazynowy_globalny_szt').show();
		} else {
			$('#stan_magazynowy_globalny_szt').hide();
		}
	}

	$('.promocja').each(function() {
		promocjaPokazUkryj($(this));
		$(this).click(function() {
			promocjaPokazUkryj($(this));
		});
	});


	function promocjaPokazUkryj(promocjaCheckbox)
	{
		var index = $(promocjaCheckbox).attr('id').lastIndexOf('_');
		var suffix = index != -1 ? $(promocjaCheckbox).attr('id').substring(index) : '';

		if ($(promocjaCheckbox).attr('checked')) {
			$('#procent_upustu'+suffix).parents(':first').show();
			$('#cena_promocyjna'+suffix).parents(':first').show();

		} else {
			$('#procent_upustu'+suffix).parents(':first').hide();
			$('#cena_promocyjna'+suffix).parents(':first').hide();
		}
	}


	$('.procent_upustu').keyup(function() {
		var index = $(this).attr('id').lastIndexOf('_');
		var suffix = index != -1 ? $(this).attr('id').substring(index) : '';
		suffix = suffix == '_upustu' ? '' : suffix;

		var procent = isNaN($(this).val()) || $(this).val() == '' ? 0 : parseFloat($(this).val());
		var cena = isNaN($('#cena'+suffix).val()) || $('#cena'+suffix).val() == '' ? 0 : parseFloat($('#cena'+suffix).val());
		var cena_promocyjna;

		if (procent != 0) {
			cena_promocyjna = cena*(100-procent)/100;
			$('#cena_promocyjna'+suffix).val(Math.round(cena_promocyjna*100)/100);
		} else {
			$('#cena_promocyjna'+suffix).val('');
		}
	});

	$('.cena').keyup(function() {
		var index = $(this).attr('id').lastIndexOf('_');
		var suffix = index != -1 ? $(this).attr('id').substring(index) : '';

		var procent = isNaN($('#procent_upustu'+suffix).val()) || $('#procent_upustu'+suffix).val() == '' ? 0 : parseFloat($('#procent_upustu'+suffix).val());
		var cena = isNaN($(this).val()) || $(this).val() == '' ? 0 : parseFloat($(this).val());
		var cena_promocyjna;

		if (cena == 0) {
			$('#procent_upustu'+suffix).val('');
			$('#cena_promocyjna'+suffix).val('');

		} else if (procent != 0){
			cena_promocyjna = cena*(100-procent)/100;
			$('#cena_promocyjna'+suffix).val(Math.round(cena_promocyjna*100)/100);

		}
	});


	$('.linkedArticlesForm #kategoria_towarow').change(function() {
		$('.linkedArticlesForm #towar').empty();
		$('.linkedArticlesForm #towar').parents('.formRow').hide();

		if ($(this).val()) {
			$('.loaderImg').show();
			var categoryId = $(this).val();
			var articleId = $('.linkedArticlesForm #towar_id').val();
			$.ajax({
				type: 'POST',
				data :'command=getArticlesFromCategory&categoryId='+categoryId+'&articleId='+articleId,
				url : '/towar/ajax/',
				dataType : 'xml',
				success : function(xmlData) {
					var htmlElem = '<option value="">&nbsp;</option>';
					$('result > article', xmlData).each(function() {
						htmlElem += '<option value="'+$(this).find('id').text()+'">'+$(this).find('name').text()+'</option>';
					});
					$('.linkedArticlesForm #towar').append(htmlElem);
					$('.linkedArticlesForm #towar').parents('.formRow').show();
				},
				complete : function() {$('.loaderImg').hide();}
			});
		}
	});

	$('.linkedArticlesDeleteForm').submit(function() {
		return confirm($.messages['LINKED_ARTICLE_DELETE']);
	});

	/*Edycja cen*/
	$('#restoreDefaultPriceForm').submit(function(){
		return confirm($.messages['DEFAULT_PRICE_RESTORE']);
	});

	/*Edycja zdjec*/
	$('.photoDeleteForm').submit(function() {
		return confirm($.messages['PHOTO_DELETE']);
	});

	/* Stany magazynowe i dostępność kombinacji */
    $('table.combinationTable').find(':checkbox').each(function() {
		$(this).click(function() {
			var tableType = $(this).parents().filter('table:first').attr('id') == 'combinationList' ? 'l' : 'm';
			var parent = tableType == 'l' ? $(this).parents().filter('tr:first') : $(this).parents().filter('td:first');
			var otherParent = tableType == 'l' ? $('#combinationMatrix :checkbox[name=\''+$(this).attr('name')+'\']').parents().filter('td:first') : $('#combinationList :checkbox[name=\''+$(this).attr('name')+'\']').parents().filter('tr:first');

			if (!$(this).attr('checked') || parseInt($(parent).find(':text').val()) <= 0 ) {
				$(parent).addClass('inaccessible');
				$(otherParent).addClass('inaccessible');
			} else {
				$(parent).removeClass('inaccessible');
				$(otherParent).removeClass('inaccessible');
			}

			if ($(this).attr('checked')) {
				$(otherParent).find(':checkbox[name=\''+$(this).attr('name')+'\']').attr('checked','checked');
			} else {
				$(otherParent).find(':checkbox[name=\''+$(this).attr('name')+'\']').removeAttr('checked');
			}
		});
	});

	$('table.combinationTable').find(':text').each(function() {
		$(this).keyup(function() {
			var tableType = $(this).parents().filter('table:first').attr('id') == 'combinationList' ? 'l' : 'm';
			var parent = tableType == 'l' ? $(this).parents().filter('tr:first') : $(this).parents().filter('td:first');
			var otherParent = tableType == 'l' ? $('#combinationMatrix :text[name=\''+$(this).attr('name')+'\']').parents().filter('td:first') : $('#combinationList :text[name=\''+$(this).attr('name')+'\']').parents().filter('tr:first');

			if (parseInt($(this).val()) <= 0 || !$(parent).find(':checkbox').attr('checked')){
				$(parent).addClass('inaccessible');
				$(otherParent).addClass('inaccessible');
			} else {
				$(parent).removeClass('inaccessible');
				$(otherParent).removeClass('inaccessible');
			}
			$(otherParent).find(':text[name=\''+$(this).attr('name')+'\']').val($(this).val());
		});
	});

	$('div#storagePresentation :radio').click(function() {
		if ($(this).val() == 'l') {
			$('#combinationList').show();
			$('#combinationMatrix').hide();
			$('p#matrixColumnVariants').hide();
		} else {
			$('#combinationList').hide();
			$('#combinationMatrix').show();
			$('p#matrixColumnVariants').show();
		}
	});
	$('div#storagePresentation #wariant_tworzacy_kolumny').change(function() {
		$(this).parents().filter('form').submit();
	});

	$('#storageKwakForm').submit(function() {
		if ($('#storageKwakForm select[multiple] option:selected').size() == 0) {
			alert($.messages['STORAGE_KWAK'])
			return false;
		}
		return true;
	});

	/*Karta prezentacji towaru*/
	$('#itemLittlePhotos a').click(function() {
		$('#majorPhoto').attr('src',$(this).attr('href'));
		$('#majorPhoto').parents('a').attr('href',$(this).attr('href').replace('karta','popup'));
		$('#itemLittlePhotos img[class="active"]').attr('class','inactive');
		$(this).find('img').attr('class','active');

		var links = $('#itemPhotos a[class="forlightbox"]');
		for (var i = 0, item; item = links[i]; i++) {
			if ($(item).attr('href') == $('#majorPhoto').parents('a').attr('href')) {
				$(item).removeAttr('rel');
			} else {
				$(item).attr('rel', 'lightbox[glowne]');
			}
		}
		$("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
			return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
		});
		return false;
	});

    jQuery('.jcarousel-skin-tango').jcarousel({
        scroll: 1
    });

    $('#itemDeleteForm').submit(function() {
    	return confirm($.messages['ARTICLE_DELETE']);
    });

    if ($('#order :radio:checked').length != 0) {
    	showCombinationAttributes();
    }

    $('#order :radio').click(function() {
    	showCombinationAttributes();
    });

    $('#orderArticleForm').submit(function() {
    	if ($('#order :radio:checked').size() != $('#order div.orderVariantRow').size()) {
    		return true;
    	}
    	var available = true;
	   	$('#order :radio:checked').each(function() {
	   		var label = $('label[for=\''+$(this).attr('id')+'\']');
	   		if (($(label).hasClass('disabled') || $(label).hasClass('constantDisabled'))) {
	   			available = false;
	   		}
	   	});

	   	if (!available) {
	   		alert($.messages['COMBINATION_INACCESSIBLE']);
	   		return false;
	   	}
	   	return true;
    });



	$('#order .loaderImg').attr('licznik',0);

	function showCombinationAttributes()
	{
		var ids = new Array();
    	var num = $('#order div.orderVariantRow').size();

    	$('#order :radio:checked').each(function() {
    		ids.push($(this).val());
    	});

    	$('#order .loaderImg').show();
    	$('#order .loaderImg').attr('licznik',parseInt($('#order .loaderImg').attr('licznik') ) + 1 );

    	if (ids.length == num) {
    		$('#order .priceValue').empty();
    		$('#order .statusValue').empty();
    		$.ajax({
				type: 'POST',
				data :'command=getCombinationAttributes&combinationValues='+ids+'&articleId='+$('#order #towar_id').val(),
				url : '/towar/ajax/',
				dataType : 'xml',
				success : function(xmlData) {
					if ($(xmlData).find('status').size() && $(xmlData).find('dostepnosc').size() && $(xmlData).find('cena').size()) {
						if ($(xmlData).find('cena_promocyjna').size()) {
							$('#order .priceValue').html('<span class="old_price">'+$(xmlData).find('cena').text()+'</span><span class="new_price">'+$(xmlData).find('cena_promocyjna').text()+'</span>');
						} else {
							$('#order .priceValue').html('<span class="normal_price">'+$(xmlData).find('cena').text()+'</span>');
						}

						if ($(xmlData).find('dostepnosc').text() == 'false' || !$(xmlData).find('stan_magazynowy_poziom').size()) {
							$('#order .statusValue').html($(xmlData).find('status').text());
						} else {
							$('#order .statusValue').html($(xmlData).find('stan_magazynowy_poziom').text());
						}
					}
				},
				complete : function() {
					$('#order .loaderImg').attr('licznik',parseInt($('#order .loaderImg').attr('licznik') ) - 1 );
					if ($('#order .loaderImg').attr('licznik') <= 0) {
						$('#order .loaderImg').hide();
						$('#order .loaderImg').attr('licznik',0);
					}
				}
			});
    	} else {
    		$.ajax({
				type: 'POST',
				data :'command=getInaccessibleValues&values='+ids+'&articleId='+$('#order #towar_id').val(),
				url : '/towar/ajax/',
				dataType : 'xml',
				success : function(xmlData) {
					$('#order label').removeClass('disabled');
					$(xmlData).find('id').each(function() {
						$('#order label[for="cecha_wartosc_id_'+$(this).text()+'"]').addClass('disabled');
					});
				},
				complete : function() {
					$('#order .loaderImg').attr('licznik',parseInt($('#order .loaderImg').attr('licznik') ) - 1 );
					if ($('#order .loaderImg').attr('licznik') <= 0) {
						$('#order .loaderImg').hide();
						$('#order .loaderImg').attr('licznik',0);
					}
				}
			});
    	}
	}

	/*Cechy i warianty*/
	$('.featureAssignedDeleteForm').submit(function() {
		return confirm($.messages['ASSIGNED_FEATURE_DELETE']);
	});

	$('.featureAssignedValueDeleteForm').submit(function() {
		return confirm($.messages['ASSIGNED_FEATURE_VALUE_DELETE']);
	});

	$('.variantAssignedDeleteForm').submit(function() {
		return confirm($.messages['VARIANT_DELETE']);
	});

	$('.variantAssignedValueDeleteForm').submit(function() {
		return confirm($.messages['VARIANT_VALUE_DELETE']);
	});

	$('.makeVariantOptionalForm').submit(function() {
		return confirm($.messages['VARIANT_MAKE_OPTIONAL']);
	});
	$('.makeVariantObligatoryForm').submit(function() {
		return confirm($.messages['VARIANT_MAKE_OBLIGATORY']);
	});


	$('.notAssignedFeatureForm div.d').find('a.dp-choose-date').remove();
	$('.notAssignedFeatureForm div.d').find('input[name="cecha_id"]').remove();
	$('.notAssignedFeatureForm div.t').find('input[name="cecha_id"]').remove();
	$('.notAssignedFeatureForm div.l').find('input[name="cecha_id"]').remove();
	$('.notAssignedFeatureForm div.m').find('input[name="cecha_id"]').remove();
	var htmlD = $('.notAssignedFeatureForm div.d').html();
	var htmlT = $('.notAssignedFeatureForm div.t').html();
	var htmlL = $('.notAssignedFeatureForm div.l').html();
	var htmlM = $('.notAssignedFeatureForm div.m').html();
	var htmlS = $('.notAssignedFeatureForm div.s').html();
	$('.notAssignedFeatureForm .loaderImg').hide();
	$('.notAssignedFeatureForm .cecha').remove();
	showHideAssignFeatureForm($('.notAssignedFeatureForm #cecha_id').val());
	$('.notAssignedFeatureForm #cecha_id').change(function() {
		showHideAssignFeatureForm($(this).val());
	});

	function showHideAssignFeatureForm(featureId)
	{
		$('.notAssignedFeatureForm .cecha').remove();
		if (featureId) {
			$('.notAssignedFeatureForm .loaderImg').show();
			$.ajax({
				type: 'POST',
				data :'command=getFeatureData&featureId='+featureId,
				url : '/cecha/ajax/',
				dataType : 'xml',
				success : function(xmlData) {
					if ($(xmlData).find('result').text() != 'err') {
						if ($(xmlData).find('slownikowa').text() == 'true') {
							var htmlElem = '';
							$(xmlData).find('wartosc').each(function() {
								htmlElem += '<input type="checkbox" name="cecha_wartosc_id['+$(this).find('id').text()+']" value="'+$(this).find('id').text()+'" id="cecha_wartosc_id_'+$(this).find('id').text()+'" /><label for="cecha_wartosc_id_'+$(this).find('id').text()+'">'+$(this).find('nazwa').text()+'</label>';
							});

							var tmp = $('<div class="cecha s">'+htmlElem+htmlS+'</div>');
						} else {
							var typ = $(xmlData).find('typ').text();
							if (typ == 'l') {
								var tmp = $('<div class="cecha l">'+htmlL+'</div>');
							} else if (typ == 't') {
								var tmp = $('<div class="cecha t">'+htmlT+'</div>');
							} else if (typ == 'd') {
								var tmp = $('<div class="cecha d">'+htmlD+'</div>');
							} else if (typ == 'm' ){
								var tmp = $('<div class="cecha m">'+htmlM+'</div>');
							}
						}
						if (tmp) {
							$('.notAssignedFeatureForm #cecha_id').parents(':first').after(tmp);
						}

						$.addDatePicker();
					}
				},
				complete : function() {$('.notAssignedFeatureForm .loaderImg').hide();}
			});
		}
	}
	$('a#priceListLink').click(function() { return false; }).mTooltip({top: -150, left: 0});

 });
