// Func.js
// © 2011 - VisiLogic

// Make array containing category_view settings
var shark_categoryContainerSettings = new Array();
var shark_defaultBubbleProperties = {themeName:	'GPI', themePath: '/_plugins/jquery_bubblepopup/jquerybubblepopup-theme', themeMargins: { total:'7px', difference:'4px' }, innerHtmlStyle: {'text-align': 'center'}, align: 'center', selectable: false};

$(document).ready(function() {

	//if($().popSlides) $('.pop').popSlides();

	// Parse through all category containers and set settings for each container once
	$('.shark_category_contents').each(function() {
		var category_settings = this.parentNode.id.split('shark_category_view_')[1];
		if(category_settings) {
			category_settings = $.parseJSON($.base64Decode(category_settings));
			shark_categoryContainerSettings[category_settings['name']] = category_settings;
			shark_populateCategoryContainer($('.shark_category_fade_container', this), category_settings['name']); // Populate category container
			shark_populatePageSelector(this, category_settings['name']); // Populate pageSelector DIV
		} else { // It's not a browsable category. Just add the popups.
			shark_createProductPopups(this);
		}
			
	});
	
});


function shark_createProductPopups(content_container) {

	// Create bubblepopups for each product
	$('.shark_cart_add', content_container).each(function(index, element) {
			
		$(element).attr('href', '#null'); // Clear any linking
		shark_showBubble(element, { innerHtml: '<img src="../data/ajax_loader_grey.gif"/>', 'text-align': 'center' }, true); // Create AJAX loading popup on hover
					
		$(element).mouseover(function(event) { // Create mouseover popup
			var product_id = element.parentNode.parentNode.id.split('shark_product_id_')[1];
			
			$.get('../pages/ajax_shark_getProductPopup.php', {pID: product_id}, function(data) {
				
				var product_info = $.parseJSON(data);
				product_stock = product_info[1];
				product_info = product_info[0];
				
				product_info['product_name'] = product_info['product_name'].match(/.{1,18}\b/gi).join('<br/>'); // Newline after 18 consecutive letters
				shark_showBubble(element, {innerHtml: '<div class="shark_productPopupTitle">' + product_info['product_name'] + '</div><a class="shark_productPopupStock' + (product_stock['STNW'] == 'low' ? ' shark_productPopupStockDisabled' : '') + '" alt="Levertijd nieuw" title="' + (product_stock['STNW'] == 'high' ? 'Levertijd: 1 werkdag' : (product_stock['STNW'] == 'med' ? 'Levertijd: 5 werkdagen' : 'Levertijd onbekend' )) + '" id="shark_addProduct_' + product_id + '_1"><img src="/_plugins/shark/icons/stock_' + product_stock['STNW'] + (product_stock['STNW'] == 'low' ? '_disabled' : '') + '.png"/> Nieuw</a><a class="shark_productPopupStock' + (product_stock['STSH'] == 'low' ? ' shark_productPopupStockDisabled' : '') + '" alt="Levertijd gebruikt" title="' + (product_stock['STSH'] == 'high' ? 'Levertijd: 1 werkdag' : (product_stock['STSH'] == 'med' ? 'Levertijd: 5 werkdagen' : 'Niet beschikbaar' )) + '" id="shark_addProduct_' + product_id + '_2"><img src="/_plugins/shark/icons/stock_' + product_stock['STSH'] + (product_stock['STSH'] == 'low' ? '_disabled' : '') + '.png"/> Gebruikt</a>', selectable: true}, false);

				$('#'+$(element).GetBubblePopupID()+' a').each(function() {
					var product_match = /\d+_\d+$/i.exec($(this).attr('id')); // Find out if it's an add button
					
					if(product_match && !$(this).hasClass('shark_productPopupStockDisabled')) {
						product_match = product_match.toString().split("_");
						$(this).click(function(event) {
							event.stopPropagation(); // Cancel bubbling and capturing														
							$.ajax({
								url: '/_plugins/shark/shark_ajax_addToCart.php?product_id=' + product_match[0] + '&stock_type_id=' + product_match[1],
								timeout: 1000,
								error: function() { shark_showBubble(element, {innerHtml: 'Fout tijdens het toevoegen van artikel', selectable: true}, false); },
								success: function(data) {$('#shark_wrapper').html(data); shark_showBubble(element, {innerHtml: 'Artikel toegevoegd aan winkelmand'}, false);	}
							});
						});
					};
					
				});

			});
			
		});
		
		$(element).click(function(event) {
			event.stopPropagation(); // Cancel bubbling and capturing
		});
		
	});
	
}

function shark_populateCategoryContainer(content_container, category) {

	var category_settings = shark_categoryContainerSettings[category]; // Retrieve settings for easy access	
	$.get('../pages/ajax_getProducts.php', {category_id: parseInt(category_settings.category_id), view_count: parseInt(category_settings.view_count), page_id: parseInt(category_settings.page_id), category_name: category_settings.name}, function(data) {
		if(!data) { // Clear contents
			$(content_container).html("Geen artikelen gevonden in deze categorie");
			$(content_container.parentNode).css('background-image', 'none');
		} else { // Data received. Set contents and fade in
			$(content_container).html(data);
			shark_createProductPopups(content_container);
			$(content_container).fadeIn(500);
		}
	});
	
};

function shark_populatePageSelector(container, category_name) {

	// Fetch and set parameters
	var fadeContainer = $('.shark_category_fade_container', container);
	var pageSelectorContainer = $('ol', $('.shark_page_selector', container.parentNode));
	
	var category_settings = shark_categoryContainerSettings[category_name];
	
	var page_id = parseInt(category_settings['page_id']);
	var page_amount = Math.ceil(category_settings['product_count'] / category_settings['view_count']);
	var start = page_id < 10 ? 0 : Math.max(0, (page_id > (page_amount - 9) ? page_amount - 20 : page_id - 10));
	var end = Math.min(page_amount, ((page_id < 10) ? 20 : (10 + page_id))) - 1;
	
	// Append numbered buttons
	$(pageSelectorContainer).html('');
	
	$(pageSelectorContainer).append('<li><a class="shark_page_selector_rtl_double" id="shark_page_' + category_name + '_0" href="#null"><span></span></a></li>');
	$(pageSelectorContainer).append('<li><a class="shark_page_selector_rtl_single" id="shark_page_' + category_name + '_' + (page_id > 0 ? (page_id - 1) : 0) + '" href="#null"><span></span></a></li>');
	
	for(var i = start; i <= end; i++) $(pageSelectorContainer).append('<li><a id="shark_page_' + category_name + '_' + i + '" href="#null"' + ((page_id) == i ? ' class="active"' : '') + '><span>' + (i + 1)+'</span></a></li>');	
	
	$(pageSelectorContainer).append('<li><a class="shark_page_selector_ltr_single" id="shark_page_' + category_name + '_' + (page_id < (page_amount - 1) ? (page_id + 1) : (page_amount - 1)) + '" href="#null"><span></span></a></li>');
	$(pageSelectorContainer).append('<li><a class="shark_page_selector_ltr_double" id="shark_page_' + category_name + '_' + (page_amount - 1) + '" href="#null"><span></span></a></li>');

	// Set button actions
	$('a',pageSelectorContainer).each(function() {
		$(this).click(function() {
		
			// Erase all 'active' classes, and set active to current button
			$('a',pageSelectorContainer).each(function(){ $(this).removeClass('active'); });
			$(this).addClass('active');
			
			// Get information from current button
			var button_info = this.id.split('shark_page_'+category_name+'_');
			shark_categoryContainerSettings[category_name]['page_id'] = button_info[1];
			$(fadeContainer).fadeOut(500,function(){
				shark_populateCategoryContainer(fadeContainer, category_name);
				shark_populatePageSelector(container, category_name);
			});
		});
	});
	
}

function shark_showBubble(element, attributes, create) { if(create) $(element).CreateBubblePopup(shark_getBubbleProperties(attributes)); else $(element).ShowBubblePopup(shark_getBubbleProperties(attributes), false); }
function shark_getBubbleProperties(attributes) { var attrObj = shark_defaultBubbleProperties; for (attrname in attributes) { attrObj[attrname] = attributes[attrname]; } return attrObj; }
