(function($) {

	// jQuery searchValue 1.0
	$.fn.searchValue=function(){var a=$(this);var b=a.val();a.focus(function(){if(a.val()==b)a.val('')});a.blur(function(){if(a.val()=='')a.val(b)});return this};

})(jQuery);

// PPK's cookie functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function replaceFormat(source, format) {
	return source.substring(0, source.lastIndexOf('/') + 1) + format;
};
	
function serialize(_obj) {
	if(!_obj)
		return false;
   // Let Gecko browsers do this the easy way
   if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined')
   {
	  return _obj.toSource();
   }
   // Other browsers must do it the hard way
   switch (typeof _obj)
   {
	  // numbers, booleans, and functions are trivial:
	  // just return the object itself since its default .toString()
	  // gives us exactly what we want
	  case 'number':
	  case 'boolean':
	  case 'function':
		 return _obj;
		 break;

	  // for JSON format, strings need to be wrapped in quotes
	  case 'string':
		 return '"' + _obj.replace('"','\"').replace("\n",'\n').replace("\\","\\\\") + '"';
		 break;

	  case 'object':
		 var str;
		 if (_obj.constructor === Array || typeof _obj.callee !== 'undefined')
		 {
			str = '[';
			var i, len = _obj.length;
			for (i = 0; i < len-1; i++) { str += serialize(_obj[i]) + ','; }
			str += serialize(_obj[i]) + ']';
		 }
		 else
		 {
			str = '{';
			var key;
			for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
			str = str.replace(/\,$/, '') + '}';
		 }
		 return str;
		 break;

	  default:
		 return 'UNKNOWN';
		 break;
   }
};

$(function() {
	
	$('#search input[type=text]').searchValue();
	
	// Set up last shown
	var list=eval(getCookie('product'));
	
	if(!(list instanceof Object)) {
		list=[];
	}
	
	if($('#product').length){
		
		var obj = {
			title: $('h1:first-child').text(),
			img: $('#image-cycle img:first-child').attr('src'),
			url: window.location.href,
			price: $('#product .price span').text().substring(2)
		}
		
		var exists=false;
		
		for(var i=0;i<list.length;i++) {
			var iets = list[i];
			if(iets.url == obj.url){
				exists=true;
			}
		}
		
		if(exists == false) {
			list.push(obj);
			if(list.length>10)
				list.shift();			
			setCookie('product1', serialize(list));
		}
		
	}
	
	var recentContainer = $('#recent-container'),
		recentElements = '';
	
	for(var i = list.length - 1; i >= 0; i--) {
		var cookie=list[i];
		recentElements += '<div class="element"><a href="' + cookie.url + '" class="image" style="background-image: url(' + cookie.img + '&amp;format=product)"><img src="' + cookie.img + '" alt="' + cookie.title + '" /></a><h3><a href="' + cookie.url + '">' + cookie.title + '</a></h3><p class="type">Type</p><p class="price"><span>&euro; </span>' + cookie.price + '</p></div>';
	};
	
	recentContainer.append(recentElements);
	
	var divClear = $('<div class="clear" />');
	recentContainer.append(divClear);
	
	// Set up image clones
	var images = $('#product .image img'),
		container = $('#product .images');
	
	if(images.length > 1){
		
		images.each(function(){

			var imageSource = replaceFormat($(this).attr('src'), 'product-small');

			var link = $('<a href="#" />');
			link.appendTo(container);
			
			var span = $('<span />', {
				css : {
					'background-image' : 'url(' + imageSource + ')'
				}
			});
			span.appendTo(link)
			
			var shadow = $('<img />', {
				load : function() {
					var el = $(this);
					el.css({
						width : el.width() + 'px',
						height : el.height() + 'px'
					});
				},
				src : imageSource
			});
			shadow.appendTo(span);

		});
		
		var clear = $('<div />', {
			className : 'clear'
		});
		clear.appendTo(container);
		
	};
	
	// Set up image cycle
	var products = $('#image-cycle .element');
	if(products.length > 1){
		
		var buttons = $('#product .images a');
		
		products.cycle({
			interval : 7000,
			keep : true,
			onCycle : function() {
				buttons.removeClass('active');
				buttons.eq(this.getCurrentIndex()).addClass('active');
			},
			rotate : true,
			speed : 500
		});

		buttons.each(function(index) {
			var el = $(this);
			$.data(el, 'index', index);
			el.bind('click', function(e) {
				products.showIndex($.data(el, 'index'));
				e.preventDefault();
			});
		});
		
		products.add(buttons).bind({
			'mouseover' : function() {
				products.pauseCycle();
			},
			'mouseout' : function() {
				products.startCycle();
			}
		});

	};
	
	// Set up image zoom	
	var cycle = $('#image-cycle'),
		preloadItems = cycle.find('img'),
		counter = 0;
	
	preloadItems.bind('load', function() {
		
		counter++;
		
		if(counter == preloadItems.length) {
		
			var cycleItems = cycle.find('.element'),
				zoom = $('#zoom'),
				zoomItems;
				
			if(cycleItems.length && zoom.length) {
			
				function getPos(client, imgOffset, ratio, offset, diff, scrollTop) {
					
					if(scrollTop) {
						imgOffset -= scrollTop;
					};
					
					var pos = Math.floor((client - imgOffset) * ratio) - offset;
					
					if(pos < 0) {
						return 0;
					};
					
					if(pos > diff) {
						return diff;
					};
					
					return pos;
					
				};
				
				var width = cycle.width(),
					height = cycle.height(),
					tWidth = zoom.width(),
					tHeight = zoom.height();
			
				cycleItems.each(function(index) {
					
					var body = document.body,
						el = $(this),
						vis = el.is(':visible'),
						link = el.children('a'),
						source = link.attr('href'),
						image = el.find('img');
						
					el.css('display', 'block');
						
					// Get image dimensions, the image has to be visible
					var imageWidth = image.width(),
						imageHeight = image.height();
				
					if(!vis) {
						el.css('display', 'none');
					};
					
					// Center link within container
					link.css({
						'position' : 'absolute',
						'top' : ((height - imageHeight) / 2) + 'px',
						'left' : ((width - imageWidth) / 2) + 'px'
					});
					
					// Set or create zoom container
					var zoomItem = $('<div />', {
						css : {
							'background-image' : 'url(' + source + ')'
						}
					});
					zoomItem.appendTo(zoom);
					
					// Create dummy to get the width and height	
					var tImage = $('<img />', {
						alt : '',
						css : {
							'position' : 'absolute',
							'top' : '-25000px',
							'left' : '0'
						},
						src : source,
						load : function() {
							
							var tImageWidth = tImage.width(),
								tImageHeight = tImage.height();
							
							tImage.remove();
							
							var x = {
								ratio : tImageWidth / imageWidth,
								offset : tWidth / 2,
								diff : tImageWidth - tWidth
							};
							
							var y = {
								ratio : tImageHeight / imageHeight,
								offset : tHeight / 2,
								diff : tImageHeight - tHeight
							};
								
							image.bind({
								
								'mouseover' : function() {
									
									zoomItems.eq(index).show();
									
									zoom.stop();
									zoom.show();
									zoom.css('opacity', '0');
									zoom.animate({
										opacity : 1
									}, 300);
									
								},
								
								'mouseout' : function() {
									
									zoomItems.eq(index).hide();
									
									zoom.stop();
									zoom.animate({
										opacity : 0
									}, 150, function() {
										zoom.hide();
									});
									
								},
								
								'mousemove' : function(event) {
									
									var imgOffset = image.offset();
									
									// Calculate positions
									var left = getPos(event.clientX, imgOffset.left, x.ratio, x.offset, x.diff),
										top = getPos(event.clientY, imgOffset.top, y.ratio, y.offset, y.diff, $(window).scrollTop());
									
									// Update background position
									zoomItem.css('background-position', '-' + left + 'px -' + top + 'px');
									
								}
								
							});
							
						}
					});
					tImage.appendTo(body);
					
				});
				
				// Store the zoomItems
				zoomItems = zoom.children();
				
			};
		
		};
		
	});
	
	if($.browser.msie || ($.browser.mozilla && parseInt($.browser.version) < 2)) {
		preloadItems.each(function() {
			var preloadItem = $(this);
			preloadItem.attr('src', preloadItem.attr('src'));
		});
	};

	// Set up banner
	var banner = $('#banner img');
	if(banner.length) {
	
		var bannerNav = $('#banner-nav'),
			buttons = $('#banner-nav a'),
			interval = 7000;
			
		banner.cycle({
			duration : 250,
			interval : interval,
			onCycle : function() {
				buttons.removeClass('active');
				buttons.eq(this.getCurrentIndex()).addClass('active');
			}
		});
	
		buttons.each(function(index) {
			var el = $(this);
			$.data(el, 'index', index);
			el.bind('click', function(e) {
				banner.showIndex($.data(el, 'index'));
				e.preventDefault();
			});
		});
		
	};
	
	// Set up product elements
	var elements = $('.products .element');
	elements.each(function(){
		$(this).bind({
			'mouseover' : function() {
				$(this).addClass('active');
			},
			'mouseout' : function() {
				$(this).removeClass('active');
			},
			'click' : function() {
				var link = $(this).find('a').attr('href');
				window.location = link;
			}
		});
	});
	
	// Set up brandlogo's
	$('#brands-front img:odd').css('float', 'right');
	
	// Toggle subnavigation
	var navButtons = $('#navigation li'),
		subNav = $('#subnavigation'),
		subNavTimer = null,
		targets = $.parseJSON(subNav.attr('data-subnav')),
		shopNav = null,
		shopNavTimer = null,
		shopSubNav = $('#shops');
	
	if(subNav.length){
		
		var targetButtons;
		switch(targets.length) {
			case 1 :
				targetButtons = navButtons.eq(targets[0]);
				break;
			case 2 :
				targetButtons = navButtons.slice(targets[0], targets[1]);
		};
		
		subNav.add(targetButtons).bind({
			'mouseover' : function() {
				if(subNavTimer) {
					window.clearTimeout(subNavTimer);
				};
				subNav.show();
				shopSubNav.hide();
			},
			'mouseout' : function() {
				subNavTimer = window.setTimeout(function() {
					subNav.hide();
				}, 400);
			}
		});
		
		shopSubNav.add(navButtons.eq(-1)).bind({
			'mouseover' : function() {
				if(shopNavTimer) {
					window.clearTimeout(shopNavTimer);
				};
				shopSubNav.show();
				subNav.hide();
			},
			'mouseout' : function() {
				shopNavTimer = window.setTimeout(function() {
					shopSubNav.hide();
				}, 400);
			}
		});
	
	}
	
	// Hide filter actives
	$('.filter .filteractives ul').hideIfEmpty({
		target : '.filteractives',
		ignoreDummy : true
	});
	
	var timer = false,
		slider = $('#recent-block');
		
	slider.serialScroll({
		items : '.element',
		force : true,
		interval : 6000,
		duration : 1000,
		start : 0,
		step : 1
	})
	.hover(function() {
		
		if(timer) {
			timer = false;
			window.clearTimeout(timer);
		};

		slider.trigger('stop');
		
	}, function() {
		
		timer = window.setTimeout(function() {				
			slider.trigger('start');
		}, 1000);
		
	});
	
	// Set up filters
	$('.filterblock').each(function(){
		
		if($(this).children('ul').length){
			
			var list = $(this).children('ul');
			
			if(list.children('li').length > 25){
				
				var listClone = list.clone();
				var counter = 0;
				
				listClone.find('li').each(function(){
					
					counter++;
					
					if(counter >= 25){
						$(this).remove();
					}
					
				});
				
				var link = $('<p class="more"><a href="#">всички категории</a></p>');
				
				link.bind({
					'click' : function(e){
						listClone.hide();
						link.hide();
						list.show();
						e.preventDefault();
					}
				});
				
				list.hide();
				$(this).append(listClone, link);
				
			}
			
		}
		
	});
	
	// Set up loading image
	var loading = $('<img src="/style/alleskoopjeonline/images/loading.gif" alt="Loading" class="loading" />');
	loading.hide();
	
	$('.filter-container').append(loading);
	
	$('.filter-container ul').bind({
		
		'click' : function(){
				
			$(this).parents('.filter-container').find('.loading').show();
			
		}
		
	});
	
	// Filter price check	
	var price = $('.filterblock.price form1');
	if(price.length) {
	
		var loc = window.location,
			search = loc.search,
			minNode = price.children('.priceMin'),
			maxNode = price.children('.priceMax');
	
		// Retrieve min value and set min node value
		var min = search.match(/search?from=(\d*)/);
		if(min && min[1]) {
			min = min[1];
			minNode.val(min);
		} else {
			max = null;
		};
		
		// Retrieve max value and set max node value
		var max = search.match(/search?to=(\d*)/);
		if(max && max[1]) {
			max = max[1];
			if(max == '' || max == 0) {
				maxNode.val('');
			} else {
				maxNode.val(max);
			};
		} else {
			max = null;
		};
		
		price.bind('submit', function(event) {

			var minValue = minNode.val(),
				maxValue = maxNode.val();
			
			// Prevent default submit
			event.preventDefault();
			
			// If both the min and max value are empty, don't submit
			if(minValue == '' && maxValue == '') {
				return false;
			};
			
			// If the min value is empty and the max value is 0 or higher, set the min value to 0
			if(minValue == '' && maxValue >= 0) {
				minValue = 0;
				
			// If the max value is empty and the max value is 0 or higher, set the max value to 0
			} else if(minValue >= 0 && maxValue == '') {
				maxValue = 0;
			};
			
			// Show loading image
			price.parents('.filter-container1').find('.loading').show();
			
			// custom submit
			var url = loc.href;
			
			if(parseFloat(minValue) >= 0) {
				
				if(min) {
					url = url.replace(/search?to=\d+/, 'from=' + minValue);
				} else {
					url += (url.indexOf('?') >= 0 ? '&' : '?') + 'from=' + minValue;
				};
				
			};
			
			if(parseFloat(maxValue) >= 0) {
				
				if(max) {
					url = url.replace(/search?=\d+/, 'to=' + maxValue);
				} else {
					url += (url.indexOf('?') >= 0 ? '&' : '?') + 'to=' + maxValue;
				};
				
			};
			
			loc.href = url;
			
		});
		
	};
	
	// Set up filter blocks
	$('.filter-container').each(function() {
		
		var el = $(this),
			title = el.find('.title'),
			titleText = title.text(),
			content = el.find('.filterblock'),
			contentHeight = content.height(),
			cookie = readCookie(titleText),
			visible = true,
			animated = false;
		
		if(cookie == 'hidden') {
			title.addClass('active');
			content.height(0);
			visible = false;
		};
		
		title.css('cursor', 'pointer');
		
		content.css('overflow', 'hidden');
			
		title.bind('click', function() {
			
			if(!animated) {
			
				if(visible) {
					title.addClass('active');
					contentHeight = content.height();
					content.animate({
						height : 0
					}, 150, function() {
						animated = false;
					});
					animated = true;
					visible = false;
				} else {
					title.removeClass('active');
					content.animate({
						height : contentHeight
					}, 300, function() {
						content.height('auto');
						animated = false;
					});
					animated = true;
					visible = true;
				};
				
			};
			
			createCookie(titleText, visible ? 'shown' : 'hidden', 7);
			
		});
		
	});
	
	// Set up favorite navigation
 
	
	// Delete from favorites
	$('#favorites .element').each(function(){
		
		var element = $(this);
		element.children('form').hide();
		
		element.bind({
			'mouseover' : function() {
				element.children('form').show();
			},
			'mouseout' : function() {
				element.children('form').hide();
			}
		});
		
		element.find('.delete a').bind({
			'click' : function(e){
				element.find('form').submit();
				e.stopPropagation();
				e.preventDefault();
			}
		});
	});
	
	// Set up product blocks
	var product = $('#product-container');
	
	if(product.length){
		
		product.children('.product-middle').css('height', product.height() - 50);
		product.children('.product-right').css('height', product.height() - 22);
		
	}
	
	// More news
	if($('#news').length){
		$('.news-more').hide();
	}
	
	// Product news
	if($('.product-right').length && $('.product-news').length){
		$('.product-right').append($('.product-news'));
	}
	
});
