// Basis functie om dom elementen mee op te halen
$(document).ready(function(){
	$('.back').css({
		cursor:'pointer'
	});
	$('.back').click(function(){
		history.back();
	});
	$('.slideshow').each(function(){
		var data = eval('('+$(this).attr('ssData')+')');
		$('.ssImage').css({visibility:'visible'});
		$(this).cycle(data);
		$(this).height(data.height);
		$(this).width(data.width);
	});

	$('.googleMap').each(function(){
		var opts = eval('('+$(this).attr('mapOptions')+')');
		var center = eval('('+opts.center+')');
		opts.center = new google.maps.LatLng(center.b,center.c);
		opts.zoom = parseFloat(opts.zoom);
		var el = document.getElementById($(this).attr('id'));
		// Markers ophalen
		var markers = [];
		$(this).find('.marker').each(function(){
			markers[markers.length] = {
				data:eval('('+$(this).attr('markerOptions')+')'),
				description:$(this).html()
			}
		});
		var map = null;
		if(el){
			map = new google.maps.Map(el,opts);
		}
		if(map != null && markers.length > 0){
			for(var i = 0; i < markers.length; i++){
				var opts = markers[i].data;
				if(opts.cmsDraggable != undefined){
					opts.draggable = opts.cmsDraggable;
				}
				if(opts.cmsClickable != undefined){
					opts.clickable = opts.cmsClickable;
				}
				var position = eval('('+opts.position+')');
				opts.position = new google.maps.LatLng(position.b,position.c);
				opts.map = map;
				var m = new google.maps.Marker(opts);
				if(markers[i].description != ''){
					var w = new google.maps.InfoWindow({
						content:markers[i].description,
						position:opts.position
					});
					w.open(map);
					google.maps.event.addListener(m, 'click', function(e){
						w.open(map);
					});
				}
			}
		}
	});


	var first = true;
	$('#homeSlideImages').cycle({
		fx:'fade',
		speed:2000,
		timeout:10000,
		next:'#homeSlideNext',
		prev:'#homeSlidePrev',
		before:function(current, next, options, forwardFlag){
			if(!first){
				var curId = current.id.split('_').pop();
				var nextId = next.id.split('_').pop();
				$('#hst_'+nextId).fadeIn(options.speed);
				$('#hst_'+curId).fadeOut(options.speed);
				setTimeout(function(){
					$('#hsnr_'+curId).addClass('slideNavLink').removeClass('slideNavLinkActive');
					$('#hsnr_'+nextId).addClass('slideNavLinkActive').removeClass('slideNavLink');
				}, options.speed);
			} else {
				first = false;
			}
		}
	});

	$('.link').click(function(){
		var id = parseInt(this.id.split('_').pop())-1;
		$('#homeSlideImages').cycle(id);
	});

	$('.orderInput').click(function(){
		$(this).select();
	});
	var basket = {};
	basket.timer = null;
	basket.replace = function(replace){
		if(typeof replace == 'object'){
			for(var i in replace){
				if(typeof replace[i] != 'function'){
					switch(i){
						case 'popup':
							var mask = $('<div></div>');
							mask.attr('id', 'mask');
							$(document.body).append(mask);
							$(document.body).append(replace[i]);
						break;
						default:
							$('#'+i).replaceWith(replace[i]);
						break;
					}
				}
			}
			init();
		}
	}
	
	$('.orderButton,.orderFrontButton').click(function(){
		var data = {
			task:'updateBasket',
			amount:1,
			replace:['popup']
		};
		var input = null;
		if($(this).hasClass('orderFrontButton')){
			input = $(this).parent().parent().find('.orderFrontInput');
		} else {
			input = $(this).parent().parent().find('.orderInput');
		}
		if(input.length > 0){
			var delay = 0;
			if(basket.timer != null){
				delay = 200;
			}
			setTimeout(function(){
				data.amount = parseFloat(input.val().replace(',', '.'));
				var inputData = ajax.decode(input.attr('inputData'));
				data.id = inputData.id;
				data.add = true;
				ajax.request({
					url:'customer/plugins/webshop/render/basket.php',
					method:'GET',
					params:{
						data:ajax.encode(data)
					},
					success:function(response){
						var result = response.responseText;
						if(result != ''){
							result = ajax.decode(result);
							switch(result.success){
								case true:
									// Laten zien dat het artikel besteld is
									basket.replace(result.replace);
								break;
								case false:
									renderErrors([result.msg]);
								break;
							}
						} else {
							renderErrors(['Geen antwoord van basket.php bij '+data.task]);
						}
					},
					failure:function(response){
						renderErrors([response.responseText]);
					}
				});
			},delay);
		}
	});

	function init(){
		var list = ['#mask','#productPopup'];
		for(var i = 0; i < list.length; i++){
			$(list[i]).css({
				cursor:'pointer'
			});
			$(list[i]).click(function(){
				for(var j = 0; j < list.length; j++){
					$(list[j]).remove();
				}
			});
		}
		$('.orderInput,.orderFrontInput,.orderInputBasket').keyup(function(){
			if(basket.timer != null){
				clearTimeout(basket.timer);
			}
			var el = $(this);
			basket.timer = setTimeout(function(){
				var data = ajax.decode(el.attr('inputData'));
				var val = el.val();
				if(val != ''){
					var amount = parseFloat(val.replace(',','.'));
					var valid = true;
					if(isNaN(amount)){
						valid = false;
					} else if(data.decimals !== true && amount%1!=0){
						valid = false;
					}
					var o = data.old;
					if(!valid){
						el.val(data.old);
					} else {
						data.old = ''+amount;
						data.old = data.old.replace('.',',');
						el.attr('inputData', ajax.encode(data));
						if(el.hasClass('orderInputBasket')){
							var l = $('#loader_'+data.id);
							l.css({
								display:'block'
							});
							var d = {
								task:'updateBasket',
								id:data.id,
								amount:amount,
								replace:['cartOverview']
							}
							ajax.request({
								url:'customer/plugins/webshop/render/basket.php',
								method:'GET',
								mask:false,
								params:{
									data:ajax.encode(d)
								},
								success:function(response){
									var result = response.responseText;
									if(result != ''){
										result = ajax.decode(result);
										switch(result.success){
											case true:
												if(result.redirect){
													document.location = result.redirect;
												} else {
													basket.replace(result.replace);
												}
											break;
											case false:
												if(!result.errors){
													result.errors = [result.msg];
												}
												renderErrors(result.errors);
												el.val(o);
												l.css({
													display:'none'
												});
											break;
										}
									} else {
										renderErrors(['Geen antwoord van basket.php']);
									}
								},
								failure:function(response){
									renderErrors([response.responseText]);
								}
							});
						}
					}
				}
				basket.timer = null;
			},200);
		});

		$('.orderInput,.orderFrontInput,.orderInputBasket').blur(function(){
			var val = $(this).val();
			if(val == ''){
				var data = ajax.decode($(this).attr('inputData'));
				$(this).val(data.old);
			}
		});
	}
	init();

	$('.deleteIcon').click(function(){
		var input = $(this).parent().parent().find('.orderInputBasket');
		var data = ajax.decode(input.attr('inputData'));
		var d = {
			task:'updateBasket',
			id:data.id,
			amount:0,
			replace:['cartOverview']
		}
		ajax.request({
			url:'customer/plugins/webshop/render/basket.php',
			method:'GET',
			mask:false,
			params:{
				data:ajax.encode(d)
			},
			success:function(response){
				var result = response.responseText;
				if(result != ''){
					result = ajax.decode(result);
					switch(result.success){
						case true:
							if(result.redirect){
								document.location = result.redirect;
							} else {
								basket.replace(result.replace);
							}
						break;
						case false:
							if(!result.errors){
								result.errors = [result.msg];
							}
							renderErrors(result.errors);
							el.val(o);
							l.css({
								display:'none'
							});
						break;
					}
				} else {
					renderErrors(['Geen antwoord van basket.php']);
				}
			},
			failure:function(response){
				renderErrors([response.responseText]);
			}
		});
	});

	$('#openPassword').change(function(){
		var diff = 50;
		$('#passwordTable').animate({height:diff}, 400);
		$('#registerForm').animate({height:$('#registerForm').height()+diff}, 400);
		$('#register').animate({height:$('#register').height()+diff},400);
	});

	$('#closePassword').change(function(){
		var diff = 50;
		$('#passwordTable').animate({height:$('#passwordTable').height()-diff}, 400);
		$('#registerForm').animate({height:$('#registerForm').height()-diff}, 400);
		$('#register').animate({height:$('#register').height()-diff},400);
	});

	$('#openDelivery').change(function(){
		$('#registerForm').animate({left:0},400);
		$('#deliveryForm').css({display:'block'});
		$('#deliveryForm').animate({right:0,opacity:100},400);
		if($('#firstOpen').val() === '1'){
			if($('#c_gender_dhr').attr('checked') === true){
				$('#d_gender_dhr').attr({checked:true});
			} else {
				$('#d_gender_mevr').attr({checked:true});
			}
			var fields = [
				{from:'c_initials',		to:'d_initials'},
				{from:'c_lastName',		to:'d_lastName'},
				{from:'c_email',		to:'d_email'},
				{from:'c_country',		to:'d_country'}
			];
			for(var i in fields){
				$('#'+fields[i].to).val($('#'+fields[i].from).val());
			}


			$('#firstOpen').val(0);
		}
	});

	$('#closeDelivery').change(function(){
		$('#registerForm').animate({left:250},400);
		$('#deliveryForm').animate({right:250,opacity:0},400, 'swing', function(){
			$(this).css({display:'none'});
		});
	});

	$('.info img').mouseover(function(e){
		var info = $(this).attr('info');
		var div = document.createElement('div');
		div.className = 'infoDiv';
		div.style.position = 'absolute';
		div.innerHTML = info;
		var pos = $(this).position();
		div.style.left = pos.left+20+'px';
		div.style.top = pos.top+$(this).parent().height()+'px';
		$(this).parent().append(div);
		$('.infoDiv').animate({opacity:1},100);
	});

	$('.info img').mouseout(function(e){
		$('.infoDiv').remove();
	});

	$('.textInputError').mouseenter(function(e){
		var error = $(this).attr('errorInfo');
		if(error){
			var div = document.createElement('div');
			div.className = 'inputErrorDiv';
	//		div.innerHTML = error;
			div.style.position = 'absolute';
			var l = document.createElement('div');
			l.className = 'error_left';
			var r = document.createElement('div');
			r.className = 'error_right';
			var c = document.createElement('div');
			c.className = 'error_center';
			c.innerHTML = error;
			var pos = $(this).position();
			div.style.left = pos.left+20+'px';
			div.style.top = pos.top+$(this).parent().height()+'px';
			div.appendChild(l);
			div.appendChild(c);
			div.appendChild(r);
			$(this).parent().append(div);
			$('.inputErrorDiv').animate({opacity:1}, 100);
		}
	});
	$('.textInputError').mouseleave(function(e){
		$('.inputErrorDiv').remove();
	});
	$('.textInputError').keydown(function(){
		$(this).css({
			backgroundImage:'url("")'
		});
		$(this).addClass('textInput');
		$(this).removeClass('textInputError');
		$(this).attr({'errorinfo':''});
	});

	$('#continueShopping').click(function(){
		history.back();
	});

	$('#finishOrder').click(function(){
		var url = $(this).attr('href');
		ajax.request({
			url:'customer/plugins/webshop/render/check.php',
			method:'GET',
			params:{
				task:'checkPaymentMethod'
			},
			success:function(response){
				var result = response.responseText;
				if(result != ''){
					result = ajax.decode(result);
					switch(result.success){
						case true:
							document.location.href = url;
						break;
						case false:
							renderErrors(result.errors);
						break;
					}
				} else {
					renderErrors(['Geen antwoord van check.php bij checkPaymentMethod']);
				}
			},
			failure:function(response){
				renderErrors([response.msg]);
			}
		});
	});

	$('.pmInput').change(function(){
		ajax.request({
			url:'customer/plugins/webshop/render/update.php',
			method:'GET',
			params:{
				task:'updatePaymentMethod',
				id:$(this).val()
			},
			success:function(response){
				var result = response.responseText;
				if(result != ''){
					result = ajax.decode(result);
					switch(result.success){
						case true:
							// Doe niets
						break;
						case false:
							renderErrors([result.msg]);
						break;
					}
				} else {
					renderErrors(['Geen antwoord van update.php bij updatePaymentMethod']);
				}
			},
			failure:function(response){
				renderErrors([response.msg]);
			}
		});
	});


	$('#searchInput').focus(function() {
		if(this.value == 'trefwoord...') {
			this.value = '';
		}
	});
	$('#searchInput').blur(function() {
		if(this.value == '') {
			this.value = 'trefwoord...';
		}
	});
	function renderErrors(errors){
		if(errors.length > 0){
			var div = document.createElement('div');
			div.id = 'mask';
			var eDiv = document.createElement('div');
			eDiv.id = 'errors';
			eDiv.title = 'Klik om te sluiten';
			div.appendChild(eDiv);
			var span = document.createElement('span');
			span.id = 'errorHeader';
			eDiv.appendChild(span);
			if(errors.length == 1){
				span.innerHTML = 'Er is een fout gevonden:';
			} else {
				span.innerHTML = 'Er zijn fouten gevonden:';
			}
			var ul = document.createElement('ul');
			eDiv.appendChild(ul);
			for(i = 0; i < errors.length; i++){
				var li = document.createElement('li');
				li.innerHTML = errors[i];
				ul.appendChild(li);
			}
			document.body.appendChild(div);
			init();
		}
	}
	$('.form').find('input,textarea').focus(function(){
		if($(this).val() == $(this).attr('original')){
			$(this).val('');
		}
	});
	$('.form').find('input,textarea').blur(function(){
		if($(this).val() == ''){
			$(this).val($(this).attr('original'));
		}
	});
});

function initAjaxMessage(html){
	var mask = document.createElement('div');
	mask.id = 'mask';
	mask.innerHTML = html;
	document.body.appendChild(mask);
	$('#mask div').first().css({
		marginTop:-(Math.round($('#mask div').first().height()/2))
	});
	$('#mask div').first().animate({opacity:100}, 1000);
}


