// Initialising the array wich contains all the filter values
var filterArray = new Array();

var vat_rate1 = 0;
var vat_rate2 = 0;
var small_order_charge = 4.00;
var small_order_limit = 45.00;
var productsOnPage = 10;
var statuses = [];

var productId = 0;
var pageCatId = 0;
var tempAssetsHeight = 0;
var activeProdPage = 1;
var activeSearchPage = 1;
var extra_category_filters = 0;
var cartLoaded = false;
var footer_out = false;
var active_filters = false;
var back_to = 'products';
var sort_products_by = 'name~asc';
var config_compilations = '';
var product_stock = 0;
var set_configs = false;

// Get the vat rates and save them to their variables
jQuery.getJSON('/modules/shop/load.php?item=vat_rates', function(data)
{
	vat_rate1 = parseFloat(data[0]);
	vat_rate2 = parseFloat(data[1]);
});

jQuery(document).ready(function()
{
	// Binds and handles the change of the 'sort_products_by' select box
	jQuery('#sort_products_by').change(function()
	{
		showAjaxLoader(2);
		
		sort_products_by = jQuery(this).val();
		
		jQuery.getJSON('/modules/shop/load.php?item=categories&load=single_page&page='+getCurrentPageID(),function(data)
		{
			activeProdPage = 1;
			activeSearchPage = 1;
			statuses['nieuw'] = 0;
			statuses['opruiming'] = 0;
			statuses['aanbieding'] = 0;
			statuses['populair'] = 0;
			
			// Set the current page it's category_id, and add it as filter
			pageCatId = data[0].id;
			filterArray['page'] = pageCatId;
			
			// Load the products and categories for this shop page
			loadCategories(data,data,0);
			loadProducts();

			if(jQuery('#shop_search').is(':visible'))
			{
				search(jQuery('#search_string').html());
			}
		});
	});
	
	// Binds and handles the change of the 'products_on_page' select box
	jQuery('#products_on_page').change(function()
	{
		showAjaxLoader(2);
		if(jQuery(this).val() != '*') productsOnPage = parseInt(jQuery(this).val());
		else productsOnPage = 1000000000;
		
		jQuery.getJSON('/modules/shop/load.php?item=categories&load=single_page&page='+getCurrentPageID(),function(data)
		{
			activeProdPage = 1;
			activeSearchPage = 1;
			statuses['nieuw'] = 0;
			statuses['opruiming'] = 0;
			statuses['aanbieding'] = 0;
			statuses['populair'] = 0;
	
			// Set the current page it's category_id, and add it as filter
			pageCatId = data[0].id;
			filterArray['page'] = pageCatId;
			
			// Load the products and categories for this shop page
			loadCategories(data,data,0);
			loadProducts();
			
			if(jQuery('#shop_search').is(':visible'))
			{
				search(jQuery('#search_string').html());
			}
		});
	});
});

function setup()
{
	filterArray = new Array();
	productId = 0;
	activeProdPage = 1;
	activeSearchPage = 1;
	extra_category_filters = 0;
	back_to = 'products';
	config_compilations = '';
	product_stock = 0;
	
	if(tempAssetsHeight == 0)
	{
		if(footer_out && active_filters)
		{
			jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()-120+'px');
		}
		else if(footer_out)
		{
			jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()-95+'px');
		}
		
		footer_out = false;
		active_filters = false;
	}
	else
	{
		jQuery('#permanent_assets').css('height', tempAssetsHeight+'px');
	}
	
	jQuery.getJSON('/modules/shop/load.php?item=categories&load=single_page&page='+getCurrentPageID(),function(data)
	{
		// Set the current page it's category_id, and add it as filter
		pageCatId = data[0].id;
		filterArray['page'] = pageCatId;
		
		// Load the products and categories for this shop page
		loadCategories(data,data,0);
		loadProducts();
		if(!cartLoaded)
		{
			loadTinyCart();
			cartLoaded = true;
		}
	});
	
	statuses['nieuw'] = 0;
	statuses['opruiming'] = 0;
	statuses['aanbieding'] = 0;
	statuses['populair'] = 0;
}

// Loads the products, if a filter is set (in the array) only the filtered products will be loaded
function loadProducts()
{
	back_to = 'products';
	jQuery('#product_pages').empty().hide();
	
	var listParams = '';
	
	for(key in filterArray)
	{
		// Check if key is not indexOf. Because of weird bug in IE
		if(key != 'indexOf')listParams += '&arr[]='+filterArray[key];
	}
	
	jQuery('#sort_products_by').attr('disabled','');
	jQuery('#products_on_page').attr('disabled','');
	
	jQuery.getJSON('/modules/shop/load.php?item=products'+listParams+'&sort='+sort_products_by,function(data)
	{
		jQuery('#producttable tbody').empty();
		jQuery('#products_holder').remove();
		
		if(data.length == 0)
		{
			jQuery('#producttable tbody').append
			(
				'<tr><td id="shop_message">Er zijn geen producten beschikbaar in deze categorie</td></tr>'
			);
			jQuery('#ajax_loader').hide('fast');
		}
		else
		{
			var product_page = 1;
			var edit = '';
			
			if(HomePage == getCurrentPageID())
			{
				// It is the home page				
				jQuery('#sort_products_by').attr('disabled','disabled');
				jQuery('#products_on_page').attr('disabled','disabled');
				
				jQuery('#producttable').after
				(
			 			'<div style="width: 100%;" id="products_holder">'
			 		+		'<div style="clear: both;">'
			 		+			'<div style="background: #D4EADD url(img/site/head_text.png) no-repeat; width: 100%; height: 27px;">'
			 		+				'<div style="padding-left: 5px; padding-top: 2px;"></div>'
			 		+			'</div>'
			 		+			'<div id="nieuw_col" class="status_col" style="width: 100%; min-height: 10px;"></div>'
			 		+		'</div>'
			 		+		'<div style="clear: both;">'
			 		+			'<div style="background: #D4EADD url(img/site/head_text.png) no-repeat left -54px; width: 100%; height: 27px;">'
			 		+				'<div style="padding-left: 5px; padding-top: 2px;"></div>'
			 		+			'</div>'
			 		+			'<div id="populair_col" class="status_col" style="width: 100%; min-height: 10px;"></div>'
			 		+		'</div>'
			 		+		'<div style="clear: both;">'
			 		+			'<div style="background: #D4EADD url(img/site/head_text.png) no-repeat left -27px; width: 100%; height: 27px;">'
			 		+				'<div style="padding-left: 5px; padding-top: 2px;"></div>'
			 		+			'</div>'
			 		+			'<div id="aanbieding_col" class="status_col" style="width: 100%; min-height: 10px;"></div>'
			 		+		'</div>'
			 		+		'<div style="clear: both;">'
	 				+			'<div style="background: #D4EADD url(img/site/head_text.png) no-repeat left -81px; width: 100%; height: 27px;">'
			 		+				'<div style="padding-left: 5px; padding-top: 2px;"></div>'
			 		+			'</div>'
			 		+			'<div id="opruiming_col" class="status_col" style="width: 100%; min-height: 10px;"></div>'
			 		+		'</div>'
			 		+	'</div>'
				);
				
				var statuses_length = 0;					
				for(key in statuses)
				{
    				if(statuses.hasOwnProperty(key)) statuses_length++;
				}
				
				jQuery.each(data, function(i,item)
				{
					var status = (item.status).split('~')[1];
					
					statuses[status.toLowerCase()] = statuses[status.toLowerCase()] + 1;
					var status_count = statuses[status.toLowerCase()];
					
					edit = '<a href="#" onclick="editProduct('+item.id+',\'Edit Product\')" style="margin-left: 5px;"><img src="/img/framework/edit_small.png" alt="edit this product" style="margin-top: 4px;"/></a><a href="javascript:void(0);" onclick="deleteProduct('+item.id+')" style="margin-left: 2px;"><img src="/img/framework/remove_small.png" alt="delete this product" style="margin-top: 4px;"/></a> ';
					
					var title = URLDecode(item.name);
					if(title.length > 35)
					{
						title = title.substring(0,32);
						title = title+' ...';
					}
					
					var description = URLDecode(item.description);
					if(description.length > 120)
					{
						description = description.substring(0,117);
						description = description+' ...';
					}
					
					var prefix = '';
					if(item.combo == true)
						prefix = ' v.a';
					
					var temp_vat_rate = item.vat_rate.split('~');
					
					// Add a product to the list, containing all the necessary info				
					jQuery('#'+status.toLowerCase()+'_col').append
					(
							'<div class="product_wrapper" style="float: left; '+(status_count%2==0 ? '':'margin-right: 30px;')+'" id="product'+item.id+'">'
						+		'<div class="product_padding">'
						+			'<div class="prod_image">'
						+				'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">'
						+ 					'<img src="/upload/products/'+item.img1.split('~')[0]+'" alt="'+URLDecode(item.name)+'"/>'
						+				'</a>'
						+			'</div>'
						+			'<div class="prod_content_wrapper">'
						+				'<div class="prod_header">'
						+					'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">'+title+'</a>'
						+				'</div>'
						+				'<div class="prod_content">'
						+					description
						+				'</div>'
						+				'<span '+(getTinyMceActivated() ? 'style="margin-left: -15px;"' : '')+'>'
						+					(getTinyMceActivated() ? edit : '')
						+					'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">details</a>'
						+					'<font style="color: #1D4B5E"> | </font>'
						+					'<a href="javascript:void(0);" id="order_prod_'+item.id+'">bestellen</a>'
						+					'<font style="color: #1D4B5E"> | </font>'
						+					'<font style="font-style: italic;">Prijs'+prefix+': &#8364; </font>'+number_format(priceInclusive(temp_vat_rate[1],item.price), 2, ',', '')
						+				'</span>'
						+			'</div>'
						+ 		'</div>'
						+	'</div>'
					);
					
					// Bind callback for order product button
					jQuery('#order_prod_'+item.id).click(function()
					{
						var stock = item.in_stock;
						 
						if(1 > stock)
						{							
							addToCart(item.id+'^', 1,'',function()
							{
								customAlert('Er zijn momenteel 0 stuks voorradig. Het restant wordt zo snel mogelijk nageleverd of pas uw bestelling aan.','button');
							});
						}
						else
						{
							addToCart(item.id+'^', 1,'',function()
							{
								customAlert('Het product is toegevoegd aan uw winkelmandje!');
							});
						}
					});
				});
				
				// Remove bottom border of the last two items for each status
				jQuery('.status_col').each(function(i)
				{
					// last
					jQuery(this).find('.product_wrapper').filter(':last').css('border','0px');
					
					if(jQuery(this).length % 2 == 0)
					{
						// penultimate
						jQuery(this).find('.product_wrapper').not(':last').filter(':last').css('border','0px');	
					}
				});
			}
			else
			{				
				// Not the home page								
				jQuery('#producttable').after('<div id="products_holder" style="width: 100%;"></div>');
							
				jQuery.each(data, function(i,item)
				{
					if (i % 2 == 0)
					{
						jQuery('#products_holder').append
						(
							'<div class="product_page'+product_page+' page_product_holder" style="height: 110px; width: 100%; '+(product_page != 1 ? 'display:none;':'')+'"></div>'
						);
					};
						
					edit = '<div style="float:left;"><a href="#" onclick="editProduct('+item.id+',\'Edit Product\')" style="margin-left: 5px;"><img src="/img/framework/edit_small.png" alt="edit this product" style="margin-top: 4px;"/></a><a href="javascript:void(0);" onclick="deleteProduct('+item.id+')" style="margin-left: 2px;"><img src="/img/framework/remove_small.png" alt="delete this product" style="margin-top: 4px;"/></a></div>';				
					
					// Creates the page navigation ( 1 2 3 4 5 ..)
					if((i+1) > productsOnPage * product_page)
					{
						// If it's the first time, add the first page as well
						if(product_page == 1)
						{
							jQuery('#product_pages').html
							(
									'<a href="javascript:void(0);" onclick="previousProductPage()"><font style="font-size: 16px;">&laquo;</font> vorige<font style="color: #1D4B5E"></a>'
								+	' | </font><span id="page_navigation"></span><font style="color: #1D4B5E"> | </font>'
								+	' <a href="javascript:void(0);" onclick="nextProductPage()">volgende <font style="font-size: 16px;">&raquo;</font></a>'
							);
							jQuery('#page_navigation').append('<a href="javascript:void(0);" class="product_paging active_page" id="product_page_link1" onclick="showProductPage(1)">1</a>  ');
							jQuery('#product_pages').fadeIn('fast');
						}
						
						// Increase product_page variable
						product_page++;
						
						// Add the new page to the containing div
						jQuery('#page_navigation').append
						(
								'<a href="javascript:void(0);" class="product_paging" id="product_page_link'+product_page+'" onclick="showProductPage('+product_page+')">'
							+	product_page
							+	'</a>  '
						);
					}
					
					var prefix = '';
					if(item.combo == true)
						prefix = ' v.a';
					
					var temp_vat_rate = item.vat_rate.split('~');
					// Add a product to the list, containing all the necessary info				
					jQuery('#products_holder .page_product_holder:last').append
					(
							'<div id="product'+item.id+'" class="product_wrapper" style="float: left; '+(jQuery('#products_holder .page_product_holder:last .product_wrapper').exists() ? 'margin-left: 30px;' : '')+'">'
						+		'<div class="product_padding">'
						+			'<div class="prod_image">'
						+				'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">'
						+ 					'<img src="/upload/products/'+item.img1.split('~')[0]+'" alt="'+URLDecode(item.name)+'"/>'
						+				'</a>'
						+			'</div>'
						+			'<div class="prod_content_wrapper">'
						+				'<div class="prod_header">'
						+					'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">'+URLDecode(item.name)+'</a>'
						+				'</div>'
						+				'<div class="prod_content">'
						+					URLDecode(item.description)
						+				'</div>'
						+				'<div class="prod_footer">'
						+					(getTinyMceActivated() ? edit : '')
						+				'</div>'
						+				'<span>'
						+					'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">details</a>'
						+					'<font style="color: #1D4B5E"> | </font>'
						+					'<a href="javascript:void(0);" id="order_prod_'+item.id+'">bestellen</a>'
						+					'<font style="color: #1D4B5E"> | </font>'
						+					'<font style="font-style: italic;">Prijs'+prefix+': &#8364; </font>'+number_format(priceInclusive(temp_vat_rate[1],item.price), 2, ',', '')
						+				'</span>'
						+			'</div>'
						+ 		'</div>'
						+	'</div>'
					);
					
					// Bind callback for order product button
					jQuery('#order_prod_'+item.id).click(function()
					{
						var stock = item.in_stock;
						 
						if(1 > stock)
						{							
							addToCart(item.id+'^', 1,'',function()
							{
								customAlert('Er zijn momenteel 0 stuks voorradig. Het restant wordt zo snel mogelijk nageleverd of pas uw bestelling aan.','button');
							});
						}
						else
						{
							addToCart(item.id+'^', 1,'',function()
							{
								customAlert('Het product is toegevoegd aan uw winkelmandje!');
							});
						}
					});
				});
			}
		}
		
		jQuery.each(showQueue,function(i,item)
		{
			jQuery(item).show('fast');
		});
		showQueue = [];
		loading_done = true;
		jQuery('#ajax_loader').hide('fast');
		
		// last
		jQuery('#products_holder').find('.product_wrapper').not(':hidden').filter(':last').css('border','0px');
		
		if(jQuery('#products_holder').find('.product_wrapper').not(':hidden').length % 2 == 0)
		{
			// penultimate
			jQuery('#products_holder').find('.product_wrapper').not(':hidden').not(':last').filter(':last').css('border','0px');
		}
	});
}

// Show next product page
function nextProductPage()
{	
	if(jQuery('#products_holder').find('.product_wrapper').filter(':last').is(':hidden'))
	{
		showProductPage(activeProdPage+1);
		scroll(0,0);
	}
}

// Show previous product page
function previousProductPage()
{
	if(activeProdPage != 1)
	{
		showProductPage(activeProdPage-1);
		scroll(0,0);
	}
}

// Loads a single product with it's information
function loadProduct(id,name)
{
	showAjaxLoader(2);
	productId = id;
	showProduct();
	
	jQuery.getJSON('/modules/shop/load.php?item=product&id='+id,function(data)
	{
		var edit = '';
		jQuery.each(data, function(i,item)
		{
			jQuery('#product_content').load('/modules/shop/product/product.php','',function()
			{
				edit = '<a href="#" onclick="editProduct('+item.id+',\'Edit Product\');" style="margin-left: 5px;"><img src="/img/framework/edit_small.png" alt="edit this product"/></a><a href="#" onclick="deleteProduct('+item.id+');hideProduct();" style="margin-left: 2px;"><img src="/img/framework/remove_small.png" alt="delete this product"/></a>';
				product_stock = item.in_stock;
				var split = item.img[0].split('~')[0].split('.');
				var name = split[0];
				var extension = '.'+split[1];
				
				// Set the head image
				jQuery('#head_image td').html('<img src="/upload/products/'+name+'_small'+extension+'" title="'+URLDecode(item.name)+'"/>');
				
				var images = 0;
				for(var i = 0; i < 3; i++)
				{
					var split = item.img[i].split('~')[0].split('.');
					// If the name is not empty, it means there is an image
					if(split[0] != '')
					{
						// Increase counter 'images' wich contains the number of set images
						images ++;	
					}
				}
				
				// Set the thumb images
				for(var j = 0; j < 3; j++)
				{
					var split = item.img[j].split('~')[0].split('.');
					var name = split[0];
					var extension = '.'+split[1];
					
					// If the name is not empty and there is more then just one image append a thumb
					if(name != '' && images > 1)
					{
						jQuery('#thumb_images td').append
						(
								'<div '+(j == 0 ? 'class="active_thumb" style="margin-left: 0px !important;"' :'')+' onclick="resetZoom(\''+name+'\',\''+extension+'\',\''+URLDecode(item.name)+'\');jQuery(this).parent().children().each(function(){jQuery(this).removeClass()});jQuery(this).addClass(\'active_thumb\');">'
							+		'<img src="/upload/products/'+name+'_thumb'+extension+'" class="thumb_img"/>'	
							+	'</div>'
						);
					}
				}
				
				// Add product name and description, and if logged-in an edit and remove button
				jQuery('#product_details').append
				(
						'<tr><th colspan="2">'+URLDecode(item.name)+(getTinyMceActivated() ? edit : '')+'</th></tr>'
					+	'<tr><td colspan="2">'+nl2br(URLDecode(item.description))+'</td></tr>'
				);
				
				// Add each product detail
				jQuery.each(item.info, function(key,info)
				{
					jQuery('#product_details').append('<tr><td>'+ucwords(info[0])+':</td><td>'+ucwords(info[1])+'</td></tr>');
				});
				
				var temp_vat_rate = item.vat_rate.split('~');
				jQuery('#product_details').append
				(
						'<tr><td class="product_price" colspan="2">Prijs &#8364; <span id="detail_prod_price" style="font-weight: bold; font-style: italic;">'+number_format(priceInclusive(temp_vat_rate[1],item.price), 2, ',', '')+'</span></td></tr>'
				);
								
				if(item.in_stock > 0)
				{
					//var stock_text = 'Op voorraad';
					var stock_text = '<img src="img/site/in_stock.png"/ alt="Op voorraad" id="stock_img">';
				}
				else
				{
					//var split = item.out_of_stock.split('~');
					//var stock_text = split[1];
					var stock_text = '<img src="img/site/out_of_stock.png"/ alt="Geen voorraad" id="stock_img">';
				}
				
				jQuery('#order_product_stock').parent().prepend(stock_text);
				jQuery('#order_product_stock').val(product_stock);
				
				// Check if there is a config option set
				if(item.configs != '')
				{
					jQuery.each(item.configs,function(c, config)
					{
						// For each parent config create a new select
						jQuery('#order_product_now_parent').before
						(
								'<tr>'
							+		'<td>'+ucwords(URLDecode(config.name))+':</td>'
							+		'<td><select id="product_config'+config.id+'" class="product_config"></select></td>'
							+	'</tr>'
						);
						
						// For each child config create a new option, and add it to the parents select box
						jQuery.each(config.children, function(cc, child)
						{
							jQuery('#product_config'+child.parent_id).append
							(
								'<option value="'+child.id+'">'+child.name+'</option>'
							)
						});	
					});
				}
				
				jQuery.getJSON('/modules/shop/load.php?item=product_stock&product_id='+item.id, function(data)
				{
					config_compilations = data;
					var config_composition = [];
					jQuery('.product_config').each(function()
					{
						config_composition[config_composition.length] = jQuery(this).val();
					});
					
					jQuery.each(config_compilations, function(j, jtem)
					{
						if(arrayEqual(config_composition, (jtem.configs).split(',')))
						{
							jQuery('#detail_prod_price').html(number_format(priceInclusive(temp_vat_rate[1],jtem.price), 2, ',', ''));
							product_stock = jtem.stock;
							
							if(product_stock > 0)
							{
								//var stock_text = 'Op voorraad';
								var stock_src = 'img/site/in_stock.png';
							}
							else
							{
								//var split = item.out_of_stock.split('~');
								//var stock_text = split[1];
								var stock_src = 'img/site/out_of_stock.png';
							}
							
							jQuery('#stock_img').attr('src',(stock_src));
							jQuery('#order_product_stock').val(product_stock);
						}
					});
				});
				
				jQuery('.product_config').change(function()
				{
					var config_composition = [];
					jQuery('.product_config').each(function()
					{
						config_composition[config_composition.length] = jQuery(this).val();
					});
					
					jQuery.each(config_compilations, function(j, jtem)
					{						
						if(arrayEqual(config_composition, (jtem.configs).split(',')))
						{							
							jQuery('#detail_prod_price').html(number_format(priceInclusive(temp_vat_rate[1],jtem.price), 2, ',', ''));
							product_stock = jtem.stock;
							
							if(product_stock > 0)
							{
								//var stock_text = 'Op voorraad';
								var stock_src = 'img/site/in_stock.png';
							}
							else
							{
								//var split = item.out_of_stock.split('~');
								//var stock_text = split[1];
								var stock_src = 'img/site/out_of_stock.png';
							}							
							
							jQuery('#stock_img').attr('src',(stock_src));
							jQuery('#order_product_stock').val(product_stock);
						}
					});	
				});
				
				// Bind callback for order product button
				jQuery('#order_product_now').click(function()
				{
					var cart_id = '';
					
					jQuery('.product_config').each(function()
					{
						cart_id += '~'+jQuery(this).val();	
					});
					
					var temp_stock = parseInt(jQuery('#order_product_stock').val());
					
					if(parseInt(jQuery('#order_product_quantity').val()) != 0)
					{
						if(parseInt(jQuery('#order_product_quantity').val()) > temp_stock)
						{
							if(parseInt(temp_stock) < 0)
							{
								temp_stock = 0;
							}
							
							addToCart(item.id+'^'+cart_id, jQuery('#order_product_quantity').val(),'',function()
							{
								customAlert('Er zijn momenteel '+temp_stock+' stuks voorradig. Het restant wordt zo snel mogelijk nageleverd of pas uw bestelling aan.','button');
								hideProduct();
							});
						}
						else
						{
							addToCart(item.id+'^'+cart_id, jQuery('#order_product_quantity').val(),'',function()
							{
								customAlert('Het product is toegevoegd aan uw winkelmandje!');
								hideProduct();
							});
						}
					}
					else
					{
						customAlert('Als u het product wilt bestellen, moet het te bestellen aantal minimaal 1 bedragen.');
					}
				});
			});
		});
		jQuery('#ajax_loader').hide('fast');
	});
}

// Function that compares two arrays returns true if the arrays are equal
function arrayEqual(toCompareArray, dbArray)
{
	var count = 0;
	
	jQuery.each(dbArray, function(j,jtem)
	{
		if(jtem == toCompareArray[j])
		{
			count ++;
		}
	});
	
	if(count == dbArray.length)
	{
		return true;
	}
	else
	{
		return false;
	}	
}

// Hides the active page, and then shows the correct page
function showProductPage(page)
{
	showAjaxLoader(2);
	
	var last_iteration1 = jQuery('.product_page'+activeProdPage).length - 1;
	
	jQuery('.product_page'+activeProdPage).each(function(i)
	{
		jQuery(this).hide('fast',function()
		{
			if(i == last_iteration1)
			{
				var last_iteration2 = jQuery('.product_page'+page).length - 1;
				jQuery('.product_page'+page).each(function(j)
				{
					jQuery(this).fadeIn(function()
					{
						if(j == last_iteration2)
						{
							activeProdPage = page;
							
							// Set the active class for the paging link
							jQuery('.product_paging').removeClass('active_page');
							jQuery('#product_page_link'+activeProdPage).addClass('active_page');
							
							// last
							jQuery('#products_holder').find('.product_wrapper').not(':hidden').filter(':last').css('border','0px');
							
							if(jQuery('#products_holder').find('.product_wrapper').not(':hidden').length % 2 == 0)
							{
								// penultimate
								jQuery('#products_holder').find('.product_wrapper').not(':hidden').not(':last').filter(':last').css('border','0px');	
							}
							
							jQuery('#ajax_loader').hide('fast');
						}
					});
				});
			}
		});
	});
}

function showProduct()
{
	jQuery('#shop_general').hide();
	jQuery('#cart_content').hide();
	jQuery('#shop_checkout').hide();
	jQuery('#normal_content').hide();
	jQuery('#shop_search').hide();
	if(jQuery('#page_content_tbl').exists())jQuery('#page_content_tbl').hide();
	if(jQuery('#product_content').is(':hidden'))jQuery('#product_content').fadeIn('fast');
}

function hideProduct()
{	
	jQuery('#product_content').hide();
	jQuery('#cart_content').hide();
	jQuery('#shop_checkout').hide();
	
	if(back_to == 'products')
	{
		jQuery('#shop_search').hide();
		if(jQuery('#page_content_tbl').exists())
		{
			jQuery('#page_content_tbl').show();
		}
		else
		{
			jQuery('#normal_content').show();
		}
		if(jQuery('#shop_general').is(':hidden'))jQuery('#shop_general').fadeIn('fast');
	}
	else if(back_to == 'search')
	{
		jQuery('#shop_general').hide();
		if(jQuery('#shop_search').is(':hidden'))jQuery('#shop_search').fadeIn('fast');
	}
}

// Loads all the categories that are not a page
function loadCategories(root,data,iteration)
{
	var number_of_cat = 4;
	var number_of_sub_cat = 5;				/* Adapt in the function loadExtraCategories as well */
	var tables = 0;
	var filter_items = 0;
	var table_width = 100/number_of_cat; 
	var edit = '';
			
	if(iteration == 0)
	{
		jQuery('#footer').html
		(
				'<div id="active_filters">'
			+		'<div id="title">Actieve Filters:</div>'
			+	'</div>'
			+	'<table cellpadding="0" cellspacing="0" id="filtertable" class="filterTable" style="display:none;">'
			+		'<tbody><tr id="filter_content"></tr></tbody>'
			+	'</table>'
		);
		showQueue[showQueue.length] = '#filtertable';
	}
	
	jQuery.each(data, function(i,item)
	{
		edit = '<a href="javascript:void(0);" onclick="editCategory('+item.id+')"><img src="/img/framework/edit_tiny.png" alt="edit this category"/></a><a href="javascript:void(0);" onclick="deleteCategory('+item.id+','+item.parent_id+')" style="margin-left: 2px; margin-right: 2px;"><img src="/img/framework/remove_tiny.png" alt="delete this category"/></a>';
		
		if(item.is_page == -1)
		{
			// Check if the parent category is a page. If so it means that we're dealing with a head item
			// else it is a sub-category
			if(checkIfIsPage(root,item.parent_id))
			{
				tables++;
				
				// Check if the maximum number of tables is reached.
				//If not create a new one, else put it in the extra options table
				if(tables <= number_of_cat)
				{
					jQuery('#filtertable tbody #filter_content').append
					(
							'<td valign="top" width="'+table_width+'%">'
				   		+		'<table id="filter'+item.id+'" class="innerFilter">'
						+			'<tbody><tr><th>'+(getTinyMceActivated() ? edit : '')+'Alle '+item.name+'</th></tbody>'
						+		'</table>'
						+	'</td>'
					);
				}
				else
				{
					// Check if it is the first the tables maximum is exceeded
					// If so remove the last created table, and set that as an option as well
					// else just add another option to the extra table
					if(tables == number_of_cat+1)
					{
						var last = jQuery('#filter_content').children('td:last').find('th').html().split('Alle');	
						var last_id = jQuery('#filter_content').children('td:last').find('table').attr('id').split('filter')[1];
						var penultimate = jQuery('#filter_content').children('td').not(':last').filter(':last').find('th').html().split('Alle');
						var penultimate_id = jQuery('#filter_content').children('td').not(':last').filter(':last').find('table').attr('id').split('filter')[1];
						
						jQuery('#filter_content').children('td:last').empty();
						jQuery('#filter_content').children('td:last').append
						(
								'<table id="extra_filters" class="innerFilter">'
							+		'<tr><th>Meer opties...</th></tr>'
							+		'<tr><td>'+last[0]+'<a href="javascript:void(0);" onclick="loadExtraCategory(\''+last_id+'\',0)">Alle'+last[1]+'</a></td></tr>'
							+		'<tr><td>'+penultimate[0]+'<a href="javascript:void(0);" onclick="loadExtraCategory(\''+penultimate_id+'\',0)">Alle'+penultimate[1]+'</a></td></tr>'
							+	'</table>'
						);
					}
					else
					{
						jQuery('#extra_filters').append('<tr><td>'+(getTinyMceActivated() ? edit : '')+'<a href="javascript:void(0);" onclick="loadExtraCategory(\''+item.id+'\',0)">Alle '+item.name+'</a></td></tr>');
					}
				}
			}
			else
			{
				filter_items++;
				
				if(filter_items > number_of_sub_cat)
				{
					if(!jQuery('#filter_expand_'+item.parent_id).exists())
					{
						jQuery('#filter'+item.parent_id+' tbody tr:last').addClass('hidden_filter');
						
						jQuery('#filter'+item.parent_id+' tbody').append
						(
							'<tr id="filter_expand_'+item.parent_id+'" class="filter_expand"><td><a href="javascript:void(0);" onclick="toggleExpandFilter()" style="font-weight: bold;">meer &#62;&#62;</a></td></tr>'
						);
					}
					
					jQuery('#filter_expand_'+item.parent_id).before
					(
						'<tr id="category'+item.id+'" class="hidden_filter"><td class="hidden">'+(getTinyMceActivated() ? edit : '')+'<a href="javascript:void(0);" onclick="setFilter(\''+item.parent_id+'\',\''+item.id+'\');loadProducts()">'+item.name+'</a></td></tr>'
					);
				}
				else
				{
					jQuery('#filter'+item.parent_id+' tbody').append
					(
						'<tr id="category'+item.id+'"><td>'+(getTinyMceActivated() ? edit : '')+'<a href="javascript:void(0);" onclick="setFilter(\''+item.parent_id+'\',\''+item.id+'\');loadProducts()">'+item.name+'</a></td></tr>'
					);
				}
			}
			loadCategories(root,item.children,iteration+1)
		}
	});
	
	if(iteration == 0)
	{
		for(var i = 0; i < (number_of_cat-tables); i++)
		{
			jQuery('#filtertable tbody #filter_content').append('<td valign="top" width="'+table_width+'%"></td>');
		}
		jQuery('#filter_content').children('td:last').css('border-right','0px');
	}
}

// Toggles the showing and hiding of the extra filter options
function toggleExpandFilter()
{
	if(jQuery('.hidden_filter .hidden').exists())
	{
		jQuery('.hidden_filter td').removeClass('hidden');
		
		if(jQuery('#holder').height() < jQuery('#permanent_assets').height())
		{
			tempAssetsHeight = 0;
			footer_out = true;
			
			jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()).animate({height: jQuery('#permanent_assets').height()+95+'px'},'fast');
		}
		else
		{
			tempAssetsHeight = jQuery('#permanent_assets').height();
			footer_out = true;
			
			jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()).animate({height: jQuery('#holder').height()+105+'px'},'fast');	
		}		
				
		jQuery('#filtertable').css('height', '115px').animate({height: '210px'},'fast');
		
		jQuery('.filter_expand a').html('minder &#60;&#60;');
		jQuery('.hidden_filter').show();
		jQuery('.hidden_filter').children().show();
	}
	else
	{
		var callback = jQuery('.hidden_filter').length-1;
		jQuery('.hidden_filter').each(function(i)
		{
			jQuery(this).fadeOut(function()
			{
				if(i == callback)
				{
					jQuery('.hidden_filter').children().fadeOut();
					footer_out = false;
					
					if(tempAssetsHeight == 0)
					{
						jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()).animate({height: jQuery('#permanent_assets').height()-95+'px'},'fast');
					}
					else
					{
						if(active_filters)
						{
							jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()).animate({height: jQuery('#permanent_assets').height()-105+'px'},'fast');
						}
						else
						{
							jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()).animate({height: tempAssetsHeight+'px'},'fast');
						}
					}
						
					jQuery('#filtertable').css('height', '210px').animate({height: '115px'},'fast');
					jQuery('.filter_expand a').html('meer &#62;&#62;');
				}
			});
			jQuery(this).find('td').addClass('hidden');
		});
	}
}

// Check if a category is a page
function checkIfIsPage(data, category_id)
{
	for (var i = 0; i < data.length; i++)
	{
		var item = data[i];

		// Check if this category is the one were looking for and if it is a page
		if(item.id == category_id && item.is_page != -1)
		{
			return true;
			break;
		}
	}
	return false;
}

// Loads a extra category option into the next to last td 
function loadExtraCategory(category_id, iteration)
{
	var number_of_sub_cat = 5;
	var edit = '';
	
	jQuery.getJSON('/modules/shop/load.php?item=category&children&id='+category_id,function(data)
	{
		jQuery.each(data, function(i,item)
		{
			edit = '<a href="javascript:void(0);" onclick="editCategory('+item.id+')"><img src="/img/framework/edit_tiny.png" alt="edit this category"/></a><a href="javascript:void(0);" onclick="deleteCategory('+item.id+','+item.parent_id+')" style="margin-left: 2px; margin-right: 2px;"><img src="/img/framework/remove_tiny.png" alt="delete this category"/></a>';
			
			if(iteration == 0)
			{
				// Reset the extra_category_filters variable
				extra_category_filters = 0;
				
				jQuery('#filter_content').children('td').not(':last').filter(':last').html
				(
			   			'<table id="filter'+item.id+'" class="innerFilter">'
					+		'<tbody><tr><th>'+(getTinyMceActivated() ? edit : '')+'Alle '+item.name+'</th></tbody>'
					+	'</table>'
				);
			}
			else
			{
				extra_category_filters++;
							
				// Check if there are too much filter items in the table
				if(extra_category_filters > number_of_sub_cat)
				{
					var element = jQuery('#filter_content').children('td').not(':last').filter(':last');
					
					// Check if the 'more' sign allready exists, if not create it
					if(!jQuery('#filter_expand_'+item.parent_id).exists())
					{
						element.find('tbody tr:last').addClass('hidden_filter');
						
						// Determine if the text should say 'more' or 'less';
						if(jQuery('.hidden_filter').css('display') != 'table-row')
						{
							element.find('tbody').append
							(
								'<tr id="filter_expand_'+item.parent_id+'" class="filter_expand"><td><a href="javascript:void(0);" onclick="toggleExpandFilter()" style="font-weight: bold;">meer &#62;&#62;</a></td></tr>'
							);
						}
						else
						{
							element.find('tbody').append
							(
								'<tr id="filter_expand_'+item.parent_id+'" class="filter_expand"><td><a href="javascript:void(0);" onclick="toggleExpandFilter()" style="font-weight: bold;">minder &#60;&#60;</a></td></tr>'
							);
						}
					}
					
					// Add a hidden filter option
					jQuery('#filter_expand_'+item.parent_id).before
					(
						'<tr id="category'+item.id+'" class="hidden_filter"><td class="hidden">'+(getTinyMceActivated() ? edit : '')+'<a href="javascript:void(0);" onclick="setFilter(\''+item.parent_id+'\',\''+item.id+'\');loadProducts()">'+item.name+'</a></td></tr>'
					);
				}
				else
				{
					// Nothing is out of the ordinary, just proceed
					jQuery('#filter_content').children('td').not(':last').filter(':last').find('tbody').append
					(
							'<tr><td>'
						+		(getTinyMceActivated() ? edit : '')
						+		'<a href="javascript:void(0);" onclick="setFilter(\''+item.parent_id+'\',\''+item.id+'\');loadProducts()">'
						+			item.name
						+		'</a>'
						+	'</td></tr>'
					);
				}
			}
			// Loop the children
			jQuery.each(item.children, function(c,child)
			{
				loadExtraCategory(child.id, iteration+1);
			});
		});
	});
}

// Adds a filter to the filter array, and adds the filter to the active filter div
function setFilter(parent_id, id)
{
	removeFilter(parent_id);
	filterArray[parent_id] = id;
	jQuery.getJSON('/modules/shop/load.php?item=category&id='+id+'&parent_id='+parent_id,function(data)
	{
		jQuery.each(data, function(i,item)
		{
			if(jQuery('#active_filters').find('#'+parent_id).length == 0)
			{
				jQuery('#active_filters').append
				(
						'<div class="filter" id="'+parent_id+'">'
					+		item.parent_name+': '+item.name
					+		'<a href="javascript:void(0);" onclick="removeFilter('+parent_id+');loadProducts();" style="margin-left: 2px;">'
					+			'<img src="/img/site/remove.png" alt="verwijder deze filter optie" class="remove"/>'
					+		'</a>'
					+	'</div>'
				);
			}
			else
			{
				jQuery('#'+parent_id).html
				(
						item.parent_name+': '+item.name
					+	'<a href="#" onclick="removeFilter('+parent_id+');loadProducts();">'
					+		'<img src="/img/site/remove.png" alt="verwijder deze filter optie" class="remove"/>'
					+	'</a>'
				);
				
				if(jQuery('#active_filters').find('#'+parent_id).is(':hidden'))
				{
					jQuery('#active_filters').find('#'+parent_id).show();
				}	
			}
		});
	});
	if(jQuery('#active_filters').is(':hidden'))
	{
		if(jQuery('#holder').height() < jQuery('#permanent_assets').height())
		{
			tempAssetsHeight = 0;
			active_filters = true;
			
			jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()).animate({height: jQuery('#permanent_assets').height()+25+'px'},'fast');
		}
		else
		{
			tempAssetsHeight = jQuery('#permanent_assets').height();
			active_filters = true;
			
			if(footer_out)
			{
				jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()).animate({height: jQuery('#permanent_assets').height()+25+'px'},'fast');
			}
			else
			{
				jQuery('#permanent_assets').css('height', jQuery('#permanent_assets').height()).animate({height: jQuery('#holder').height()+35+'px'},'fast');	
			}	
		}
		
		jQuery('#active_filters').fadeIn('fast');
	}
}

// Resets jqzoom after switching images
function resetZoom(source,extension,name)
{
	jQuery('#head_image td').fadeTo('fast', 0.05,function()
	{
		jQuery('#head_image td').html('<img src="/upload/products/'+source+'_small'+extension+'" title="'+name+'"/>')
	}).fadeTo('fast',1);
}

// Adds a filter from the filter array, and removes the filter from the active filter div
function removeFilter(parent_id)
{
	jQuery('#active_filters').find('#'+parent_id).hide();
	filterArray = removeKey(filterArray,parent_id);
	
	/*
	if(jQuery('#active_filters .filter:visible').length == 0)
	{
		jQuery('#active_filters').fadeOut();
	}
	*/
}

// Function that handles the searching
function search()
{
	showAjaxLoader(2);
	back_to = 'search';
	
	jQuery('#sort_products_by').attr('disabled','');
	jQuery('#products_on_page').attr('disabled','');
	
	jQuery('#footer').empty();
	jQuery('#container').css('background-position','-1817px 0px');
	jQuery('#content_top').css('background-position','0px 0px');
	jQuery('#permanent_assets').show();
	
	jQuery('#search_pages').empty().hide();
	
	jQuery('#shop_general').hide();
	jQuery('#cart_content').hide();
	jQuery('#shop_checkout').hide();
	jQuery('#normal_content').hide();
	jQuery('#product_content').hide();
	if(jQuery('#page_content_tbl').exists())jQuery('#page_content_tbl').hide();
	if(jQuery('#shop_search').is(':hidden'))
	{
		jQuery('#shop_search').fadeIn('fast');
		jQuery('#submenu').html
		(
			'<div id="sub_title_search" class="sub_title"><a href="javascript:void(0);">Search results</a></div>'
		);
	}
	
	var search_string = jQuery('#search_field').val();
	// Triggers the search, based on the string from the search field and gets the search data
	jQuery.getJSON('/modules/shop/load.php?item=search&s='+search_string+'&sort='+sort_products_by,function(data)
	{
		jQuery('#search_products_holder').empty();
		
		jQuery('#search_products_holder').append
		(
				'<div class="search_header">'
			+		'<div>U heeft gezocht op: "<span id="search_string">'+search_string+'</span>"</div>'
			+		'<div>Er zijn '+data.length+' resultaten gevonden</div>'
			+	'</div>'
		);
		
		if(data == "")
		{
			jQuery('#search_products_holder').append
			(
				'<div class="search_header">Er zijn helaas geen producten gevonden.</div>'
			);
			jQuery('#ajax_loader').hide('fast');
		}
		else
		{
			var search_page = 1;
			var edit = '';
			
			jQuery.each(data, function(i,item)
			{
				edit = '<div style="display:inline;"><a href="#" onclick="editProduct('+item.id+',\'Edit Product\')" style="margin-left: 5px;"><img src="/img/framework/edit_tiny.png" alt="edit this product" style="margin-top: 4px;"/></a><a href="javascript:void(0);" onclick="deleteProduct('+item.id+')" style="margin-left: 2px;"><img src="/img/framework/remove_tiny.png" alt="delete this product" style="margin-top: 4px;"/></a></div>';				
				
				// Creates the page navigation ( 1 2 3 4 5 ..)
				if((i+1) > productsOnPage * search_page)
				{
					// If it's the first time, add the first page as well
					if(search_page == 1)
					{						
						jQuery('#search_pages').html
						(
								'<a href="javascript:void(0);" onclick="previousSearchPage()"><font style="font-size: 16px;">&laquo;</font> vorige<font style="color: #1D4B5E"></a>'
							+	' | </font><span id="search_navigation"></span><font style="color: #1D4B5E"> | </font>'
							+	' <a href="javascript:void(0);" onclick="nextSearchPage()">volgende <font style="font-size: 16px;">&raquo;</font></a>'
						);
						jQuery('#search_navigation').append('<a href="javascript:void(0);" class="search_paging active_page" id="search_page_link1" onclick="showProductPage(1)">1</a>  ');
						jQuery('#search_pages').fadeIn('fast');
					}
					
					// Increase product_page variable
					search_page++;
					
					// Add the new page to the containing div
					jQuery('#search_navigation').append
					(
							'<a href="javascript:void(0);" class="search_paging" id="search_page_link'+search_page+'" onclick="showSearchPage('+search_page+')">'
						+	search_page
						+	'</a>  '
					);
				}
				
				var description = URLDecode(item.description);
				if(description.length > 115)
				{
					description = description.substring(0,112);
					description = description+' ...';
				}
				
				var prefix = '';
				if(item.combo == true)
					prefix = ' v.a';
				
				var split = item.img1.split('~')[0].split('.');				
				var temp_vat_rate = item.vat_rate.split('~');
				
				// Add a product to the list, containing all the necessary info				
				jQuery('#search_products_holder').append
				(
						'<div class="search_row search_page'+search_page+'"'+(search_page != 1 ? 'style="display:none;"':'')+'>'
					+		'<div style="float:left;">'
					+			'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">'
					+				'<img src="/upload/products/'+split[0]+'_tiny.'+split[1]+'" alt="'+URLDecode(item.name)+'" class="head_img"/>'
					+			'</a>'
					+		'</div>'
					+		'<div style="float:right; width: 590px; height: 50px; margin-left: 8px; margin-top: -2px;">'
					+			'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">'
					+				URLDecode(item.name) +	(getTinyMceActivated() ? edit : '')
					+			'</a>'
					+			'<div class="prod_content">'
					+				description
					+			'</div>'
					+			'<div id="search_order">'
					+				'<a href="#" onclick="loadProduct(\''+item.id+'\',\''+str_replace("'","",URLDecode(item.name))+'\')">details</a>'
					+				'<font style="color: #1D4B5E"> | </font>'
					+				'<a href="javascript:void(0);" id="order__search_prod_'+item.id+'">bestellen</a>'
					+				'<font style="color: #1D4B5E"> | </font>'
					+				'<font style="font-style: italic;">Prijs'+prefix+': &#8364; </font>'+number_format(priceInclusive(temp_vat_rate[1],item.price), 2, ',', '')
					+			'</div>'
					+		'</div>'
					+	'</div>'
				);
				
				// Bind callback for order product button
				jQuery('#order__search_prod_'+item.id).click(function()
				{					
					var stock = item.in_stock;
						 
					if(1 > stock)
					{							
						addToCart(item.id+'^', 1,'',function()
						{
							customAlert('Er zijn momenteel 0 stuks voorradig. Het restant wordt zo snel mogelijk nageleverd of pas uw bestelling aan.','button');
						});
					}
					else
					{
						addToCart(item.id+'^', 1,'',function()
						{
							customAlert('Het product is toegevoegd aan uw winkelmandje!');
						});
					}
				});
				
			});
			jQuery('.search_row').not(':hidden').filter(':last').css('border','0px');
			
			jQuery('#ajax_loader').hide('fast');
		}
	});
}

// Show next product page
function nextSearchPage()
{	
	if(jQuery('.search_row').filter(':last').is(':hidden'))
	{
		showSearchPage(activeSearchPage+1);
		scroll(0,0);
	}
}

// Show previous product page
function previousSearchPage()
{
	if(activeSearchPage != 1)
	{
		showSearchPage(activeSearchPage-1);
		scroll(0,0);
	}
}

// Hides the active page, and then shows the correct page
function showSearchPage(page)
{
	showAjaxLoader(2);
	
	var iteration_1 = jQuery('.search_page'+activeSearchPage).length - 1
	var iteration_2 = jQuery('.search_page'+page).length - 1;
	
	jQuery('.search_page'+activeSearchPage).each(function(i)
	{
		jQuery(this).hide('fast',function()
		{
			if(i == iteration_1)
			{
				jQuery('.search_page'+page).each(function(j)
				{
					jQuery(this).fadeIn(function()
					{
						jQuery(this).children().each(function(k)
						{
							jQuery(this).show();							
							
							var iteration_3 = jQuery(this).children().length - 1;
							
							//alert(i+' == '+iteration_1+' && '+j+' == '+iteration_2+' && '+k+' == '+iteration_3);
							
							if(i == iteration_1 && j == iteration_2 && k == iteration_3)
							{
								activeSearchPage = page;
								
								// Set the active class for the paging link
								jQuery('.search_paging').removeClass('active_page');
								jQuery('#search_page_link'+activeSearchPage).addClass('active_page');
								
								jQuery('.search_row').not(':hidden').filter(':last').css('border','0px');
								
								jQuery('#ajax_loader').hide('fast');
							}
						});
					});
				});
			}
		});
	});
}

function exitSearch()
{
	jQuery('#shop_search').hide();
	jQuery('#cart_content').hide();
	jQuery('#shop_checkout').hide();
	jQuery('#product_content').hide();
	if(jQuery('#page_content_tbl').exists())
	{
		jQuery('#page_content_tbl').show();
	}
	else
	{
		jQuery('#normal_content').show();
	}
	if(jQuery('#shop_general').is(':hidden'))jQuery('#shop_general').fadeIn('fast');
}

// Show the custom alert with the given message
function customAlert(message, fixed, fade)
{
	if(typeof fixed == 'undefined')fixed = false;
	if(typeof fade == 'undefined')fade = false;
	
	jQuery('#alert_message').html(message);
	
	if(fade)
	{
		showFade('site_fade', 0.65);
	}
	
	if(!fixed)
	{
		jQuery('#alert').fadeIn('fast',function()
		{
			jQuery(this).timeOut(2000);
			jQuery(this).fadeOut('fast',function(){hideFade('site_fade')});
		});
	}
	else if(fixed == 'button')
	{
		jQuery('#alert').find('input').show('fast');
		jQuery('#alert').fadeIn('fast');		
	}
	else
	{
		jQuery('#alert').fadeIn('fast');
	}
}

// Hides the custom alert
function closeAlert()
{
	jQuery('#alert').fadeOut('fast',function()
	{
		jQuery('#alert').find('input').css('display','none');
		hideFade('site_fade');
	});
}

// Returns the price including vat, based on the given price and vat rate
function priceInclusive(vatRate, price)
{
	return ((parseFloat(vatRate)/100) * parseFloat(price)) + parseFloat(price);
}

// Returns the array length (needed because key values are used in the filterArray)
function arrayLength(array)
{
	var count = 0;
	for (i in array)
	{
	    count++;
	}
	return count;
}

// Removes the given key from the given array, and returns the new array
function removeKey(arrayName,key)
{
	var x;
	var tmpArray = new Array();
	for(x in arrayName)
	{
 		if(x!=key){tmpArray[x]=arrayName[x];}
	}
	return tmpArray;
}

// Php like function that hecks if the given value exists in the array  
function in_array(needle, haystack, argStrict)
{
    var key = '', strict = !!argStrict; 
    if (strict)
	{
        for (key in haystack)
		{
            if (haystack[key] === needle)
			{
                return true;
			}
        }
    }
	else
	{
        for (key in haystack)
		{
            if (haystack[key] == needle)
			{
				return true;
            }
        }
    }
	return false;
}

// Php like function wich makes the first character of each word in a string upper case
function ucwords(str)
{
    return (str+'').replace(/^(.)|\s(.)/g, function($1){return $1.toUpperCase();});
}

// Php like function wich transforms the given number, and returns the desired format 
function number_format(number, decimals, dec_point, thousands_sep)
{
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    
    // *     example 10: number_format('1.20', 2);
    // *     returns 10: '1.20'
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

jQuery.fn.ellipsis = function(enableUpdating)
{
	var s = document.documentElement.style;
	if (!('textOverflow' in s || 'OTextOverflow' in s))
	{
		return this.each(function()
		{
			var el = jQuery(this);
			if(el.css("overflow") == "hidden")
			{
				var originalText = el.html();
				var w = el.width();
				
				var t = jQuery(this.cloneNode(true)).hide().css
				({
                    'position': 'absolute',
                    'width': 'auto',
                    'overflow': 'visible',
                    'max-width': 'inherit'
                });
				el.after(t);
				
				var text = originalText;
				while(text.length > 0 && t.width() > el.width())
				{
					text = text.substr(0, text.length - 1);
					t.html(text + "...");
				}
				el.html(t.html());
				
				t.remove();
				
				if(enableUpdating == true)
				{
					var oldW = el.width();
					setInterval(function(){
						if(el.width() != oldW)
						{
							oldW = el.width();
							el.html(originalText);
							el.ellipsis();
						}
					}, 200);
				}
			}
		});
	}
	else return this;
};

// Replaces all occurrences of search in haystack with replace
function str_replace (search, replace, subject, count)
{    
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
     for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}        }
    }
    return sa ? s : s[0];
}