$(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);
					});
				}
			}
		}
	});
	$('.accordionContent').hide();
	$('.accordionContent:first').show();
	$('.accordionHeader').click(function() {
		$('.accordionContent:visible').slideUp('slow');
		$('.iconActive:visible').removeClass('iconActive');
		$(this).next().slideDown('slow');
		$(this).find('span').addClass('iconActive');
	});

	var webshop = {};
	webshop.basket = {
		timer:null
	};
	webshop.replace = function(replace){
		for(var i in replace){
			if(typeof replace[i] != 'function'){
				$('#'+i).replaceWith(replace[i]);
			}
		}
		webshop.addBasketEvents();
	}
	
	webshop.addMaskEvents = function(){
		$('#ajaxLayer,#productPopup').click(function(){
			$('#ajaxLayer,#productPopup').remove();
		});
	}

	webshop.addBasketEvents = function(){
		$('[inputData]').focus(function(){
			$(this).select();
		});
		$('[inputData]').keyup(function(){
			if(webshop.basket.timer != null){
				clearTimeout(webshop.basket.timer);
			}
			var input = $(this);
			if(input.val() != ''){
				webshop.basket.timer = setTimeout(function(){
					var value = parseFloat(input.val().replace(',','.'));
					var data = ajax.decode(input.attr('inputData'));
					var error = false;
					if(isNaN(value)){
						error = true;
						value = data.old;
					} else {
						if(data.decimals === false && value%Math.floor(value) > 0){
							error = true;
							value = data.old;
						}
					}
					if(!error){
						data.old = value;
						input.attr('inputData', ajax.encode(data));
						data = {
							id:data.id,
							amount:value,
							add:false,
							task:'updateBasket',
							replace:['smallBasket', 'basket']
						};
						$('#loader_'+data.id).css({
							visibility:'visible'
						});
						$.ajax({
							url:'customer/plugins/webshop/render/basket.php',
							type:'POST',
							data:{
								data:$.JSON.encode(data)
							},
							success:function(result){
								result = $.JSON.decode(result);
								switch(result.success){
									case true:
										if(result.redirect){
											document.location = result.redirect;
											return false;
										}
										if(result.replace){
											webshop.replace(result.replace);
										}
										$('.loadingimg').css({
											visibility:'hidden'
										});
									break;
									default:
										alert(result.msg);
									break;
								}
							}
						});
					}
					input.val(value);
				},500);
			}
		});
		webshop.addMaskEvents();
	}

	$('[orderData]').click(function(){
		var data = ajax.decode($(this).attr('orderData'));
		data.task = 'updateBasket';
		data.replace = [
			'smallBasket'
		];
		data.popup = true;
		ajax.request({
			url:'customer/plugins/webshop/render/basket.php',
			method:'GET',
			hideMask: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;
								return false;
							}
							if(result.replace) {
								webshop.replace(result.replace);
							}
							if(result.popup){
								$(document.body).append(result.popup);
							}
							webshop.addBasketEvents();
						break;
						case false:
							alert(result.msg);
						break;
					}
				} else {
					alert('Geen antwoord van basket.php bij updateBasket');
				}
			},
			failure:function(response){
				alert(response.responseText);
			}
		});
	});

	webshop.addBasketEvents();

	$('#paymentMethods').find('[name=paymentMethod]').click(function(){
		ajax.request({
			url:'customer/plugins/webshop/render/basket.php',
			method:'GET',
			params:{
				data:ajax.encode({
					task:'setPaymentMethod',
					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:
							alert(result.msg);
						break;
					}
				} else {
					alert('Geen antwoord van basket.php bij updateBasket');
				}
			},
			failure:function(response){
				alert(response.responseText);
			}
		});
	});

	$('.finishOrder').click(function(){
		if($('#paymentMethods').length > 0){
			// Betaalmethode controleren
			ajax.request({
				url:'customer/plugins/webshop/render/basket.php',
				method:'GET',
				params:{
					data:ajax.encode({
						task:'checkPaymentMethod'
					})
				},
				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;
									return false;
								}
							break;
							case false:
								alert(result.msg);
							break;
						}
					} else {
						alert('Geen antwoord van basket.php bij updateBasket');
					}
				},
				failure:function(response){
					alert(response.responseText);
				}
			});
			return false;
		}
	});

	$("a[rel=pictures]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}
	});

	$("a[rel=fancybox]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}
	});

	var fcounter = 1;
	$('.flash').each(function(){
		var object = eval('('+$(this).html()+')');
		$(this).html('');
		$(this).attr('id', 'flash_'+fcounter++);
		/*
		swfobject.embedSWF(
			'../../lucasPlayer/LucasPlayer.swf',
			$(this).attr('id'),
			'205',
			'166',
			'10.1.0',
			'../playerProductInstall.swf',
			{youtubeId:object.flash},
			{quality:'high', bgcolor:'#ffffff', allowscriptaccess:'sameDomain', allowfullscreen:true},
			{id:'LucasPlayer', name:'LucasPlayer', align:'middle'}
		);
		*/
	});

	$('.reactionLink').click(function(){
		var w = $(this).parent().find('.reactionAreaWrap');
		var c = w.find('.reactionAreaInner');
		c.css({
			visibility:(w.height()==0?'visible':'hidden')
		});
		w.animate({
			height:(w.height()==0?c.height():0)
		},200);
	});

	$('.reactionIcon').click(function(){
		var w = $(this).parent().parent().parent().find('.reactionAreaWrap');
		var c = w.find('.reactionAreaInner');
		c.css({
			visibility:(w.height()==0?'visible':'hidden')
		});
		w.animate({
			height:(w.height()==0?c.height():0)
		},200);

	});

	$('.reactionDelete').click(function(){
		$.ajax({
			url:'/ajax.php',
			type:'POST',
			data:{
				task:'deleteReaction',
				remove:$(this).attr('commentId')
			},
			success:function(result){
				result = $.JSON.decode(result);
				switch(result.success){
					case true:
						document.location.reload(true);
					break;
					default:
						alert(result.msg);
					break;
				}
			}
		});
	});

	$('.sendReaction').click(function(){
		tinyMCE.triggerSave();
		var area = $(this).parent();
		var data = {
			reactionData:{
				pageId:area.find('.pageId').html(),
				itemId:area.find('.itemId').html(),
				itemType:area.find('.itemType').html(),
				url:area.find('.reactionUrl').html()
			}
		};
		if(area.find('.parentId').length > 0){
			data.reactionData.parentId = area.find('.parentId').html();
		}
		$.ajax({
			url:'/ajax.php',
			type:'POST',
			data:{
				task:'sendReaction',
				reaction:area.find('textarea').val(),
				data:$.JSON.encode(data)
			},
			success:function(result){
				result = $.JSON.decode(result);
				switch(result.success){
					case true:
						document.location.reload(true);
					break;
					default:
						alert(result.msg);
					break;
				}
			}
		});
	});
	$('#openDelivery').click(function(){
		if($('#firstOpen').val() === '1'){
			$('#firstOpen').val('0');
			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_country',		dest:'d_country'},
				{src:'c_phone',			dest:'d_phone'}
			];
			for(var i = 0; i < fields.length; i++){
				var s = $('#'+fields[i].src);
				if(s){
					var d = $('#'+fields[i].dest);
					if(d){
						d.val(s.val());
					}
				}
			}
		}
		$('#delivery').animate({
			height:380
		},500);
	});

	$('#closeDelivery').click(function(){
		$('#delivery').animate({
			height:0
		},500);
	});
	$('#openPassword').click(function(){
		$('#passwordTable').animate({
			height:58
		},500);
	});
	$('#closePassword').click(function(){
		$('#passwordTable').animate({
			height:0
		},500);
	});
	function addCheckboxEvents(){
		$('.checkboxInput').click(function(){
			$(this).addClass('checkboxInputChecked');
			$(this).removeClass('checkboxInput');
			$('#'+$(this).attr('cbid')).attr('checked', true);
			addCheckboxEvents();
		});
		$('.checkboxInputChecked').click(function(){
			$(this).addClass('checkboxInput');
			$(this).removeClass('checkboxInputChecked');
			$('#'+$(this).attr('cbid')).attr('checked', false);
			addCheckboxEvents();
		});
		$('.checkboxInputError').click(function(){
			$(this).addClass('checkboxInputChecked');
			$(this).removeClass('checkboxInputError');
			$('#'+$(this).attr('cbid')).attr('checked', true);
			addCheckboxEvents();
		});
	}
	addCheckboxEvents();
	var submitClicked = false;
	$('.webshopSubmit').click(function(){
		if(submitClicked === false){
			submitClicked = true;
			$.ajax({
				url:'customer/plugins/webshop/render/basket.php',
				type:'POST',
				data:{
					data:$.JSON.encode({
						task:'saveOrder'
					})
				},
				success:function(result){
					result = ajax.decode(result);
					switch(result.success){
						case true:
							if(result.order){
								var formInputs = {
									BPE_Invoice:'id',
									BPE_Amount:'total',
									BPE_Description:'description',
									BPE_Signature2:'signature',
									BPE_Invoicevat:'vat',
									BPE_Customerid:'customerId'
								};
								for(i in formInputs){
									$('[name='+i+']').val(result.order[formInputs[i]]);
								}
								$('#payWindow').submit();
							} else {
								alert('Geen gegevens gevonden voor buckaroo');
							}
						break;
						default:
							alert(result.msg);
						break;
					}
				}
			});
		}
		return false;
	});
	
	
	var pollWait = 0;
	$('.pollBar').each(function() {
		var p = $(this);		
		setTimeout(function() {
			$(p).animate({
				width:$(p).attr('info')+'%'
			}, 500, 'easeOutBounce');
		}, pollWait);
		pollWait += 500;
	});

	$('.mask').css({
		opacity:0.7
	});

	$('.mask,.errors').click(function(){
		$('.mask,.errors').remove();
	});


	$("a[rel=boek]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}
	});

});

function rankingsPush(){
	var url = String(document.referrer);

	// confirm they came from G
	if (url.indexOf ("google.com") !=-1)
	{

	var urlVars = {};
	var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value)
	{
	urlVars[key] = value;
	});

	// Push to GA Custom Variables
	_gaq.push(['_setCustomVar', '1', 'Rankings', urlVars["cd"], 1]);

	}

}
