pageTracker = null;
$(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);
					});
				}
			}
		}
	});

	function activateTab(el){
		var deactivate = $('#mainContent').find('.current').each(function(){
			$(this).animate({opacity:0}, 300, 'linear', function(){
				$(this).removeClass('current');
				$(this).css({visibility:'hidden'});
			})
		});
		$('#'+el.attr('id')).each(function(){
			$(this).css({
				opacity:0,
				visibility:'visible'
			});
			$(this).animate({opacity:1}, 300, 'swing', function(){
				$(this).addClass('current');	
			});
		});

	}
	var mcc = 1;
	$('#mainContent').children().each(function(){
		if(mcc++ == 1){
			$(this).css({
				display:'block'
			});
		}
	});


	$('.tab').click(function(){
		if(!$(this).hasClass('current')){
			var dTab = $(this).parent().find('.current');
			dTab.removeClass('current');
			dTab.addClass('darkgreen');
			dTab.removeClass('green');
			$('#content_'+dTab.attr('id')).css({
				display:'none'
			});
			$(this).addClass('current');
			$(this).addClass('green');
			$(this).removeClass('darkgreen');
			$('#content_'+$(this).attr('id')).css({
				display:'block'
			});
		}
	});

	var navigation = {};
	navigation.hover = '';
	navigation.timer = null;

	// Opzetten
	var d = 1;
	$('.catHover').each(function(){
		var h = 0;
		var counter = 0;
		var rows = [];
		var max = 4;
		var subs = $(this).find('.subNav');
		subs.each(function(){
			h += $(this).height();
			counter++;
		});
		for(var i = 0; i < rows.length; i++){
			h += rows[i];
		}
		var navData = ajax.decode($(this).attr('navData'));
		navData.height = h;
		$(this).attr('navData', ajax.encode(navData));
		$(this).css({
			height:0,
			visibility:'visible'
		});
	});

	navigation.show = function(){
		if(navigation.timer != null){
			clearTimeout(navigation.timer);
		}
		navigation.timer = setTimeout(function(){
			if(navigation.hover != ''){
				$('div[hoverid="'+navigation.hover+'"]').each(function(){
					var navData = ajax.decode($(this).attr('navData'));
					$(this).animate({height:navData.height},200);
				});
			}
			$('.catHover').each(function(){
				var hoverId = $(this).attr('hoverId');
				if(hoverId != navigation.hover){
					var navData = ajax.decode($(this).attr('navData'));
					$(this).animate({top:navData.height+47,height:0},200, 'swing', function(){
						$(this).css({top:47});	
					});
				}
			});
			navigation.timer = null;
		},200);
	}

	$('.catHover,.navItem').mouseenter(function(){
		navigation.hover = $(this).attr('hoverId');
		navigation.show();
	});
	$('.catHover,.navItem').mouseleave(function(){
		navigation.hover = '';
		navigation.show();
	});

	var winkelmand = {};
	winkelmand.timer = null;
	winkelmand.replace = function(replace){
		if(typeof replace == 'object'){
			for(var i in replace){
				if(typeof replace[i] != 'function'){
					if(i != 'popup'){
						$('#'+i).replaceWith(replace[i]);
					} else {
						$(document.body).append(replace[i]);
					}
				}
			}
			init();
		}
	}

	$('[wsData]').css({
		cursor:'pointer'
	});

	$('[wsData]').click(function(){
		var data = ajax.decode($(this).attr('wsData'));
		data.replace = ['basketSmall','popup'];
		data.task = 'updateBasket';
		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:
							winkelmand.replace(result.replace);
						break;
						case false:
							alert(result.msg);
						break;
					}
				} else {
					alert('Geen antwoord van basket.php bij '+data.task);
				}
			},
			failure:function(response){
				alert(response.responseText);
			}
		});
	});

	$('.addButtonList').click(function(){
		var checked = $('[name="productInput[]"]:checked');
		if(checked.length > 0){
			var items = {};
			checked.each(function(){
				var val = $(this).parent().next().find('#addToBasketInput,.subData').first().val();
				items[$(this).val()] = parseFloat(val);
			});
			var data = {
				task:'updateBasket',
				list:items,
				add:true,
				replace:['basketSmall', 'popup']
			};
			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:
								winkelmand.replace(result.replace);
							break;
							case false:
								alert(result.msg);
							break;
						}
					}
				},
				failure:function(response){
					alert(response.responseText);
				}
			});
		} else {
			var mask = $('<div></div>');
			mask.attr('class','mask');
			$(document.body).append(mask);
			var div = $('<div></div>');
			div.attr('id', 'errors');
			div.attr('class', 'errorLarge');
			var ul = $('<ul></ul>');
			var list = ['Geen artikelen geselecteerd om toe te voegen'];
			for(var i = 0; i < list.length; i++){
				var li = $('<li></li>');
				li.html(list[i]);
				ul.append(li);
			}
			div.append(ul);
			$(document.body).append(div);
			init();
		}
	});
	
	function renderErrors(list){
		if(typeof list == 'object'){
			var mask = $('<div></div>');
			mask.attr('class','mask');
			$(document.body).append(mask);
			var div = $('<div></div>');
			div.attr('id', 'errors');
			var ul = $('<ul></ul>');
			for(var i = 0; i < list.length; i++){
				var li = $('<li></li>');
				li.html(list[i]);
				ul.append(li);
			}
			div.append(ul);
			$(document.body).append(div);
			init();
		}
	}


	var input = {};
	input.timer = null;
	$('#addToBasketInput,.subData').keyup(function(){
		var el = $(this);
		if(input.timer != null){
			clearTimeout(input.timer);
		}
		input.timer = setTimeout(function(){
			var data = ajax.decode(el.attr('inputData'));
			var val = el.val().replace(',', '.');
			if(val != ''){
				var val = parseFloat(val);
				if(val < 0){
					val = val * -1;
				}
				if(isNaN(val)){
					val = data.old;
				}
				if(data.decimals === false && val%1 > 0){
					val = Math.floor(val);
				} else {
					val = ''+val;
					val = val.replace('.', ',');
				}
				data.old = val;
				el.attr('inputData', ajax.encode(data));
				el.val(val);
				var b =	$('#addButton');
				if(b.length > 0){
					var wsData = ajax.decode(b.attr('wsData'));
					wsData.amount = val;
					b.attr('wsData', ajax.encode(wsData));
				}
			}
		}, 500);
	});

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

	$('#openPassword').click(function(){
		$('#passwordTable').animate({
			height:50
		},300);
	});

	$('#closePassword').click(function(){
		$('#passwordTable').animate({
			height:0
		},300);
	});

	$('#openDelivery').click(function(){
		var fp = $('#firstOpen');
		if(fp.val() === '1'){
			var fields = [
				{src:'c_initials',		dest:'d_initials'},
				{src:'c_middleName',	dest:'d_middleName'},
				{src:'c_lastName',		dest:'d_lastName'},
				{src:'c_email',			dest:'d_email'},
				{src:'c_street',		dest:'d_street'},
				{src:'c_houseNumber',	dest:'d_houseNumber'},
				{src:'c_zipcode',		dest:'d_zipcode'},
				{src:'c_city',			dest:'d_city'},
				{src:'c_country',		dest:'d_country'}
			];
			for(var i = 0; i < fields.length; i++){
				$('#'+fields[i].dest).val($('#'+fields[i].src).val());
			}
			fp.val(0);
		}
		$('#delivery').animate({
			height:360
		},300);
	});

	$('#closeDelivery').click(function(){
		$('#delivery').animate({
			height:0
		},300);
	});

	$('.checkboxInput,.checkboxInputError,.checkboxInputChecked').click(function(){
		var el = $('#'+$(this).attr('cbid'));
		if(el.attr('checked')){
			$(this).removeClass('checkboxInputChecked');
			$(this).addClass('checkboxInput');
		} else {
			$(this).removeClass('checkboxInputError');
			$(this).addClass('checkboxInputChecked');
		}
		el.attr('checked', !el.attr('checked'));
	});

	$('.paymentMethodInput').click(function(){
		var data = {
			task:'setPaymentMethod',
			id:$(this).val()
		};
		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:
							// Doe niets
						break;
						case false:
							alert(result.msg);
						break;
					}
				} else {
					alert('Geen antwoord van basket.php bij setPaymentMethod');
				}
			},
			failure:function(response){
				alert(response.responseText);
			}
		});
	});

	$('#logout').click(function(){
		data = {
			task:'logout',
			replace:['loginOverview']
		};
		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:
							var reload = ['orderbevestiging.html', 'winkelmand.html'];
							for(var i = 0; i < reload.length; i++){
								if(document.location.href.indexOf(reload[i])!= -1){
									document.location.reload(true);
								}
							}
							winkelmand.replace(result.replace);
						break;
						case false:
							alert(result.msg);
						break;
					}
				} else {
					alert('Geen antwoord van basket.php bij logout');
				}
			},
			failure:function(response){
				alert(response.responseText);
			}
		});
		return false;
	});

	$('.finishOrder').click(function(){
		var data = {
			task:'checkPaymentMethod'
		};
		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:
							// Order opslaan en mail versturen
							data = {
								task:'saveOrder'
							};
							ajax.request({
								url:'customer/plugins/webshop/render/basket.php',
								method:'GET',
								mask:false,
								params:{
									data:ajax.encode(data)
								},
								success:function(response){
									var result = response.responseText;
									if(result != ''){
										//alert(result);
										result = ajax.decode(result);
										switch(result.success){
											case true:
												document.location = 'http://www.horsefriend.nl/order_verstuurd/order'+result.orderId+'.html';
											break;
											case false:
												alert(result.msg);
											break;
										}
									} else {
										alert('Geen antwoord van basket.php bij saveOrder');
									}
								},
								failure:function(response){
									alert(response.responseText);
								}
							});
						break;
						case false:
							alert(result.msg);
						break;
					}
				} else {
					alert('Geen antwoord van basket.php bij checkPaymentMethod');
				}
			},
			failure:function(response){
				alert(response.responseText);
			}
		});
	});

	$('#mainNav').find('.subNavItem,.subSubNavItem,.subSubNavItemChild').mouseover(function(){
		if($(this).hasClass('subNavItem')){
			$(this).addClass('subNavItemHover');
		} else if($(this).hasClass('subSubNavItem')){
			$(this).addClass('subSubNavItemHover');
		} else {
			$(this).addClass('subSubNavItemChildHover');
		}
	});

	$('#mainNav').find('.subNavItem,.subSubNavItem,.subSubNavItemChild').mouseout(function(){
		if($(this).hasClass('subNavItemHover')){
			$(this).removeClass('subNavItemHover');
		}
		if($(this).hasClass('subSubNavItemHover')){
			$(this).removeClass('subSubNavItemHover');
		}
		if($(this).hasClass('subSubNavItemChildHover')){
			$(this).removeClass('subSubNavItemChildHover');
		}
	});
	/*
	$('.zoomIn').click(function(){
		var href = $(this).attr('href');
		var anchor = $(this).prev();
		var origHref = anchor.attr('href');
		anchor.attr('href', href);
		fb.start(anchor.get(0));
		var link = $('<a href="'+origHref+'"></a>');
		link.html(anchor.html());
		anchor.replaceWith(link);
		return false;
	});
	*/

	function init(){
		$('.removeProduct').click(function(){
			var data = ajax.decode($(this).attr('removeData'));
			data.task = 'updateBasket';
			data.amount = 0;
			data.autoAdd = false;
			data.replace = ['winkelmandje', 'basketSmall'];
			ajax.request({
				url:'customer/plugins/webshop/render/basket.php',
				method:'GET',
				mask:false,
				params:{
					data:ajax.encode(data)
				},
				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 {
									winkelmand.replace(result.replace);
								}
							break;
							case false:
								alert(result.msg);
							break;
						}
					} else {
						alert('Geen antwoord van basket.php bij '+data.task);
					}
				},
				failure:function(response){
					alert(response.responseText);
				}
			});
		});
		$('.productInput').keyup(function(){
			var el = $(this);
			if(winkelmand.timer != null){
				clearTimeout(winkelmand.timer);
			}
			winkelmand.timer = setTimeout(function(){
				var data = ajax.decode(el.attr('inputData'));
				var val = el.val().replace(',', '.');
				if(val != ''){
					var val = parseFloat(val);
					if(val < 0){
						val = val * -1;
					}
					if(isNaN(val)){
						val = data.old;
					}
					if(data.decimals === false && val%1 > 0){
						val = Math.floor(val);
					} else {
						val = ''+val;
						val = val.replace('.', ',');
					}
					data.old = val;
					el.attr('inputData', ajax.encode(data));
					el.val(val);
					var sendData = {
						replace:['winkelmandje'],
						amount:val,
						id:data.id,
						autoAdd:false,
						task:'updateBasket'
					}
					data.old = null;
					$('#loader_'+data.id).css({
						visibility:'visible'
					});
					ajax.request({
						url:'customer/plugins/webshop/render/basket.php',
						method:'GET',
						mask:false,
						params:{
							data:ajax.encode(sendData)
						},
						success:function(response){
							var result = response.responseText;
							if(result != ''){
								result = ajax.decode(result);
								switch(result.success){
									case true:
										winkelmand.replace(result.replace);
									break;
									case false:
										alert(result.msg);
									break;
								}
							} else {
								alert('Geen antwoord van basket.php bij '+data.task);
							}
						},
						failure:function(response){
							alert(response.responseText);
						}
					});
				}
			},500);
		});
		var list = ['.mask', '#productPopup', '#errors', '.errors'];
		for(var i = 0; i < list.length; i++){
			$(list[i]).click(function(){
				if($('#errors').length > 0){
					var inputs = $('.checkbox');
					if(inputs.length > 0){
						var to = 200;
						var loops = 3*inputs.length;
						function attention(el){
							el.css({
								background:'#005231'
							});
							setTimeout(function(){
								el.css({
									background:'#ffffff'
								});
								if(--loops > 1){
									setTimeout(function(){
										attention(el);
									},to);
								}
							},to);
						}
						inputs.each(function(){
							attention($(this));
						});
					}
				}
				$(list.join(',')).remove();
			});
		}
		$('.checkboxInput').click(function(){
			$(this).addClass('checkboxInputChecked');
			$(this).removeClass('checkboxInput');
			$('#'+$(this).attr('CBID')).attr('checked',true);
			init();
		});

		$('.checkboxInputError').click(function(){
			$(this).addClass('checkboxInputChecked');
			$(this).removeClass('checkboxInputError');
			$(this).removeAttr('errorInfo');
			$('#'+$(this).attr('CBID')).attr('checked',true);
			init();
		});

		$('.checkboxInputChecked').click(function(){
			$(this).addClass('checkboxInput');
			$(this).removeClass('checkboxInputChecked');
			$('#'+$(this).attr('CBID')).attr('checked',false);
			init();
		});
	}
	init();

	var hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
	function rgb2hex(rgb) {
		if(rgb){
			if(rgb.indexOf('#') == -1){
				rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
				if(rgb != null){
					return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
				}
			} else {
				return rgb;
			}
		}
	}
	function hex(x) {
		return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
	}

	$('[hover]').mouseover(function(){
		var current = $(this).css('background-color');
		var hover = rgb2hex($(this).attr('hover'));
		$(this).css({
			backgroundColor:hover
		});
		$(this).attr('hover', current);
	});

	$('[hover]').mouseout(function(){
		var current = $(this).css('background-color');
		var hover = $(this).attr('hover');
		$(this).css({
			backgroundColor:hover
		});
		$(this).attr('hover', current);
	});
	var uppercaseList = [
		'#c_initials',
		'#d_initials',
		'#c_lastName',
		'#d_lastName',
		'#c_street',
		'#d_street',
		'#c_city',
		'#d_city'
	];

	$(uppercaseList.join(',')).keyup(function(){
		var value = $(this).val();
		var newValue = ucfirst(value);
		if(value != newValue){
			$(this).val(newValue);
		}
	});
	$('#c_zipcode,#d_zipcode').keyup(function(){
		var value = $(this).val();
		var newValue = value.toUpperCase();
		if(value != newValue){
			$(this).val(newValue);
		}
	});
	$('#c_phone,#d_phone').keyup(function(){
		var value = $(this).val();
		var valid = '1234567890-/+() ';
		var valSplit = value.split('');
		var newValue = '';
		for(var i = 0; i < valSplit.length; i++){
			var pos = valid.indexOf(valSplit[i]);
			if(pos !== -1){
				newValue += valSplit[i];
			}
		}
		if(newValue != value){
			$(this).val(newValue);
		}
	});

	var pt = null;
	function getTracker(){
		if(typeof _gat == 'object'){
			pt = _gat._createTracker('UA-8452791-1');
			var items = [
				{id:'#name',		action:'blur',	href:'/nl/contact/achternaam'},
				{id:'#phone',		action:'blur',	href:'/nl/contact/telefoon'},
				{id:'#email',		action:'blur',	href:'/nl/contact/email'},
				{id:'#remarks',		action:'blur',	href:'/nl/contact/opmerking'},
				{id:'#contactSend',	action:'found',	href:'/nl/contact/voltooid'}
			];
			for(var i = 0; i < items.length; i++){
				switch(items[i].action){
					case 'blur':
						var el = $(items[i].id);
						el.attr('rel', items[i].href);
						$(items[i].id).blur(function(){
							pt._trackPageview($(this).attr('rel'));
						});
					break;
					case 'found':
						$(items[i].id).each(function(){
							pt._trackPageview(items[i].href);
						});
					break;
				}
			}
		} else {
			setTimeout(function(){
				getTracker();
			},100);
		}
	}
	getTracker();

	$('#orderComment').blur(function(){
		var comment = $(this).val();
		var data = {
			task:'updateComment',
			comment:comment
		}
		ajax.request({
			url:'customer/plugins/webshop/render/basket.php',
			method:'GET',
			params:{
				data:ajax.encode(data)
			}
		});
	});
});
