// LIST COMPONENT MANAGER //select-list

var locationMG = {

	init: function() {
//		on choosing province create cities list
		$('#sel-province').bind('change', function(e){
			var idProvince = ($(this).val());
			locationMG.raiseCreateCitiesList(idProvince, '');
			return false;
		});

//		on choosing city create districts list
		$('#sel-city').bind('change', function(e){
			var idCity = ($(this).val());
			locationMG.raiseCreateDistrictsList(idCity, '');
			return false;
		});

//		on choosing location radiobutton show user from the area
		$('.location').bind('change', function(e){
			var locationType = ($(this).val());
			window.location = '/friend/friend.html?type='+locationType;
			return false;
		});

	},

//	creating cities list
	raiseCreateCitiesList: function(idProvince, selected){
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/user/get_province_cities',
				data: {id_province: idProvince},
				success: function(data){
					$('#sel-city').children('.city').remove();
					$('#sel-district').children('.district').remove();
					$.each(data.result, function(){
						$('#sel-city').append('<option id="sel-city-'+ this.id +'" class="city" value="' + this.id + '">' + this.name + '</option>');
						if (selected != '' && selected==this.id){
							$('#sel-city-'+selected).attr('selected', 'selected');
						}
					});
				}
			});
	},

//	creating districts list
	raiseCreateDistrictsList: function(idCity, selected){
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/user/get_city_districts',
				data: {id_city: idCity},
				success: function(data){
					$('#sel-district').children('.district').remove();
					$.each(data.result, function(){
						$('#sel-district').append('<option id="sel-district-'+ this.id +'" class="district" value="' + this.id + '">' + this.name + '</option>');
						if (selected != '' && selected==this.id){
							$('#sel-district-'+selected).attr('selected', 'selected');
						}
					});
				}
			});
	}
}

var userMG = {
//	constructor: catch events
	init: function(){

		$('#with-category').bind('change', function(e){
			if ($('#bought-down').attr('disabled') == true) {
				$('#bought-down').attr('disabled', '');
			} else {
				$('#bought-down').attr('disabled', 'disabled');
			}
			userMG.raiseChangeOptions();
			return false;
		});

		$('#bought-down').bind('change', function(e){
			if ($('#with-category').attr('disabled') == false) {
				$('#with-category').attr('disabled', 'disabled');
			} else {
				$('#with-category').attr('disabled', '');
			}
			userMG.raiseChangeOptions();
			return false;
		});

	},

	raiseChangeOptions: function(){
		if ($('#with-category').attr('checked') == true) {
			var withCategory = true;
		} else {
			var withCategory = false;
		}
		if ($('#bought-down').attr('checked') == true) {
			var boughtDown = true;
		} else {
			var boughtDown = false;
		}
		$.ajax({
			type: "POST",
			dataType: "json",
			url: '/xhr/list/change_options.action',
			data: {with_category: withCategory, bought_down: boughtDown},
			success: function(data){
			}
		});
		return false;
	}

};

var listMG = {

//	constructor: catch events
	init: function(){

//		pokazanie edycji listy
		$('a.edit-btn-show-tags').livequery('click', function(e){
			$(this).parent().siblings('.tags').show();
			$(this).hide();
			$(this).siblings('a.edit-btn-hide-tags').show();
			return false;
		});

//		pokazywanie szczegolow aktualnej listy
		$('#list-of-lists > li.li-details-list > div.row > div.item-actions > a.this-expand').bind('click', function(e) {
			var idShoppingList = ($(this).attr('id').replace('a-details-list-', ''));
			if ($('#li-details-list-'+idShoppingList).hasClass('expanded')) {
				$('#li-details-list-'+idShoppingList).children('ul').slideUp(300, function() {$(this).hide(); $('#li-details-list-'+idShoppingList).removeClass('expanded');});
			} else {
				$('#li-details-list-'+idShoppingList).addClass('expanded');
				$('#li-details-list-'+idShoppingList).children('ul').show(550);
			}
			return false;
		});

//		pokazywanie szczegolow listy zrealizowanej
		$('#list-of-closed-lists > li.li-details-list > div.row > div.item-actions > a.this-expand').bind('click', function(e) {
			var idShoppingList = ($(this).attr('id').replace('a-details-list-', ''));
			if ($('#li-details-list-'+idShoppingList).hasClass('expanded')) {
				$('#li-details-list-'+idShoppingList).children('ul').slideUp(300, function() {$(this).hide(); $('#li-details-list-'+idShoppingList).removeClass('expanded')});
			} else {
				$('#li-details-list-'+idShoppingList).addClass('expanded');
				$('#li-details-list-'+idShoppingList).children('ul').show(550);
			}
			return false;
		});

//		zamień link "przenieś do zakończonych" na "przenieś do aktualych"
		$('#list-of-closed-lists > li.li-details-list > div.row > div.item-actions > a.this-move').html('Przenieś do aktualnych').attr("title","Przenieś do aktualnych").removeClass('this-move').addClass('this-move-up');

//		pokazanie selecta z lista wszystkich list uzytkownika
		$('a.add-to-list-from-hint').livequery('click', function(e){
//			jezeli podpowiedz jest z koszyka, to w idProduct jest id_product, a jesli z sugestii to w idProduct jest id_bought_product
			var idProduct = $(this).attr('id').replace('a-add-to-list-from-hint-', '');
			$('#a-add-to-list-from-hint-'+idProduct).removeClass("add-to-list-from-hint");
			$('#a-add-to-list-from-hint-'+idProduct).addClass("no-add-to-list-from-hint");
			$('#select-list-'+idProduct).show();
			return false;
		});

//		schowanie selecta z lista wszystkich list uzytkownika
		$('a.no-add-to-list-from-hint').livequery('click', function(e){
			var idProduct = $(this).attr('id').replace('a-add-to-list-from-hint-', '');
			$('#select-list-'+idProduct).hide();
			$('#a-add-to-list-from-hint-'+idProduct).removeClass("no-add-to-list-from-hint");
			$('#a-add-to-list-from-hint-'+idProduct).addClass("add-to-list-from-hint");
			return false;
		});

//		wywolanie funkcji dodajacej produkt z podpowiedzi do listy
		$('select.select-list').livequery('change', function(e){
			var idUserList = $(this).val();
//			jezeli podpowiedz jest z koszyka, to w idProduct jest id_product, a jesli z sugestii to w idProduct jest id_bought_product
			var idProduct = $(this).attr('id').replace('select-list-', '');
			if ($(this).hasClass('hint-in-list')) {
				var addingType = 'hint_in_list' 
			}
			if ($(this).hasClass('hint')) {
				var addingType = 'hint'
			}
			if ($(this).hasClass('hint-in-basket')) {
				var addingType = 'hint_in_basket'
			}
			if ($(this).hasClass('hint-from-similar-user-in-list')) {
				var addingType = 'hint_from_similar_user_in_list'
			}
			if ($(this).hasClass('hint-from-similar-user')) {
				var addingType = 'hint_from_similar_user'
			}
//			wywolanie funkcji dodajacej produkt z sugestii na liscie list i z zakladki sugestii
			listMG.raiseAddProductToListFromHint(idProduct, idUserList, addingType);
			return false;
		});

//		wywolanie funkcji pokazujacej udostepnione listy znajomego usera 
		$('#select-friend').livequery('change', function(e){
			var idFriend = $(this).val();
			window.location = '/list/lists_list.html?inner_active_tab=inner_tab_friends&id_friend='+idFriend+'#friends_lists'
			return false;
		});

//		show public list components
		$('#all-shared-lists > li.li-details-list > div.row > div.item-actions > a.public').livequery('click', function(e){
			var idShoppingList = ($(this).attr('id').replace('a-expand-public-list-', ''));
			listMG.raiseShowPublicListProducts(idShoppingList, 'public');
			return false;
			
		});

//		show friend public list components
		$('#friends-shared-lists > li.li-details-list > div.row > div.item-actions > a.friend-public').livequery('click', function(e){
			var idShoppingList = ($(this).attr('id').replace('a-expand-friend-public-list-', ''));
			listMG.raiseShowPublicListProducts(idShoppingList, 'friend-public');
			return false;
		});

	},

//	dodanie produktu do listy z sugestii na liscie
	raiseAddProductToListFromHint: function(idProduct, idUserList, addingType) {
		$('#a-add-to-list-from-hint-'+idProduct).hide();
		$('#select-list-'+idProduct).hide();
		window.location = '/list/add_component.action?adding_type='+addingType+'&id='+idProduct+'&id_shopping_list='+idUserList
		return false;
	},

//	show components list when user expand public/friends public list
	raiseShowPublicListProducts: function(idShoppingList, type) {
		
//		if it is already expanded hide components
		if ($('#li-'+ type +'-list-'+idShoppingList).hasClass('expanded')){
			$('#components-'+ type +'-list-'+idShoppingList).slideUp(300, function() {
				$(this).children().remove(); 
				$(this).hide(); 
				$('#li-'+ type +'-list-'+idShoppingList).removeClass('expanded');});
		} else {
//			get components and show them on the list
			$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/list/get_all_list_components',
				data: {id_shopping_list: idShoppingList},
				success: function(data){
					var json = data.result;
//					if list is empty - show message
					if (json == 0) {
						$('#components-'+ type +'-list-'+idShoppingList).append('<li class=""><div class="item-name">Lista jest pusta</div><div class="item-qty"></div></li>');
					} else {
						$.each(json, function(){
							$('#components-'+ type +'-list-'+idShoppingList).append('<li class=""><div class="item-name">'+ this.name +'</div><div class="item-qty">'+ this.quantity +'</div></li>');
						});
					}
					$('#components-'+ type +'-list-'+idShoppingList+' > li:even').addClass('odd');
					$('#components-'+ type +'-list-'+idShoppingList).append('<li><a href=/list/'+ idShoppingList +'/add_from_public_lists.action class="product-add">Dodaj do moich list</a></li>');
					$('#li-'+ type +'-list-'+idShoppingList).addClass('expanded');
					$('#components-'+ type +'-list-'+idShoppingList).show(550);
				}
			});
		}
	}

};

var list_componentMG = {

//	constructor: catch events
	init: function(){

//		wyswietlenie pola do dodania tagow
		$('a.edit-btn-show-tags').livequery('click', function(e){
			$(this).parent().siblings('.tags').show();
			$(this).hide();
			$(this).siblings('a.edit-btn-hide-tags').show();
			return false;
		});

//		chowanie pola do dodania tagow
		$('a.edit-btn-hide-tags').livequery('click', function(e){
			$(this).parent().siblings('.tags').hide();
			$(this).hide();
			$(this).siblings('a.edit-btn-show-tags').show();
			return false;
		});

//		list component details
		$('#product-list > li > div.item-name > a').livequery('click', function(e){
			var idListComponent = ($(this).attr('id').replace('name-list-component-', ''));
			list_componentMG.raiseDetailsListComponent(idListComponent);
//			usuń liste podobnie otagowanych produktów
			list_componentMG.removeTaggedSiblings();
			return false;
		});

//		removing list component (list_type = with-category)
		$('#product-list > li > div.item-actions > a.delete-with-category').livequery('click', function(e){
			var idListComponent = ($(this).attr('id').replace('remove-list-component-', ''));
			list_componentMG.raiseRemoveListComponent(idListComponent, 'list', 'with-category');
			return false;
		});

//		removing list component (list_type = without-category)
		$('#product-list > li > div.item-actions > a.delete-without-category').livequery('click', function(e){
			var idListComponent = ($(this).attr('id').replace('remove-list-component-', ''));
			list_componentMG.raiseRemoveListComponent(idListComponent, 'list', 'without-category');
			return false;
		});

//		removing editing list component
		$('#remove-edit-list-component').livequery('click', function(e){
			var idListComponent = $('#input-edit-id-list-component').val();
			if ($('#remove-edit-list-component').hasClass('with-category')) {
				list_type = 'with-category';
			} else {
				list_type = 'without-category';
			}
			list_componentMG.raiseRemoveListComponent(idListComponent, 'edit_form', list_type);
			return false;
		});

//		adding list component (list_type = with-category)
		$('#with-category-add-list-component').livequery('click', function(e){
			$(this).attr('disabled', 'disabled');
			list_componentMG.raiseHideAddTags();
			list_componentMG.raiseAddActionListComponent('with-category');
			return false;
		});

//		adding list component (list_type = without-category)
		$('#without-category-add-list-component').livequery('click', function(e){
			$(this).attr('disabled', 'disabled');
			list_componentMG.raiseHideAddTags();
			list_componentMG.raiseAddActionListComponent('without-category');
			return false;
		});

//		editing list component (list_type = with-category)
		$('#product-list > li > div.item-actions > a.this-edit').livequery('click', function(e){
			list_componentMG.raiseHideAddTags();
			var idListComponent = ($(this).attr('id').replace('edit-list-component-', ''));
			list_componentMG.raiseEditListComponent(idListComponent);
			list_componentMG.raiseDetailsListComponent(idListComponent);
			return false;
		});

//		cancel editing list component
		$('#cancel-edit-list-component').livequery('click', function(e){
			var idListComponent = $('#input-edit-id-list-component').val();
			list_componentMG.raiseCancelEditListComponent(idListComponent);
			return false;
		});

//		submit list component edit form (list_type = with-category)
		$('#with-category-save-edit-list-component').livequery('click', function(e) {
			var idListComponent = $('#input-edit-id-list-component').val();
			list_componentMG.raiseEditActionListComponent(idListComponent, 'with-category');
			return false;
		});

//		submit list component edit form (list_type = without-category)
		$('#without-category-save-edit-list-component').livequery('click', function(e) {
			var idListComponent = $('#input-edit-id-list-component').val();
			list_componentMG.raiseEditActionListComponent(idListComponent, 'without-category');
			return false;
		});

//		wywolanie funkcji pobrajacej produkty po nacisnieciu danego taga
		$('a.bold').livequery('click', function(e) {
//			usuń liste podobnie otagowanych produktów
			list_componentMG.removeTaggedSiblings();
			$('#slide-wrapper').prepend('<a id="close-tagged-list" class="sliding-tab"></a>');
			$('#close-tagged-list').scrollFollow({container: 'slide-wrapper',speed: 1000,offset: 10});
			var tag = ($(this).attr('id').replace('a-product-tag-', ''));
			list_componentMG.raiseFindProducts(tag);
			return false;
		});

//		chowanie listy podobnie otagowanych poduktów
		$('#slide-wrapper a#close-tagged-list').livequery('click', function(e) {
//			usuń liste podobnie otagowanych produktów
			list_componentMG.removeTaggedSiblings();
			$('#slide-wrapper').hide();
			return false;
		});

//		wywolanie funkcji, ktore dodaje produkt z listy tagow do naszej listy
		$('a.a-hint-list').livequery('click', function(e) {
			list_componentMG.raiseHideAddTags();
			var idProduct = $(this).attr('id');
			var idShoppingList = $('#input-id-shopping-list').val();
			var list_type = '';
			if ($(this).hasClass('with-category')) {
				list_type = 'with-category';
			}
			list_componentMG.raiseAddListComponentFromTag(idProduct, idShoppingList, list_type);
			return false;
		});

//		wywolanie funkcji wysylajacej liste mailem
		$('#send-list').livequery('click', function(e){
//			disable button for not double clicking
			$(this).attr('disabled', 'disabled');
			var idShoppingList = $('#input-id-shopping-list').val();
			var sendToEmail = $('#textarea-send-to-email').val();
			list_componentMG.raiseSendList(idShoppingList, sendToEmail);
			return false;
		});

//		sent to myself
		$('#send-to-user').livequery('click', function(e){
			var idShoppingList = $('#input-id-shopping-list').val();
			list_componentMG.raiseSendListToUser(idShoppingList);
			return false;
		});

//		mark as bought
		$('#product-list > li > div > input.mark-as-bought').livequery('click', function(e) {
			var idListComponent = $(this).attr('id');
			list_componentMG.raiseMarkAsBoughtListComponent(idListComponent);
			$('#'+idListComponent).removeClass('mark-as-bought');
			$('#'+idListComponent).addClass('mark-as-unbought');
			$('#remove-list-component-'+idListComponent).addClass('link-hide');
			$('#edit-list-component-'+idListComponent).addClass('link-hide');
			$('#description-list-component-'+idListComponent).addClass('link-hide');
			$('#quantity-list-component-'+idListComponent).addClass('bought');
		});

//		mark as unbought
		$('#product-list > li > div > input.mark-as-unbought').livequery('click', function(e) {
			var idListComponent = $(this).attr('id');
			list_componentMG.raiseMarkAsUnboughtListComponent(idListComponent);
			$('#'+idListComponent).removeClass('mark-as-unbought');
			$('#'+idListComponent).addClass('mark-as-bought');
			$('#remove-list-component-'+idListComponent).removeClass('link-hide');
			$('#edit-list-component-'+idListComponent).removeClass('link-hide');
			$('#description-list-component-'+idListComponent).removeClass('link-hide');
			$('#quantity-list-component-'+idListComponent).removeClass('bought');
		});
	},

	raiseHideAddTags: function() {
		if ($('#div-add-tags').is(':visible') == true) {
			$('div.tags').show();
			$('a.edit-btn-hide-tags').show();
			$('a.edit-btn-show-tags').hide();
		}
		if (($('#div-add-tags').is(':visible') == false)) {
			$('div.tags').hide();
			$('a.edit-btn-show-tags').show();
			$('a.edit-btn-hide-tags').hide();
		}
	},

	raiseMarkAsBoughtListComponent: function(idListComponent) {
		$.ajax({
			type: "POST",
			dataType: "json",
			url: '/xhr/list/' + idListComponent + '/1/mark_as_bought.action',
			data: {id_list_component: idListComponent},
			success: function(data){
				$('#name-list-component-'+idListComponent).addClass("bought");
			}
		});
	},

	raiseMarkAsUnboughtListComponent: function(idListComponent) {
		$.ajax({
			type: "POST",
			dataType: "json",
			url: '/xhr/list/' + idListComponent + '/0/mark_as_bought.action',
			data: {id_list_component: idListComponent},
			success: function(data){
				$('#name-list-component-'+idListComponent).removeClass("bought");
			}
		});
	},

//	get list component details and show them on right column
	raiseDetailsListComponent: function (idListComponent) {
		$('#right-col .col-content').show();
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/list/get_list_component_all_details',
				data: {id_list_component: idListComponent},
				success: function(data) {
//					highlight active element
					$('#list-details-page').find('li.highlight').removeClass('highlight');
					$('#list-component-'+ idListComponent).addClass('highlight');
//					usuń liste podobnie otagowanych produktów
					list_componentMG.removeTaggedSiblings();
					$('#details-name-list-component').text(data.result.name);
					if (data.result.id_product) {
						$('#right-col').find('.product-only').show();
						productMG.raiseCatalogProductDetails (data);
					} else {
						$('#right-col').find('.product-only').hide();
						list_componentMG.raiseNoCatalogListComponentDetails (data);
					}
				}
		});
	},

	raiseNoCatalogListComponentDetails: function (data) {
//		clear details
		$('div.product-img').children().remove();
		$('#ul-opinion').children('.opinion').remove();
		$('#tags-list > p').remove();

//		usuń liste podobnie otagowanych produktów
		list_componentMG.removeTaggedSiblings();
		$('div.product-img').append(
			'<img id="details-thumb-image-list-component" src="/img/brak-zdjecia.png" alt="Przepraszamy, brak zdjęcia" />'
		);		
//		setting tags list
		list_componentMG.raiseCreateTagsList (data.result.tags);
	},

	raiseCreateTagsList: function (json) {
		$('#tags-list').append('<p></p>');
		$.each(json, function(){
			$('#tags-list > p').append('<a id="a-product-tag-' + this.tag + '" class="bold" href="#">' + this.tag + '</a> ');
		});
		if ($('#tags-list > p').children('.bold').size() == 0) {
			$('#tags-list > p').prepend('Brak tagów powiązanych z produktem.');
		} else {
			$('#tags-list > p').prepend('Tagi powiązane z produktem: ');
		}
	},

//	funkcja usuwająca listę podobnie otagowanych produktów
	removeTaggedSiblings: function () {
		$('#ul-hint-list').slideUp(20, function() {$(this).remove();});
		$('a.sliding-tab').remove();
	},

//	funkcja wysylajaca liste mailem
	raiseSendList: function (idShoppingList, sendToEmail) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/list/send_list',
				data: {id_shopping_list: idShoppingList, send_to_emails: sendToEmail},
				success: function(data) {
					if (data.info.message) {
						$('#msg-mail-sent').hide();
						formMG.formRequest('send-list-form', data.info.message);
					} else {
						formMG.clearMessages('send-list-form');
						formMG.clearFields('send-list-form', '');
						$('#msg-mail-sent').show();
					}
				$('#send-list').removeAttr('disabled');
				}
			});
	},

//	sending list to user
	raiseSendListToUser: function (idShoppingList) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/list/send_list_to_user',
				data: {id_shopping_list: idShoppingList},
				success: function(data) {
						$('#msg-mail-sent').show();
					}
			});
	},

//	setting list messages "Brak zakupionych produktow"/"Brak zakupow na liscie"
	raiseSetListMessages: function (idList, idMessageField, childrenClass) {
		var count_children = $('#'+idList).children('.'+childrenClass).size();
		if (count_children == 0) {
			$('#'+ idMessageField).show();
		} else {
			$('#'+ idMessageField).hide();
		}
	},

//	funkcja, ktora dodaje ocene do produktu
	raiseAddNote: function (note) {
		var idProduct = $('#input-id-product').val();
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/product/add_note',
				data: {id_product: idProduct, note: note},
				success: function(data) {
					var publicNote = data.info.public_note;
					list_componentMG.raiseAddStar(note, publicNote);
				}
			});
	},

//	funkcja, ktora zwraca podswietlone gwiazdki po ocenie produktu
	raiseAddStar: function (note, publicNote) {
//		ustawienie gwiazdek w 'Twoja opinia'
		$('#ul-rating-star-empty').hide();
		$('#ul-rating-star').show();
		$('#ul-rating-star').addClass('rating star-' + note);
//		ustawienie gwiazdek w 'Wasza opinia'
		$('#ul-public-rating-star').show();
		$('#span-public-user-star-empty').hide();
		$('#span-public-user-star').show();
		$('#ul-public-rating-star').removeClass();
		$('#ul-public-rating-star').addClass('public-rating star-' + publicNote);
	},

//	funkcja zwracajaca liste produktow pasujacych do danego taga
	raiseFindProducts: function (tag) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/product/show_products',
				data: {tag: tag},
				success: function(data) {
					list_componentMG.raiseShowProducts(data.result);
				}
			});
	},

	raiseUpdateTagsList: function (idListComponent) {
		$('#tags-list > p').remove();
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/list/get_updated_tags',
				data: {id_list_component: idListComponent},
				success: function(data) {
					list_componentMG.raiseCreateTagsList(data.result.tags);
				}
			});
	},

//	funkcja pokazujaca liste produktow pasujacych do danego taga
	raiseShowProducts: function (json) {
//		wstaw listę podobnie otagowanych produktów
		$('#slide-wrapper').append('<ul id="ul-hint-list" style="display:none;"></ul>');
		$('#slide-wrapper').show();
		if (json == '') {
			$('#ul-hint-list').append(
				'<li>Brak produktów powiązanych z danym tagiem</li>'
			);
		}
		$.each(json, function(){
			var list_type = '';
			if ($('#slide-wrapper').hasClass('with-category')) {
				list_type = 'with-category';
			}
			$('#ul-hint-list').append(
				'<li>'+
					'<a href="/product/'+this.id+'/list.html">'+this.name+'</a>'+
					'<a href="#" class="a-hint-list ' + list_type + '" id='+this.id+' title="Dodaj do listy zakupów"></a>'+
				'</li>'
			);
		});
		$('#ul-hint-list').show(550);
	},

//	funkcja dodajaca produkt wyszukany z tagow do listy komponentow
	raiseAddListComponentFromTag: function (idProduct, idShoppingList, list_type) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/list/add_component.action',
				data: {id_product: idProduct, id_shopping_list: idShoppingList, adding_type: 'tag'},
				success: function(data) {
					if (list_type == 'with-category') {
//						if this is the first list component in this category add category to the list
						if (data.info.category_action == 'add_category') {
							list_componentMG.raiseAddCategoryToList(data.info.category_id, data.info.category_name, data.info.category_position);
						}
					}
//					add row on components list
					list_componentMG.raiseAddRowToList(data, 'style="display:none"');
					list_componentMG.raiseEditListComponent(data.result.id);
					list_componentMG.raiseDetailsListComponent(data.result.id);
				}
			});
	},

	raiseRemoveListComponent: function (idListComponent, type, list_type) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/list/delete_component.action',
				data: {id_list_component : idListComponent},
				success: function(data) {
//					check if deleting component is the one we preview on right column
					if ($('#list-component-'+idListComponent).hasClass('highlight')) {
						var change_highlight_element = true;
					} else {
						var change_highlight_element = false;
					}
					var active_li = $('#product-list').find('li.highlight');
					var idActiveListComponent = active_li.attr('id').replace('list-component-', '');
					$('#list-component-'+idListComponent).remove();
					if (type == 'edit_form') {
						$('#edit-list-component').hide();
					}
					if (list_type == 'with-category') {
//						check if the removed component was last in this category, if so remove the category name from list
						if (data.info.category_action == 'remove_category') {
							$('#category-'+data.info.category_id).remove();
						}
					}
					if (change_highlight_element == true) {
						list_componentMG.raiseChangeActiveElement();
					}
//					usuwamy ostatni produkt z listy
					if ($('#product-list').children('.list-component').size() == '0') {
//						schowanie linkow do zmiany wyswietlania listy (z kategoriami lub bez kategorii)
						$('#span-list-type').addClass('link-hide');
//						pokazanie linka do sugestii
						$('#a-link-to-hints').show();
					}
				}
			});
	},

	raiseChangeActiveElement: function () {
		if ($('#product-list').children('.list-component').size() != '0') {
			list_componentMG.raiseDetailsListComponent($('#product-list > li.list-component:first').attr('id').replace('list-component-', ''));
		} else {
			$('#right-col .col-content').hide();
		}
	},

	raiseAddActionListComponent: function (list_type) {
		var nameVal = $('#input-add-name').val();
		var quantityVal = $('#input-add-quantity').val();
		var descriptionVal = $('#textarea-add-description').val();
		var tagVal = $('#input-add-tag').val();
		var idShoppingListVal = $('#input-id-shopping-list').val();
		var addingType = $('#input-adding-type').val();
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/list/add_component.action',
				data: {name: nameVal, 
					   quantity: quantityVal, 
					   description: descriptionVal, 
					   tag: tagVal, 
					   id_shopping_list: idShoppingListVal,
					   adding_type: addingType},
				success: function(data) {
//					if validation errors add messages
					formMG.clearMessages('custom-doc');
					if (data.info.message) {
						formMG.formRequest('list-component-add-form', data.info.message);
					} else {
						if ($('#span-list-type').hasClass('link-hide')) {
							$('#span-list-type').removeClass('link-hide');
						}
						if (list_type == 'with-category') {
//							if this is the first list component in this category add category to the list
							if (data.info.category_action == 'add_category') {
								list_componentMG.raiseAddCategoryToList(data.info.category_id, data.info.category_name, data.info.category_position);
							}
						}
//						add row on components list
						list_componentMG.raiseAddRowToList(data, '');
						$('div.message-box').hide();
						list_componentMG.raiseDetailsListComponent(data.result.id);
						formMG.clearFields('list-component-add-form', ' > div.top > div.content > div.row');
//						schowanie linka do sugestii
						if ($('#a-link-to-hints').is(':visible') == true) {
							$('#a-link-to-hints').hide();
						}
					}
				$('#'+list_type+'-add-list-component').removeAttr('disabled');
				}
			});
	},

	raiseEditListComponent: function (idListComponent) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/list/get_list_component_edit_details',
				data: {id_list_component : idListComponent},
				success: function(data) {
					if ($('#edit-list-component').is(':visible')) {
						$('#edit-list-component').hide();
						$('#product-list').children('.list-component').removeClass('highlight').show();
					}
					$('#input-edit-name').val(data.result.name);
					$('#input-edit-quantity').val(data.result.quantity);
					$('#textarea-edit-description').val(data.result.description);
					$('#input-edit-tag').val(data.result.tag);
					$('#input-edit-id-list-component').val(data.result.id);
					$('#edit-list-component').insertAfter($('#list-component-'+data.result.id));
					$('#list-component-'+data.result.id).hide();
					$('#edit-list-component').show();
					$('div.message-box').hide();
				}
			});
	},

	raiseCancelEditListComponent: function(idListComponent) {
		$('#edit-list-component').hide();
		$('#list-component-'+idListComponent).show();
		formMG.clearMessages('list-component-edit-form');
	},

	raiseAddCategoryToList: function(category_id, category_name, category_position) {
		$('#product-list').append(
			'<li id="category-'+ category_id + '" class="category-title">' +
				'<span>' +
					category_name +
				'</span>' +
			'</li>'
		);
		if (category_position || category_position == 0) {
			$('#category-'+ category_id).insertBefore('#category-'+category_position);
		}
	},

//	adding new row on list after adding/editing component
	raiseAddRowToList: function(data, display) {
		var checkbox = '';
		if (data.info.shopping_list_status == 'current') {
			checkbox = '<div>' +
				'<input type="checkbox" id="' + data.result.id + '" class="mark-as-bought" name="bought" value="' + data.result.id + '" />' +
			'</div>';
		}
		$('#product-list').append(
			'<li id="list-component-'+ data.result.id +'" class="list-component" '+ display +'>' +
				checkbox +
				'<div class="item-name">' +
					'<a id="name-list-component-'+ data.result.id + '" href="/list/'+ data.result.id_shopping_list + '/list.html?view_id_list_component=' + data.result.id +'">' + data.result.name + '</a>' +
					'<span id="description-list-component-'+ data.result.id + '">' + data.result.description +'</span>' +
				'</div>' +
				'<div class="item-qty">' +
					'<p id="quantity-list-component-' + data.result.id + '">' + 
						data.quantity +
					'</p>' +
				'</div>' +
				'<div class="item-actions">' + 
					'<a href="#" id="remove-list-component-' + data.result.id + '" class="this-remove delete-with-category" title="Usuń produkt">Usuń produkt</a>' +
					'<a href="#" id="edit-list-component-' + data.result.id + '" class="this-edit" title="Edytuj produkt">Edytuj produkt</a>' +
				'</div>' + 
			'</li>'
		);
		$('#list-component-'+data.result.id).insertAfter('#category-'+data.result.category_id);
	},

	raiseEditActionListComponent: function(idListComponent, list_type) {
		var nameVal = $('#input-edit-name').val();
		var quantityVal = $('#input-edit-quantity').val();
		var descriptionVal = $('#textarea-edit-description').val();
		var tagVal = $('#input-edit-tag').val();
		var idListComponentVal = $('#input-edit-id-list-component').val();
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/list/edit_component.action',
				data: {edit_name: nameVal, edit_quantity: quantityVal, edit_description: descriptionVal, edit_tag: tagVal, id_list_component: idListComponentVal},
				success: function(data) {
//					if validation errors add messages
					if (data.info.message) {
						formMG.formRequest('list-component-edit-form', data.info.message);
					} else {
						$('#edit-list-component').hide();
						if (list_type == 'with-category') {
//							if this is the first list component in this category add category to the list
							if (data.info.add_category_action == 'add_category') {
								list_componentMG.raiseAddCategoryToList(data.info.add_category_id, data.info.add_category_name, data.info.category_position);
							}
//							if there are no left list components in this category remove this category
							if (data.info.remove_category_action == 'remove_category') {
								$('#category-'+data.info.remove_category_id).remove();
							}
						}
//						if category was changed remove row and add as new one
						if (data.info.component_category_status == 'changed') {
							$('#list-component-'+data.result.id).remove();
//								add row on components list
							list_componentMG.raiseAddRowToList (data, '');
							list_componentMG.raiseDetailsListComponent(data.result.id);
						} else {
							$('#name-list-component-'+data.result.id).text(data.result.name);
							$('#description-list-component-'+data.result.id).text(data.result.description);
							if (data.result.quantity) {
								var quantity = data.quantity;
							} else {
								var quantity = '';
							}
							$('#quantity-list-component-'+data.result.id).text(quantity);
							$('#list-component-'+data.result.id).show();
							list_componentMG.raiseUpdateTagsList(idListComponent);
						}
					}
				}
		});
	}
};

// PRODUCT MANAGER //
// funkcje dla katalogu (do kategorii, podkategorii i produktów) //
var productMG = {

//	constructor: catch events
	init: function(){

//		dodawanie oceny do produktu
		$('#user-note > ul > li.add-note').livequery('click', function(e){
			var note = ($(this).attr('id').replace('li-add-note-', ''));
			list_componentMG.raiseAddNote(note);
			return false;
		});

//		chowanie listy podobnie otagowanych poduktów
		$('#slide-wrapper a#close-tagged-list').livequery('click', function(e) {
//			usuń listę podobnie otagowanych produktów
			productMG.removeTaggedSiblings();
			$('#slide-wrapper').hide();
			return false;
		});

//		wywolanie funkcji dodawania opinii do produktu
		$('#add-product-opinion').livequery('click', function(e){
//			disable submit for no double adding
			$(this).attr('disabled', 'disabled');
			$('#opinion-add-description-error .message-box').remove();
			var idProduct = $('#input-id-product').val();
			productMG.raiseAddProductOpinion(idProduct);
			return false;
		});

//		funkcja wywolujaca funkcje zwracajaca liste produktow dla danej kategorii
		$('div.item-top > div.item-content > a.category').livequery('click', function(e){
			var idCategory = ($(this).attr('id').replace('input-id-category-', ''));
			$('#span-product-details').hide();
			$('#a-add-product').hide();
			var activeCategory = $('div.col-content').find('li.highlight, li.active');
			if (activeCategory) {
				activeCategory.removeClass('highlight active');
				activeCategory.find('ul.subcategories-list').slideUp(300, function() {$(this).children().remove(); $(this).hide();});
			}
			$('#ul-products').slideUp(300, function() {$(this).children().remove(); $(this).hide();
				$('#ul-subcategories-'+idCategory).children().remove();
				$('h3.products-empty').hide();
				productMG.raiseReturnProductsFromCategory(idCategory);
			});
			return false;
		});

//		funkcja wywolujaca funkcje zwracajaca liste produktow dla danej podkategorii
		$('a.subcategory').livequery('click', function(e){
			$('a.subcategory').removeClass('current');
			$(this).addClass('current');
			$('#span-product-details').hide();
			var idSubcategory = ($(this).attr('id').replace('li-id-subcategory-', ''));
			$('#ul-products').slideUp(300, function() {$(this).children().remove(); $(this).hide();
			productMG.raiseReturnProductsFromSubcategory(idSubcategory);});
			return false;
		});

//		funkcja wywolujaca funkcje zwracajaca dane wybranego produktu
		$('a.product-details').livequery('click', function(e){
			var idProduct = ($(this).attr('id').replace('li-id-product-', ''));
			productMG.raiseShowProduct(idProduct);
			return false;
		});

//		adding product to list from catalog
		$('#sel-user-lists').livequery('change', function(e){
			var idUserList = $('#sel-user-lists').val();
			var idProduct = $('#input-id-product').val();
			$('#span-add-product-to-list-from-details').hide();
			$('#a-add-to-list-from-details-'+idProduct).removeClass('image-no-add-to-list-from-details');
			$('#a-add-to-list-from-details-'+idProduct).addClass('image-add-to-list-from-details');
			productMG.raiseAddProductToListFromCatalog(idProduct, idUserList);
		});

//		click "Pokaz wiecej" on opinions list
		$('#unroll-opinions-list').livequery('click', function(e){
			$('#ul-opinion').children('.opinion').show(550);
			$('#unroll-opinions-list').removeClass('visible');
			$('#roll-opinions-list').addClass('visible');
			return false;
		});

//		click "Schowaj" on opinions list
		$('#roll-opinions-list').livequery('click', function(e){
			$('#ul-opinion > li.opinion:gt(4)').slideUp(300, function () {$(this).hide();});
			$('#unroll-opinions-list').addClass('visible');
			$('#roll-opinions-list').removeClass('visible');
			return false;
		});

		$('select.catalog-select-list').livequery('change', function(e){
			var idProduct = $(this).attr('id');
			var idUserList = $(this).val();
			productMG.raiseAddProductToListFromCatalog(idProduct, idUserList);
		});

//		po wcisnieciu ikonki 'dodaj do listy' pokazanie selecta z listami uzytkownika
		$('a.image-add-to-list').livequery('click', function(e){
			var idProduct = ($(this).attr('id').replace('a-add-to-list-', ''));
			$('#a-add-to-list-'+idProduct).removeClass('image-add-to-list');
			$('#a-add-to-list-'+idProduct).addClass('image-no-add-to-list');
			$('#'+idProduct).show();
			return false;
		});

//		schowanie selecta z listami uzytkownika
		$('a.image-no-add-to-list').livequery('click', function(e){
			var idProduct = ($(this).attr('id').replace('a-add-to-list-', ''));
			$('#a-add-to-list-'+idProduct).removeClass('image-no-add-to-list');
			$('#a-add-to-list-'+idProduct).addClass('image-add-to-list');
			$('#'+idProduct).hide();
			return false;
		});

		$('a.image-add-to-list-from-details').livequery('click', function(e){
			var idProduct = ($(this).attr('id').replace('a-add-to-list-from-details-', ''));
			$('#span-add-product-to-list').hide();
			$('#a-add-to-list-from-details-'+idProduct).removeClass('image-add-to-list-from-details');
			$('#a-add-to-list-from-details-'+idProduct).addClass('image-no-add-to-list-from-details');
			$('#span-add-product-to-list-from-details').show();
			return false;
		});

		$('a.image-no-add-to-list-from-details').livequery('click', function(e){
			var idProduct = ($(this).attr('id').replace('a-add-to-list-from-details-', ''));
			$('#span-add-product-to-list').show();
			$('#a-add-to-list-from-details-'+idProduct).removeClass('image-no-add-to-list-from-details');
			$('#a-add-to-list-from-details-'+idProduct).addClass('image-add-to-list-from-details');
			$('#span-add-product-to-list-from-details').hide();
			return false;
		});

//		recommend the product
		$('a.product-recommend').livequery('click', function(e) {
			var idProduct = $('#input-id-product').val();
			productMG.raiseAddRecommendation(idProduct);
			return false;
		});
		
//		marking as bought from hints
		$('input.mark-as-bought-from-hint').livequery('click', function(e){
			var idBoughtProduct = $(this).attr('id').replace('mark-as-bought-from-hint-', '');
			window.location = '/message/hint/'+ idBoughtProduct +'/mark_as_bought.action';
			return false;
		})

	},
	
//	add product recommendation
	raiseAddRecommendation: function(idProduct) {
		$.ajax({
			type: "POST",
			dataType: "json",
			url: '/xhr/product/add_recommendation',
			data: {id_product: idProduct},
			success: function(data) {
				$('#a-recommend').hide();
				$('#label-recommend').show();
				productMG.raiseSetRecommendationInfo(data.result);
			}
		});
		
	},

//	adding product to shopping list from catalog
	raiseAddProductToListFromCatalog: function (idProduct, idUserList) {
		$('#'+idProduct).hide();
		$('#a-add-to-list-'+idProduct).removeClass('image-no-add-to-list');
		$('#a-add-to-list-'+idProduct).addClass('image-add-to-list');
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/list/add_component.action',
				data: {id_product: idProduct, id_shopping_list: idUserList, adding_type: 'catalog'},
				success: function(data) {
					$('#sel-user-lists').val('');
					$('select.select-list').val('');
					productMG.raiseSetAverageBuying(data.result.average_buying);
				}
			});
	},

	raiseAddRowToProductsList: function (json, user_lists) {
		if (json == 0) {
//			no products in category/subcategory
			$('#ul-products').append(
				'<li><div class="item-top"><div class="item-content">'+
				'Brak produktów' +
				'</div></div><div class="item-bottom"></div></li>'
			);
		} else {
			$.each(json, function(){
				$('#ul-products').append(
					'<li id="li-product-'+this.id+'"><div class="item-top"><div class="item-content">'+
					'<a href="#" class="product-details" id="li-id-product-'+this.id+'">'+this.name+'</a><br />'+
					'<a href="#" class="image-add-to-list" id="a-add-to-list-'+this.id+'" title="Dodaj do listy zakupów"></a>'+
					'<select style="display: none;" class="catalog-select-list" id="'+this.id+'">'+
					'<option>Dodaj do listy</option>'+
					user_lists+
					'</select>'+
					'</div></div><div class="item-bottom"></div></li>'
				);
			});
		}
		$('#ul-products').show(550);
	},

//	funkcja, ktora dodaje opinie do produktu
	raiseAddProductOpinion: function (idProduct) {
		var description = $('#textarea-add-opinion').val();
		var userLogin = $('#input-user-login').val();
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/product/add_opinion',
				data: {id_product: idProduct, description: description},
				success: function(data) {
					formMG.clearMessages('product-opinion-add-form');
//					if validation errors add messages
					if (data.info.message) {
						formMG.formRequest('product-opinion-add-form', data.info.message);
					} else {
						productMG.raiseCreateOpinionList(data.result);
						formMG.clearFields('product-opinion-add-form', '');
						list_componentMG.raiseSetListMessages('ul-opinion', 'msg-no-opinion', 'opinion');
					}
					$('#add-product-opinion').removeAttr('disabled');
				}
			});
	},

//	add new opinion/create opinions list
	raiseCreateOpinionList: function (json) {
		$.each(json, function(){
			var avatar = this.avatar;
			$('#ul-opinion').prepend(
				'<li class="opinion">' +
					'<a href="/friend/'+this.id_user+'/friend.html" target="_blank">'+
						'<div class="mini-image-wrapper">' +
							'<div class="content">' +
								'<div class="image">' +
									avatar +
								'</div>' +
								'<span>' + this.author + '</span>' +
							'</div>'+
							'<div class="mini-image-footer"></div>' +
						'</div>' +
					'</a>'+
					'<div class="text">' +
					'<p><span class="time">'+ this.creation_time+'</span></p>'+
						this.description +
					'</div>' +
				'</li>'
			);
		});
		productMG.raiseSetProductOpinionsVisibility ();
	},

	raiseSetProductOpinionsVisibility: function () {
		var countOpinion = $('#ul-opinion').children('.opinion').size();
		if (countOpinion > 5) {
			$('#ul-opinion > li.opinion:gt(4)').hide();
			$('#unroll-opinions-list').addClass('visible');
		} else {
			$('#unroll-opinions-list').removeClass('visible');
			$('#roll-opinions-list').removeClass('visible');
		}
	},

//	set average buying when product details are loaded or product id added to list from catalog
	raiseSetAverageBuying: function (average_buying) {
		if (average_buying) {
			$('#details-average-buying-span-topic').text('Kupowany średnio co:');
			$('#details-average-buying-list-component').text(average_buying);
		} else {
			$('#details-average-buying-span-topic').text('Produkt nie został zakupiony.');
			$('#details-average-buying-list-component').text('');
		}
	},

//	funkcja zwracajaca liste produktow dla danej kategorii
	raiseReturnProductsFromCategory: function(idCategory) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/product/products_list_from_catalog',
				data: {id_category: idCategory},
				success: function(data) {
					productMG.raiseShowProductsFromCategory(data, idCategory);
				}
		});
	},

//	funkcja zwracajaca liste produktow dla danej podkategorii
	raiseReturnProductsFromSubcategory: function(idSubcategory) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/product/products_list_from_catalog',
				data: {id_subcategory: idSubcategory},
				success: function(data) {
					productMG.raiseShowProductsFromSubcategory(data, idSubcategory);
				}
		});
	},

//	funkcja zwracajaca dane o wybranym produkcie i ustawiajaca klasy
	raiseShowProduct: function (idProduct) {
		$('#component-name a.image-add-to-list-from-details').remove();
		$('#component-name a.image-no-add-to-list-from-details').remove();
		if ($('#span-add-product-to-list-from-details').is(':visible')) {
			$('#span-add-product-to-list-from-details').hide();				
			$('#component-name a.image-add-to-list-from-details').show();
		}
		$('a.product-details').removeClass('current');
		$('ul#ul-products').find('li.highlight').removeClass('highlight');
		$('#li-id-product-'+idProduct).addClass('current');
		$('#component-name').append(
			'<a href="#" id="a-add-to-list-from-details-'+idProduct+'" class="image-add-to-list-from-details" title="Dodaj do listy zakupów"></a>'
		);
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/product/details',
				data: {id_product: idProduct},
				success: function(data) {
					$('#product-empty').hide();
					$('#span-product-details').show();
					productMG.raiseCatalogProductDetails(data, 'catalog');
					$('#li-product-'+idProduct).addClass('highlight');
				}
		});
	},

//	show recommendation info
	raiseSetRecommendationInfo: function(countRecommendations) {
		$('#details-recommendation-span-topic').text('Polecany przez: ');
		$('#details-product-recommendation').text(countRecommendations)
		if (countRecommendations == '1') {
			$('#details-product-recommendation').append(' użytkownika');
		}
		else {
			$('#details-product-recommendation').append(' użytkowników');
		}
	},
	
//	funkcja pokazujaca szczegoly produktu
	raiseCatalogProductDetails: function (data, from) {
//		clear details
		$('div.product-img').children().remove();
		$('#ul-opinion').children('.opinion').remove();
		$('#tags-list > p').remove();
		formMG.clearFields('product-opinion-add-form', '');
//		usuń listę podobnie otagowanych produktów
		productMG.removeTaggedSiblings();
		$('#ul-public-rating-star').removeClass('star-0 star-1 star-2 star-3 star-4 star-5');
		$('#ul-rating-star').removeClass('star-0 star-1 star-2 star-3 star-4 star-5');
		$('#details-name-list-component').text(data.result.name);

//		if there is no note hide stars and show information "Produkt nie został oceniony"
		if (data.result.note == '0') {
			$('#ul-public-rating-star').hide();
			$('#span-public-user-star').hide();
			$('#span-public-user-star-empty').show();
		} else {
			$('#span-public-user-star-empty').hide();
			$('#span-public-user-star').show();
			$('#ul-public-rating-star').show().addClass('star-'+data.result.note);
		}
//		showing how many recommendations product has
		if (data.result.count_recommendations == '0') {
			$('#details-recommendation-span-topic').text('Produkt nie został polecony');
			$('#details-product-recommendation').text('');
		} else {
			productMG.raiseSetRecommendationInfo(data.result.count_recommendations);
		}
//		showed when friends recommended this product
		if (data.result.friends_recommendations) {
			$('#details-product-friends-recommendations').children().remove();
			$('#friends-recommendations').show();
			$.each(data.result.friends_recommendations, function(){
			$('#details-product-friends-recommendations').prepend(
				'<a class="author" href="/friend/'+ this[0] +'/friend.html">'+this[1]+'</a>'
			);
			});
		} else {
			$('#friends-recommendations').hide();
		}
//		show/hide link Poleć
		if (data.result.user_recommendation == '0') {
			$('#a-recommend').show();
			$('#label-recommend').hide();
		} else {
			$('#a-recommend').hide();
			$('#label-recommend').show();
		}
		if (data.result.note_product_user) {
			$('#ul-rating-star').show().addClass('star-'+data.result.note_product_user.note);
			$('#ul-rating-star-empty').hide();
		} else {
			$('#ul-rating-star-empty').show();
			$('#ul-rating-star').hide();
		}
		if (data.result.product_image) {
			$('div.product-img').append(
				'<a id="details-image-list-component" href="/product/'+data.result.product_image+'/image.html" target="_blank">'+
				'<img id="details-thumb-image-list-component" src="/product_images/mini_product_images/'+data.result.product_image+'" alt="product" />'+
				'</a>'
			);
		} else {
			$('div.product-img').append(
				'<img id="details-thumb-image-list-component" src="/img/brak-zdjecia.png" alt="Przepraszamy, brak zdjęcia" />'
			);
		}
		if (from == 'catalog') {
			$('#input-id-product').val(data.result.id);			
		} else {
			$('#input-id-product').val(data.result.id_product);			
//			setting tags list
			list_componentMG.raiseCreateTagsList(data.result.tags);
		}

//		setting average buying
		productMG.raiseSetAverageBuying(data.result.average_buying);
//		setting opinions list
		productMG.raiseCreateOpinionList(data.result.product_opinions);
//		setting product opinions
		list_componentMG.raiseSetListMessages('ul-opinion', 'msg-no-opinion', 'opinion');
	},

//	funkcja pokazujaca liste podkategorii i produktow dla danej kategorii
	raiseShowProductsFromCategory: function (data, idCategory) {
		var products = data.result;
		var user_lists = data.user_lists;
		var subcategories = data.subcategories;
		var categoryName = data.category_name;
		$('h3.products').show();
		$('h3.products').text('Produkty z kategorii '+categoryName);
		$('#li-category-'+idCategory).addClass('highlight active');
		productMG.raiseAddRowToProductsList(products, user_lists);
//		if there are no subcategories in category
		if (data.subcategories == 0){
			$('#ul-subcategories-'+idCategory).append(
				'<li>Brak podkategorii</li>'
			);
		} else {
			$.each(subcategories, function(){
				$('#ul-subcategories-'+idCategory).append(
					'<li id="li-subcategory-'+this.id+'"><a href="#" id="li-id-subcategory-'+this.id+'" class="subcategory">'+this.name+'</a></li>'
				);
			});
		}
		$('#ul-subcategories-'+idCategory).show(550);
	},

//	funkcja pokazujaca liste produktow dla danej podkategorii
	raiseShowProductsFromSubcategory: function (data, idSubcategory) {
		var products = data.result;
		var user_lists = data.user_lists;
		var subcategoryName = data.subcategory_name;
		var categoryName = data.category_name;
		$('h3.products').text('Produkty z kategorii ' + categoryName + ', podkategorii '+subcategoryName);
		productMG.raiseAddRowToProductsList(products, user_lists);
	},

//	funkcja usuwająca listę podobnie otagowanych produktów
	removeTaggedSiblings: function () {
		$('#ul-hint-list').children().remove();
		$('#ul-hint-list').remove();
		$('a.sliding-tab').remove();
	}
};

var subcategoryMG = {

	set_subcategories_list: function(product_subcategory) {
		var idCategory = $('#sel-category').val();
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/set_subcategories_list',
				data: {id_category: idCategory},
				success: function(subcategory_data) {
					$('#sel-subcategory').children().remove();
					$.each(subcategory_data.subcategories_list, function(j){
					$('#sel-subcategory').append('<option id="sel-subcategory-' + subcategory_data.subcategories_list[j][1] + '" value="' + subcategory_data.subcategories_list[j][1] + '">' + subcategory_data.subcategories_list[j][0] + '</option>');

					if (product_subcategory != '' && product_subcategory==subcategory_data.subcategories_list[j][1]){
						$('#sel-subcategory-'+product_subcategory).attr('selected', 'selected');
					}
 				});
			}
		});
	}
}

var messageMG = {
	//	constructor: catch events
	init: function(){
		
//		hints list on tab message: set background none to every first li after li with class title
		var firstElementsOfHints = $('#ul-basket-hints').find('li.title').next().attr('style', 'background:none;');
		
//		submit form to add messages
		$('#submit-add-message').livequery('click', function(e){
			$(this).attr('disabled', 'disabled');
			messageMG.raiseAddMessage();
			return false;
		});
		
//		on choosing message area radiobutton show messages from this area
		$('.message-area').bind('change', function(e){
			var messageArea = ($(this).val());
			var messageBox = $('#message-box').val();
			messageMG.raiseReturnMessages(messageArea, messageBox);
			return false;
		});
		
//		showing products which matches clicked basket product tag
		$('a.basket-product-tag').bind('click', function(e){
			var categoryTagString = $(this).attr('id').replace('-', ' ');
			categoryTagString = categoryTagString.split(' ');
			var idCategory = categoryTagString[0];
			var basketProductTag = categoryTagString[1];

//			if basket tag user clicked is already expanded rollup products and remove expanded class
			if ($('#category-'+basketProductTag).hasClass('expanded')){
				$('#category-'+basketProductTag).removeClass('expanded');
				$('#ul-basket-tag-products').slideUp(300, function() {$(this).remove();});
			} else {
//				check if any other basket tag is rolled down
				var activeRow = $('#ul-basket-hints').find('li.expanded');
				if (activeRow) {
					$('#ul-basket-hints').find('li.expanded').removeClass('expanded');
					$('#ul-basket-tag-products').remove();
				}
				$('#category-'+basketProductTag).addClass('expanded');
				messageMG.raiseReturnBasketProductsHints(idCategory, basketProductTag);
			}
			return false;
		});
	},
	
//	return message from choosen area, and if we are on friends tab take only our friends message
	raiseReturnMessages: function(messageArea, messageBox) {
		$.ajax({
			type: "POST",
			dataType: "json",
			url: '/xhr/get_messages',
			data: {message_area: messageArea, message_box: messageBox},
			success: function(data) {
				$('#messages-list').children('.message').slideUp(300, function() {$(this).remove();});
//				if there are no user messages show message 'Brak wiadomosci'
				if (data.result == 0) {
					$('#messages-list').prepend(
						'<li id="message-0" class="message no-location" style="background: none;">' +
							'Brak wiadomości' +
						'</li>'
					);
					$('#message-0').insertAfter('#messages-list > li.no-location:last');
					$('#messages-list li.message').show(550);
				} else {
					messageMG.raiseCreateMessagesList(data.result);
				}
			}
		});
	},
	
//	create messages list, adding_type set if function should prepend or append li
	raiseCreateMessagesList: function(json) {
		$.each(json, function(){
			var avatar = this.avatar;
			$('#messages-list').prepend(
				'<li id="message-'+this.id+'" class="message" style="display:none;">' +
					'<div class="mini-image-wrapper">' +
						'<div class="content">' +
							'<a href="/friend/'+this.id_user+'/friend.html">'+
							'<div class="image">' +
								avatar +
							'</div>' +
							'<span>' + this.author + '</span>' +
							'</a>'+
						'</div>'+
						'<div class="mini-image-footer"></div>' +
					'</div>' +
					'<div class="text">' +
						'<p><span class="time">' + this.creation_time + '</span></p>' +
						this.message +
					'</div>' +
				'</li>'
			);
			$('#message-'+this.id).insertAfter('#messages-list > li.no-location:last');
		});
		if ($('#messages-list').children('.message').size() > 3) {
			$('#messages-list li.message:last').remove();
		}
		$('#messages-list li.message:first').attr('style', 'background: none;');
		$('#messages-list li.message:eq(1)').removeAttr('style');
		$('#messages-list li.message').show(550);
		
	},
	
//	check if there are validation errors, if not add message
	raiseAddMessage: function() {
		var message = $('#textarea-add-message').val();
//		getting message box to know if message list should be updated - if it is friends message then it shouldn't be updated
		var messageBox = $('#message-box').val();
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/add_message',
				data: {message: message, message_box: messageBox},
				success: function(data) {
					formMG.clearMessages('custom-doc');
//					if validation errors add messages
					if (data.info.message) {
						formMG.formRequest('add-message-form', data.info.message);
					} else {
//						show message that message was added
						$('#add-message-form').prepend('<div class="message-box success"><p>Dodano wiadomość</p></div>');
//						if user is on friends messages tab don't add his new message to the message list
						if (data.result != 0) {
							if ($('#message-0')){
								$('#message-0').remove();
							}
							messageMG.raiseCreateMessagesList(data.result);
						}
						formMG.clearFields('add-message-form', '');
					}
					$('#submit-add-message').removeAttr('disabled');
 				}
				});
		},
	
//	get products from category which contains basket tag
	raiseReturnBasketProductsHints: function(idCategory, basketProductTag) {
		$.ajax({
				type: "POST",
				dataType: "json",
				url: '/xhr/get_basket_tag_products',
				data: {id_category: idCategory, basket_product_tag: basketProductTag},
				success: function(data) {
					if ($('#ul-basket-tag-products')) {
						$('#ul-basket-tag-products').slideUp(300, function() {$(this).remove();});
					}
					$('#'+idCategory+'-'+basketProductTag).append('<ul id="ul-basket-tag-products" style="display:none;"></ul>');
					$('#ul-basket-tag-products').insertAfter($('#'+idCategory+'-'+basketProductTag));
					messageMG.raiseShowBasketTagProducts(data.result, data.user_lists);
 				}
				});
	},
	
//	show products from category which contains basket tag as list
	raiseShowBasketTagProducts: function(json, user_lists){
		if (json == '') {
			$('#ul-basket-tag-products').append(
				'<li>Brak produktów</li>'
			);
		}
		$.each(json, function(){
			$('#ul-basket-tag-products').append(
				'<li>'+
					'<a href="/product/'+this.id+'/list.html">'+this.name+'</a>'+
					'<a id="a-add-to-list-from-hint-'+this.id+'" class="add-to-list-from-hint" href="#"></a>'+
					'<select style="display: none;" class="select-list hint-in-basket" id="select-list-'+this.id+'">'+
					'<option>Dodaj do listy</option>'+
					user_lists +
					'</select>'+
				'</li>'
			);
			
		});
		$('#ul-basket-tag-products').show(550);
	}
}

// FORM MANAGER //
var formMG = {

	clearFields: function(form_id, source) {
		$('#' + form_id + source).find('input[type=text], textarea').val('');
	},

//	remove all error elements and clear all error classes from the form
	clearMessages: function (form_id) {
		$('#'+form_id).find('.msg-error').remove();
		$('#'+form_id).find('.warning').remove();
		$('#'+form_id).find('.success').remove();
	},

	formRequest: function (form_id, errors) {
		formMG.clearMessages(form_id);
		if (errors) {
//			call proper validation method in dependence on the form id
			switch(form_id) {
				case 'list-component-add-form':
					formMG.validateListComponentAdd(errors);
					break;
				case 'list-component-edit-form':
					formMG.validateListComponentEdit(errors);
					break;
				case 'product-opinion-add-form':
					formMG.validateOpinionAdd(errors);
					break;
				case 'send-list-form':
					formMG.validateSendListByEmail(errors);
					break;
				case 'add-message-form':
					formMG.validateMessageAdd(errors);
					break;
				default:
			}
		}
	},

//	component add
	validateListComponentAdd: function (errors) {
		if (errors.name) {
			$('#list-component-add-form .top .content').prepend('<div class="message-box warning"><p>'+errors.name+'</p></div>');
		}
		if (errors.quantity) {
			$('#list-component-add-form .top .content').prepend('<div class="message-box warning"><p>'+errors.quantity+'</p></div>');
		}
	},

//	send list by email
	validateSendListByEmail: function (errors) {
		if (errors.send_to_emails) {
			$('#send-list-form').prepend('<div class="message-box warning"><p>'+errors.send_to_emails+'</p></div>');
		}
	},

//	component edit
	validateListComponentEdit: function (errors) {
		if (errors.edit_name) {
			$('#list-component-edit-form').prepend('<div id="list-component-edit-name-error" class="message-box warning"><p>'+errors.edit_name+'</p></div>');
		}
		if (errors.edit_quantity) {
			$('#list-component-edit-form').prepend('<div id="list-component-edit-quantity-error" class="message-box warning"><p>'+errors.edit_quantity+'</p></div>');
		}
	},

//	opinion add
	validateOpinionAdd: function (errors) {
		if (errors.description) {
			$('#opinion-add-description-error').prepend('<div class="message-box warning"><p>'+errors.description+'</p></div>');
		}
	},

//	message add
	validateMessageAdd: function (errors) {
		if (errors.message) {
			$('#add-message-form').prepend('<div class="message-box warning"><p>'+errors.message+'</p></div>');
//			$('#add-message-msg').prepend('<div class="message-box warning"><p>'+errors.message+'</p></div>');
		}
	}
};

//	Finding min and max values in array from http://snippets.dzone.com/posts/show/769
	Array.prototype.min = function(){ return Math.min.apply({},this) };
	Array.prototype.max = function(){ return Math.max.apply({},this) };

	$.fn.masonry = function() {
		this.each(function() {

			var wall = $(this);

			if ( wall.children().length > 0 ) { // check if the element has anything in it

				if( wall.children('.masonryWrap').length == 0 ) {      // checks if the masonryWrap div is already there
					wall.wrapInner('<div class=\"masonryWrap\"></div>');
				}
				var mWrap = wall.children('.masonryWrap');

				var brick = mWrap.children();
				var brickW = brick.outerWidth(true);
				var colCount = Math.floor( mWrap.width() / brickW ) ;

				var colH=new Array();
				for ( i=0; i < colCount; i++) {
					colH[ i ] =  0 ;
				}		

				mWrap.css({ position: 'relative' });

				brick.css({
						float: 'none',
						position: 'absolute',
						display: 'block'
					})
					.each(function(){
						for ( i=colCount-1; i > -1; i-- ) {
							if ( colH[ i ] == colH.min() ) {
								var thisCol = i;
							}
						}
						$(this).css({
							top: colH[ thisCol ],
							left: brickW * thisCol
						});
						colH[ thisCol ] += $(this).outerHeight(true);
					});

				mWrap.height( colH.max() );
			}
			return this; 
		});
	};